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
cjstehno/ersatz
ersatz/src/test/java/io/github/cjstehno/ersatz/expectations/ErsatzServerDeleteExpectationsTest.java
[ "public class ErsatzServer implements Closeable {\r\n\r\n private final UnderlyingServer underlyingServer;\r\n private final ServerConfigImpl serverConfig;\r\n\r\n /**\r\n * Creates a new Ersatz server instance with empty (default) configuration.\r\n */\r\n public ErsatzServer() {\r\n this.serverConfig = new ServerConfigImpl();\r\n this.serverConfig.setStarter(this::start);\r\n\r\n this.underlyingServer = new UndertowUnderlyingServer(serverConfig);\r\n }\r\n\r\n /**\r\n * Creates a new Ersatz server instance configured by the provided <code>Consumer</code>, which will have an instance of <code>ServerConfig</code>\r\n * passed into it for server configuration.\r\n *\r\n * @param consumer the configuration consumer\r\n */\r\n public ErsatzServer(final Consumer<ServerConfig> consumer) {\r\n this();\r\n if (consumer != null) {\r\n consumer.accept(serverConfig);\r\n }\r\n }\r\n\r\n /**\r\n * Used to retrieve the port where the HTTP server is running.\r\n *\r\n * @return the HTTP port\r\n */\r\n public int getHttpPort() {\r\n return underlyingServer.getActualHttpPort();\r\n }\r\n\r\n /**\r\n * Used to retrieve the port where the HTTPS server is running.\r\n *\r\n * @return the HTTPS port\r\n */\r\n public int getHttpsPort() {\r\n return underlyingServer.getActualHttpsPort();\r\n }\r\n\r\n /**\r\n * Used to retrieve whether HTTPS is enabled or not.\r\n *\r\n * @return true if HTTPS is enabled\r\n */\r\n public boolean isHttpsEnabled() {\r\n return serverConfig.isHttpsEnabled();\r\n }\r\n\r\n /**\r\n * Used to retrieve the full URL of the HTTP server.\r\n *\r\n * @return the full URL of the HTTP server\r\n */\r\n public String getHttpUrl() {\r\n return getUrl(\"http\", getHttpPort());\r\n }\r\n\r\n /**\r\n * Used to retrieve the full URL of the HTTPS server.\r\n *\r\n * @return the full URL of the HTTP server\r\n */\r\n public String getHttpsUrl() {\r\n return getUrl(\"https\", getHttpsPort());\r\n }\r\n\r\n private String getUrl(final String prefix, final int port) {\r\n if (port > 0) {\r\n return prefix + \"://localhost:\" + port;\r\n } else {\r\n throw new IllegalStateException(\"The port (\" + port + \") is invalid: Has the server been started?\");\r\n }\r\n }\r\n\r\n /**\r\n * A helper method which may be used to append the given path to the server HTTP url.\r\n *\r\n * @param path the path to be applied\r\n * @return the resulting URL\r\n */\r\n public String httpUrl(final String path) {\r\n return getHttpUrl() + path;\r\n }\r\n\r\n /**\r\n * A helper method which may be used to append the given path to the server HTTPS url.\r\n *\r\n * @param path the path to be applied\r\n * @return the resulting URL\r\n */\r\n public String httpsUrl(final String path) {\r\n return getHttpsUrl() + path;\r\n }\r\n\r\n /**\r\n * Used to configure HTTP expectations on the server; the provided <code>Consumer&lt;Expectations&gt;</code> implementation will have an active\r\n * <code>Expectations</code> object passed into it for configuring server interaction expectations.\r\n * <p>\r\n * Calling this method when auto-start is enabled will start the server.\r\n *\r\n * @param expects the <code>Consumer&lt;Expectations&gt;</code> instance to perform the configuration\r\n * @return a reference to this server\r\n */\r\n public ErsatzServer expectations(final Consumer<Expectations> expects) {\r\n serverConfig.expectations(expects);\r\n\r\n if (serverConfig.isAutoStartEnabled()) {\r\n underlyingServer.start();\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * An alternate means of starting the expectation chain.\r\n * <p>\r\n * Calling this method when auto-start is enabled will <b>NOT</b> start the server. Use one of the other expectation configuration method if\r\n * auto-start functionality is desired.\r\n *\r\n * @return the reference to the Expectation configuration object\r\n */\r\n public Expectations expects() {\r\n return serverConfig.expects();\r\n }\r\n\r\n /**\r\n * Used to specify the server request timeout property value on the server.\r\n * <p>\r\n * The IDLE_TIMEOUT, NO_REQUEST_TIMEOUT, REQUEST_PARSE_TIMEOUT, READ_TIMEOUT and WRITE_TIMEOUT are all configured to the same specified\r\n * value.\r\n *\r\n * @param value the timeout value\r\n * @param units the units the timeout is specified with\r\n * @return a reference to the server being configured\r\n */\r\n public ServerConfig timeout(final int value, final TimeUnit units) {\r\n return serverConfig.timeout(value, units);\r\n }\r\n\r\n /**\r\n * Used to specify the server request timeout property value on the server (in seconds).\r\n * <p>\r\n * The IDLE_TIMEOUT, NO_REQUEST_TIMEOUT, REQUEST_PARSE_TIMEOUT, READ_TIMEOUT and WRITE_TIMEOUT are all configured to the same specified\r\n * value.\r\n *\r\n * @param value the timeout value\r\n * @return a reference to the server being configured\r\n */\r\n public ServerConfig timeout(final int value) {\r\n return timeout(value, SECONDS);\r\n }\r\n\r\n /**\r\n * Used to start the HTTP server for test interactions. This method should be called after configuration of expectations and before the test\r\n * interactions are executed against the server.\r\n *\r\n * @return a reference to this server\r\n */\r\n public ErsatzServer start() {\r\n underlyingServer.start();\r\n return this;\r\n }\r\n\r\n /**\r\n * Clears all configured expectations from the server. Does not affect global encoders or decoders.\r\n */\r\n public void clearExpectations() {\r\n serverConfig.clearExpectations();\r\n }\r\n\r\n /**\r\n * Used to stop the HTTP server. The server may be restarted after it has been stopped.\r\n */\r\n public void stop() {\r\n underlyingServer.stop();\r\n }\r\n\r\n /**\r\n * An alias to the <code>stop()</code> method.\r\n */\r\n @Override\r\n public void close() {\r\n stop();\r\n }\r\n\r\n /**\r\n * Used to verify that all of the expected request interactions were called the appropriate number of times. This method should be called after\r\n * all test interactions have been performed. This is an optional step since generally you will also be receiving the expected response back\r\n * from the server; however, this verification step can come in handy when simply needing to know that a request is actually called or not.\r\n *\r\n * @param timeout the timeout value\r\n * @param unit the timeout unit\r\n * @return <code>true</code> if all call criteria were met during test execution.\r\n */\r\n public boolean verify(final long timeout, final TimeUnit unit) {\r\n return serverConfig.getExpectations().verify(timeout, unit);\r\n }\r\n\r\n /**\r\n * Used to verify that all of the expected request interactions were called the appropriate number of times. This method should be called after\r\n * all test interactions have been performed. This is an optional step since generally you will also be receiving the expected response back\r\n * from the server; however, this verification step can come in handy when simply needing to know that a request is actually called or not.\r\n *\r\n * @param timeout the timeout value (in seconds)\r\n * @return <code>true</code> if all call criteria were met during test execution.\r\n */\r\n public boolean verify(final long timeout) {\r\n return verify(timeout, SECONDS);\r\n }\r\n\r\n /**\r\n * Used to verify that all of the expected request interactions were called the appropriate number of times. This method should be called after\r\n * all test interactions have been performed. This is an optional step since generally you will also be receiving the expected response back\r\n * from the server; however, this verification step can come in handy when simply needing to know that a request is actually called or not.\r\n *\r\n * @return <code>true</code> if all call criteria were met during test execution.\r\n */\r\n public boolean verify() {\r\n return verify(1, SECONDS);\r\n }\r\n}\r", "public interface ServerConfig {\r\n\r\n /**\r\n * Used to control the enabled/disabled state of HTTPS on the server. By default HTTPS is disabled.\r\n *\r\n * @param enabled whether or not HTTPS support is enabled\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig https(boolean enabled);\r\n\r\n /**\r\n * Used to enabled HTTPS on the server. By default HTTPS is disabled.\r\n *\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig https();\r\n\r\n /**\r\n * Used to enable/disable the auto-start feature, which will start the server after any call to either of the <code>expectations</code>\r\n * configuration methods. With this setting enabled, any other calls to the <code>start()</code> method are ignored. Further configuration is\r\n * allowed.\r\n * <p>\r\n * Auto-start is enabled by default.\r\n *\r\n * @param enabled whether or not auto-start is enabled\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig autoStart(boolean enabled);\r\n\r\n /**\r\n * Used to specify the server request timeout property value on the server.\r\n *\r\n * @param value the timeout value\r\n * @param units the units the timeout is specified with\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig timeout(int value, TimeUnit units);\r\n\r\n /**\r\n * Used to specify the server request timeout property value on the server, in seconds.\r\n *\r\n * @param value the timeout value\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig timeout(int value);\r\n\r\n /**\r\n * Causes the mismatched request reports to be generated as console output, rather than only in the logging.\r\n *\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig reportToConsole();\r\n\r\n /**\r\n * Used to toggle the console output of mismatched request reports. By default they are only rendered in the logging. A value of <code>true</code>\r\n * will cause the report to be output on the console as well.\r\n *\r\n * @param toConsole whether or not the report should also be written to the console\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig reportToConsole(boolean toConsole);\r\n\r\n /**\r\n * Allows configuration of an external HTTPS keystore with the given location and password. By default, if this is not specified an internally\r\n * provided keystore will be used for HTTPS certification. See the User Guide for details about configuring your own keystore.\r\n *\r\n * @param location the URL of the keystore file\r\n * @param password the keystore file password\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig keystore(URL location, String password);\r\n\r\n /**\r\n * Allows configuration of an external HTTPS keystore with the given location (using the default password \"ersatz\"). By default, if this is not\r\n * specified an internally provided keystore will be used for HTTPS certification. See the User Guide for details about configuring your own\r\n * keystore.\r\n *\r\n * @param location the URL of the keystore file\r\n * @return a reference to the server being configured\r\n */\r\n ServerConfig keystore(URL location);\r\n\r\n /**\r\n * Used to configure HTTP expectations on the server; the provided <code>Consumer&lt;Expectations&gt;</code> implementation will have an active\r\n * <code>Expectations</code> object passed into it for configuring server interaction expectations.\r\n *\r\n * If auto-start is enabled (default) the server will be started after the expectations are applied.\r\n *\r\n * @param expects the <code>Consumer&lt;Expectations&gt;</code> instance to perform the configuration\r\n * @return a reference to this server\r\n */\r\n ServerConfig expectations(final Consumer<Expectations> expects);\r\n\r\n /**\r\n * An alternate means of starting the expectation chain.\r\n *\r\n * @return the reference to the Expectation configuration object\r\n */\r\n Expectations expects();\r\n\r\n /**\r\n * Configures the given request content decoder for the specified request content-type. The decoder will be configured globally and used if no\r\n * overriding decoder is provided during expectation configuration.\r\n *\r\n * @param contentType the request content-type\r\n * @param decoder the request content decoder\r\n * @return the reference to the server configuration\r\n */\r\n ServerConfig decoder(final String contentType, final BiFunction<byte[], DecodingContext, Object> decoder);\r\n\r\n /**\r\n * Configures the given request content decoder for the specified request content-type. The decoder will be configured globally and used if no\r\n * overriding decoder is provided during expectation configuration.\r\n *\r\n * @param contentType the request content-type\r\n * @param decoder the request content decoder\r\n * @return the reference to the server configuration\r\n */\r\n ServerConfig decoder(final ContentType contentType, final BiFunction<byte[], DecodingContext, Object> decoder);\r\n\r\n /**\r\n * Registers a global response body encoder.\r\n * <p>\r\n * param contentType the response content-type to be encoded\r\n *\r\n * @param contentType the response content type to be encoded\r\n * @param objectType the response object type to be encoded\r\n * @param encoder the encoder function\r\n * @return a reference to this server configuration\r\n */\r\n ServerConfig encoder(String contentType, Class objectType, Function<Object, byte[]> encoder);\r\n\r\n /**\r\n * Registers a global response body encoder.\r\n * <p>\r\n * param contentType the response content-type to be encoded\r\n *\r\n * @param contentType the response content type to be encoded\r\n * @param objectType the response object type to be encoded\r\n * @param encoder the encoder function\r\n * @return a reference to this server configuration\r\n */\r\n default ServerConfig encoder(ContentType contentType, Class objectType, Function<Object, byte[]> encoder) {\r\n return encoder(contentType.getValue(), objectType, encoder);\r\n }\r\n\r\n /**\r\n * Allows the specific configuration of the HTTP server port. The default ephemeral port should be used in most cases since\r\n * specifying the port will negate the ability to run tests in parallel and will also allow possible collisions with\r\n * other running servers on the host.\r\n * <p>\r\n * Do NOT specify this setting unless you really need to.\r\n *\r\n * @param value the desired HTTP port\r\n * @return a reference to this server configuration\r\n */\r\n ServerConfig httpPort(int value);\r\n\r\n /**\r\n * Allows the specific configuration of the HTTPS server port. The default ephemeral port should be used in most cases since\r\n * specifying the port will negate the ability to run tests in parallel and will also allow possible collisions with\r\n * other running servers on the host.\r\n * <p>\r\n * Do NOT specify this setting unless you really need to.\r\n *\r\n * @param value the desired HTTPS port\r\n * @return a reference to this server configuration\r\n */\r\n ServerConfig httpsPort(int value);\r\n\r\n /**\r\n * Causes the full response content to be rendered in the server log message (if true) for the cases where the\r\n * response content is a renderable textual response. If false (or binary response) only the number of bytes and\r\n * content type will be rendered for the response.\r\n *\r\n * @param value whether or not to enable logging of response content (false by default)\r\n * @return a reference to this server configuration.\r\n */\r\n ServerConfig logResponseContent(final boolean value);\r\n\r\n /**\r\n * Causes the full response content to be rendered in the server log message for the cases where the response\r\n * content is a renderable textual response. If false (or binary response) only the number of bytes and content type\r\n * will be rendered for the response.\r\n *\r\n * @return a reference to this server configuration.\r\n */\r\n default ServerConfig logResponseContent() {\r\n return logResponseContent(true);\r\n }\r\n}\r", "public class ErsatzServerExtension implements BeforeEachCallback, AfterEachCallback {\r\n\r\n @Override public void beforeEach(final ExtensionContext context) throws Exception {\r\n findInstance(context.getRequiredTestInstance(), true).start();\r\n }\r\n\r\n @Override public void afterEach(final ExtensionContext context) throws Exception {\r\n val ersatzInstance = findInstance(context.getRequiredTestInstance(), false);\r\n if (ersatzInstance != null) {\r\n ersatzInstance.close();\r\n ersatzInstance.clearExpectations();\r\n }\r\n }\r\n\r\n private static ErsatzServer findInstance(final Object testInstance, final boolean create) throws Exception {\r\n try {\r\n val field = findField(testInstance);\r\n Object instance = field.get(testInstance);\r\n\r\n if (instance == null && create) {\r\n instance = field.getType().getDeclaredConstructor().newInstance();\r\n field.set(testInstance, instance);\r\n }\r\n\r\n return (ErsatzServer) instance;\r\n\r\n } catch (Exception throwable) {\r\n throw new Exception(throwable);\r\n }\r\n }\r\n\r\n private static Field findField(final Object testInstance) throws Exception {\r\n val field = stream(testInstance.getClass().getDeclaredFields())\r\n .filter(f -> f.getType().getSimpleName().endsWith(\"ErsatzServer\"))\r\n .findFirst()\r\n .orElseThrow((Supplier<Exception>) () -> new IllegalArgumentException(\"An ErsatzServer field must be specified.\"));\r\n\r\n field.setAccessible(true);\r\n return field;\r\n }\r\n}", "public class HttpClientExtension implements BeforeEachCallback {\n\n @Override public void beforeEach(final ExtensionContext context) throws Exception {\n val testInstance = context.getRequiredTestInstance();\n\n val server = findInstance(testInstance).start();\n\n val https = server.isHttpsEnabled();\n val client = new Client(server.getHttpUrl(), https ? server.getHttpsUrl() : server.getHttpUrl(), https);\n findField(testInstance, \"Client\").set(testInstance, client);\n }\n\n private static ErsatzServer findInstance(final Object testInstance) throws Exception {\n return (ErsatzServer) findField(testInstance, \"ErsatzServer\").get(testInstance);\n }\n\n private static Field findField(final Object testInstance, final String type) throws Exception {\n val field = stream(testInstance.getClass().getDeclaredFields())\n .filter(f -> f.getType().getSimpleName().endsWith(type))\n .findFirst()\n .orElseThrow(() -> new IllegalArgumentException(\"A field of type \" + type + \" must be specified.\"));\n field.setAccessible(true);\n\n return field;\n }\n\n /**\n * The HTTP client wrapper used by the HttpClientExtension. It may be used outside the extension.\n */\n public static class Client {\n\n private final String httpUrl;\n private final String httpsUrl;\n private final OkHttpClient client;\n\n public Client(final String httpUrl, final String httpsUrl, final boolean httpsEnabled) throws Exception {\n this.httpUrl = httpUrl;\n this.httpsUrl = httpsUrl;\n\n client = configureHttps(\n new OkHttpClient.Builder().cookieJar(new InMemoryCookieJar()),\n httpsEnabled\n ).build();\n }\n\n public Response get(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).get();\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response get(final String path, final Consumer<Request.Builder> config) throws IOException {\n return get(path, config, false);\n }\n\n public Response get(final String path, final boolean https) throws IOException {\n return get(path, null, https);\n }\n\n public Response get(final String path) throws IOException {\n return get(path, null, false);\n }\n\n public CompletableFuture<Response> aget(final String path, final Consumer<Request.Builder> config, final boolean https) {\n return supplyAsync(() -> {\n try {\n return get(path, config, https);\n } catch (IOException io) {\n throw new IllegalArgumentException(io.getMessage());\n }\n });\n }\n\n public CompletableFuture<Response> aget(final String path) {\n return aget(path, null, false);\n }\n\n public Response head(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).head();\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response head(final String path, final Consumer<Request.Builder> config) throws IOException {\n return head(path, config, false);\n }\n\n public Response head(final String path, final boolean https) throws IOException {\n return head(path, null, https);\n }\n\n public Response head(final String path) throws IOException {\n return head(path, null, false);\n }\n\n public Response delete(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).delete();\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response delete(final String path, final Consumer<Request.Builder> config) throws IOException {\n return delete(path, config, false);\n }\n\n public Response delete(final String path, final boolean https) throws IOException {\n return delete(path, null, https);\n }\n\n public Response delete(final String path) throws IOException {\n return delete(path, null, false);\n }\n\n public Response trace(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).method(\"TRACE\", null);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response options(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).method(\"OPTIONS\", null);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response post(final String path, final Consumer<Request.Builder> config, final RequestBody body, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).post(body);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response post(final String path, final Consumer<Request.Builder> config, final RequestBody body) throws IOException {\n return post(path, config, body, false);\n }\n\n public Response post(final String path, final RequestBody body, final boolean https) throws IOException {\n return post(path, null, body, https);\n }\n\n public Response post(final String path, final RequestBody body) throws IOException {\n return post(path, null, body, false);\n }\n\n public Response put(final String path, final Consumer<Request.Builder> config, final RequestBody body, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).put(body);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response put(final String path, final Consumer<Request.Builder> config, final RequestBody body) throws IOException {\n return put(path, config, body, false);\n }\n\n public Response put(final String path, final RequestBody body, final boolean https) throws IOException {\n return put(path, null, body, https);\n }\n\n public Response put(final String path, final RequestBody body) throws IOException {\n return put(path, null, body, false);\n }\n\n public Response patch(final String path, final Consumer<Request.Builder> config, final RequestBody body, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).patch(body);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response patch(final String path, final Consumer<Request.Builder> config, final RequestBody body) throws IOException {\n return patch(path, config, body, false);\n }\n\n public Response patch(final String path, final RequestBody body, final boolean https) throws IOException {\n return patch(path, null, body, https);\n }\n\n public Response patch(final String path, final RequestBody body) throws IOException {\n return patch(path, null, body, false);\n }\n\n public static Request.Builder basicAuthHeader(final Request.Builder builder, final String user, final String pass) {\n return builder.header(AUTHORIZATION_HEADER, header(user, pass));\n }\n\n private static OkHttpClient.Builder configureHttps(final OkHttpClient.Builder builder, final boolean enabled) throws KeyManagementException, NoSuchAlgorithmException {\n if (enabled) {\n // Create a trust manager that does not validate certificate chains\n final var trustAllCerts = new TrustManager[]{\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n }\n };\n\n // Install the all-trusting trust manager\n val sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new SecureRandom());\n\n // Create an ssl socket factory with our all-trusting manager\n val sslSocketFactory = sslContext.getSocketFactory();\n\n builder.sslSocketFactory(\n sslSocketFactory,\n (X509TrustManager) trustAllCerts[0]\n )\n .hostnameVerifier((s, sslSession) -> true);\n }\n\n return builder;\n }\n }\n}", "static void verify(final ErsatzServer server) {\n assertTrue(server.verify());\n}", "static Request basicAuth(final Request request, final String userame, final String password) {\n return request.header(AUTHORIZATION_HEADER, header(userame, password));\n}", "public static Request.Builder basicAuthHeader(final Request.Builder builder, final String user, final String pass) {\n return builder.header(AUTHORIZATION_HEADER, header(user, pass));\n}" ]
import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; import io.github.cjstehno.ersatz.ErsatzServer; import io.github.cjstehno.ersatz.cfg.ServerConfig; import io.github.cjstehno.ersatz.junit.ErsatzServerExtension; import io.github.cjstehno.ersatz.util.HttpClientExtension; import lombok.val; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.util.List; import static io.github.cjstehno.ersatz.TestAssertions.verify; import static io.github.cjstehno.ersatz.util.BasicAuth.basicAuth; import static io.github.cjstehno.ersatz.util.HttpClientExtension.Client.basicAuthHeader;
/** * Copyright (C) 2022 Christopher J. Stehno * * 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 io.github.cjstehno.ersatz.expectations; @ExtendWith({ErsatzServerExtension.class, HttpClientExtension.class}) public class ErsatzServerDeleteExpectationsTest { private final ErsatzServer server = new ErsatzServer(ServerConfig::https); @SuppressWarnings("unused") private HttpClientExtension.Client client; @ParameterizedTest(name = "[{index}] path only: https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttps") void withPath(final boolean https) throws IOException { server.expectations(expect -> { expect.DELETE("/something").secure(https).called(1).responds().code(200); }); assertEquals(200, client.delete("/something", https).code()); verify(server); } @ParameterizedTest(name = "[{index}] path and consumer: https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttpsWithContent") void withPathAndConsumer(final boolean https) throws IOException { server.expects().DELETE("/something", req -> { req.secure(https).called(1); req.responds().code(200); }); assertEquals(200, client.delete("/something", https).code()); verify(server); } @ParameterizedTest(name = "[{index}] path matcher: https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttpsWithContent") void withPathMatcher(final boolean https, final String responseText) throws IOException { server.expects().DELETE(startsWith("/loader/")).secure(https).called(1).responds().code(200); assertEquals(200, client.delete("/loader/something", https).code()); verify(server); } @ParameterizedTest(name = "[{index}] path matcher and consumer: https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttpsWithContent") void withPathMatcherAndConsumer(final boolean https, final String responseText) throws IOException { server.expectations(expect -> { expect.DELETE(startsWith("/loader/"), req -> { req.secure(https); req.called(1); req.responder(res -> res.code(200)); }); }); assertEquals(200, client.delete("/loader/something", https).code()); verify(server); } @ParameterizedTest(name = "[{index}] path and consumer (with response headers): https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttps") void withPathAndConsumerWithResponseHeaders(final boolean https) throws IOException { server.expectations(expect -> { expect.DELETE("/something", req -> { req.secure(https); req.called(1); req.responder(res -> { res.header("Alpha", "Header-A"); res.header("Bravo", List.of("Header-B1", "Header-B2")); res.code(200); }); }); }); val response = client.delete("/something", https); assertEquals(200, response.code()); assertEquals("Header-A", response.header("Alpha")); assertEquals(List.of("Header-B1", "Header-B2"), response.headers("Bravo")); verify(server); } @ParameterizedTest(name = "[{index}] BASIC authentication: https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttps") void withBASICAuthentication(final boolean https) throws IOException { server.expectations(cfg -> { cfg.DELETE("/safe", req -> {
basicAuth(req, "basicuser", "ba$icp@$$");
5
NightKosh/Gravestone-mod-Graves
src/main/java/nightkosh/gravestone/renderer/tileentity/TileEntityGraveStoneRenderer.java
[ "public enum EnumGraves implements IBlockEnum {\n\n // VERTICAL PLATES\n WOODEN_VERTICAL_PLATE(Resources.GRAVE_WOODEN_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.WOOD),\n SANDSTONE_VERTICAL_PLATE(Resources.GRAVE_SANDSTONE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_VERTICAL_PLATE(Resources.GRAVE_RED_SANDSTONE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_VERTICAL_PLATE(Resources.GRAVE_STONE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.STONE),\n DIORITE_VERTICAL_PLATE(Resources.GRAVE_DIORITE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.DIORITE),\n ANDESITE_VERTICAL_PLATE(Resources.GRAVE_ANDESITE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.ANDESITE),\n GRANITE_VERTICAL_PLATE(Resources.GRAVE_GRANITE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.GRANITE),\n IRON_VERTICAL_PLATE(Resources.GRAVE_IRON_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.IRON),\n GOLDEN_VERTICAL_PLATE(Resources.GRAVE_GOLDEN_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.GOLD),\n DIAMOND_VERTICAL_PLATE(Resources.GRAVE_DIAMOND_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.DIAMOND),\n EMERALD_VERTICAL_PLATE(Resources.GRAVE_EMERALD_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.EMERALD),\n LAPIS_VERTICAL_PLATE(Resources.GRAVE_LAPIS_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.LAPIS),\n REDSTONE_VERTICAL_PLATE(Resources.GRAVE_REDSTONE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_VERTICAL_PLATE(Resources.GRAVE_OBSIDIAN_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_VERTICAL_PLATE(Resources.GRAVE_QUARTZ_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_VERTICAL_PLATE(Resources.GRAVE_PRIZMARINE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.PRIZMARINE),\n ICE_VERTICAL_PLATE(Resources.GRAVE_ICE_VERTICAL_PLATE, EnumGraveType.VERTICAL_PLATE, EnumGraveMaterial.ICE),\n // CROSSES\n WOODEN_CROSS(Resources.GRAVE_WOODEN_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.WOOD),\n SANDSTONE_CROSS(Resources.GRAVE_SANDSTONE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_CROSS(Resources.GRAVE_RED_SANDSTONE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.RED_SANDSTONE),\n STONE_CROSS(Resources.GRAVE_STONE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.STONE),\n DIORITE_CROSS(Resources.GRAVE_DIORITE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.DIORITE),\n ANDESITE_CROSS(Resources.GRAVE_ANDESITE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.ANDESITE),\n GRANITE_CROSS(Resources.GRAVE_GRANITE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.GRANITE),\n IRON_CROSS(Resources.GRAVE_IRON_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.IRON),\n GOLDEN_CROSS(Resources.GRAVE_GOLDEN_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.GOLD),\n DIAMOND_CROSS(Resources.GRAVE_DIAMOND_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.DIAMOND),\n EMERALD_CROSS(Resources.GRAVE_EMERALD_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.EMERALD),\n LAPIS_CROSS(Resources.GRAVE_LAPIS_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.LAPIS),\n REDSTONE_CROSS(Resources.GRAVE_REDSTONE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_CROSS(Resources.GRAVE_OBSIDIAN_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_CROSS(Resources.GRAVE_QUARTZ_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_CROSS(Resources.GRAVE_PRIZMARINE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.PRIZMARINE),\n ICE_CROSS(Resources.GRAVE_ICE_CROSS, EnumGraveType.CROSS, EnumGraveMaterial.ICE),\n // OBELISKS\n WOODEN_OBELISK(Resources.WOODEN_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.WOOD),\n SANDSTONE_OBELISK(Resources.SANDSTONE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_OBELISK(Resources.RED_SANDSTONE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.RED_SANDSTONE),\n STONE_OBELISK(Resources.STONE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.STONE),\n DIORITE_OBELISK(Resources.DIORITE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.DIORITE),\n ANDESITE_OBELISK(Resources.ANDESITE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.ANDESITE),\n GRANITE_OBELISK(Resources.GRANITE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.GRANITE),\n IRON_OBELISK(Resources.IRON_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.IRON),\n GOLDEN_OBELISK(Resources.GOLDEN_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.GOLD),\n DIAMOND_OBELISK(Resources.DIAMOND_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.DIAMOND),\n EMERALD_OBELISK(Resources.EMERALD_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.EMERALD),\n LAPIS_OBELISK(Resources.LAPIS_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.LAPIS),\n REDSTONE_OBELISK(Resources.REDSTONE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_OBELISK(Resources.OBSIDIAN_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_OBELISK(Resources.QUARTZ_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_OBELISK(Resources.PRIZMARINE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.PRIZMARINE),\n ICE_OBELISK(Resources.ICE_OBELISK, EnumGraveType.OBELISK, EnumGraveMaterial.ICE),\n // CELTIC CROSSES\n WOODEN_CELTIC_CROSS(Resources.WOODEN_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.WOOD),\n SANDSTONE_CELTIC_CROSS(Resources.SANDSTONE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_CELTIC_CROSS(Resources.RED_SANDSTONE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.RED_SANDSTONE),\n STONE_CELTIC_CROSS(Resources.STONE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.STONE),\n DIORITE_CELTIC_CROSS(Resources.DIORITE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.DIORITE),\n ANDESITE_CELTIC_CROSS(Resources.ANDESITE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.ANDESITE),\n GRANITE_CELTIC_CROSS(Resources.GRANITE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.GRANITE),\n IRON_CELTIC_CROSS(Resources.IRON_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.IRON),\n GOLDEN_CELTIC_CROSS(Resources.GOLDEN_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.GOLD),\n DIAMOND_CELTIC_CROSS(Resources.DIAMOND_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.DIAMOND),\n EMERALD_CELTIC_CROSS(Resources.EMERALD_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.EMERALD),\n LAPIS_CELTIC_CROSS(Resources.LAPIS_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.LAPIS),\n REDSTONE_CELTIC_CROSS(Resources.REDSTONE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_CELTIC_CROSS(Resources.OBSIDIAN_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_CELTIC_CROSS(Resources.QUARTZ_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_CELTIC_CROSS(Resources.PRIZMARINE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.PRIZMARINE),\n ICE_CELTIC_CROSS(Resources.ICE_CELTIC_CROSS, EnumGraveType.CELTIC_CROSS, EnumGraveMaterial.ICE),\n // HORISONTAL PLATES\n WOODEN_HORIZONTAL_PLATE(Resources.GRAVE_WOODEN_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.WOOD),\n SANDSTONE_HORIZONTAL_PLATE(Resources.GRAVE_SANDSTONE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_HORIZONTAL_PLATE(Resources.GRAVE_RED_SANDSTONE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_HORIZONTAL_PLATE(Resources.GRAVE_STONE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.STONE),\n DIORITE_HORIZONTAL_PLATE(Resources.GRAVE_DIORITE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.DIORITE),\n ANDESITE_HORIZONTAL_PLATE(Resources.GRAVE_ANDESITE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.ANDESITE),\n GRANITE_HORIZONTAL_PLATE(Resources.GRAVE_GRANITE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.GRANITE),\n IRON_HORIZONTAL_PLATE(Resources.GRAVE_IRON_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.IRON),\n GOLDEN_HORIZONTAL_PLATE(Resources.GRAVE_GOLDEN_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.GOLD),\n DIAMOND_HORIZONTAL_PLATE(Resources.GRAVE_DIAMOND_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.DIAMOND),\n EMERALD_HORIZONTAL_PLATE(Resources.GRAVE_EMERALD_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.EMERALD),\n LAPIS_HORIZONTAL_PLATE(Resources.GRAVE_LAPIS_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.LAPIS),\n REDSTONE_HORIZONTAL_PLATE(Resources.GRAVE_REDSTONE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_HORIZONTAL_PLATE(Resources.GRAVE_OBSIDIAN_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_HORIZONTAL_PLATE(Resources.GRAVE_QUARTZ_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_HORIZONTAL_PLATE(Resources.GRAVE_PRIZMARINE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.PRIZMARINE),\n ICE_HORIZONTAL_PLATE(Resources.GRAVE_ICE_HORISONTAL_PLATE, EnumGraveType.HORIZONTAL_PLATE, EnumGraveMaterial.ICE),\n // VILLAGERS STATUES\n WOODEN_VILLAGER_STATUE(Resources.WOODEN_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.WOOD),\n SANDSTONE_VILLAGER_STATUE(Resources.SANDSTONE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_VILLAGER_STATUE(Resources.RED_SANDSTONE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_VILLAGER_STATUE(Resources.STONE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.STONE),\n DIORITE_VILLAGER_STATUE(Resources.DIORITE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.DIORITE),\n ANDESITE_VILLAGER_STATUE(Resources.ANDESITE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.ANDESITE),\n GRANITE_VILLAGER_STATUE(Resources.GRANITE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.GRANITE),\n IRON_VILLAGER_STATUE(Resources.IRON_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.IRON),\n GOLDEN_VILLAGER_STATUE(Resources.GOLDEN_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.GOLD),\n DIAMOND_VILLAGER_STATUE(Resources.DIAMOND_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.DIAMOND),\n EMERALD_VILLAGER_STATUE(Resources.EMERALD_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.EMERALD),\n LAPIS_VILLAGER_STATUE(Resources.LAPIS_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.LAPIS),\n REDSTONE_VILLAGER_STATUE(Resources.REDSTONE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_VILLAGER_STATUE(Resources.OBSIDIAN_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_VILLAGER_STATUE(Resources.QUARTZ_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_VILLAGER_STATUE(Resources.PRIZMARINE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.PRIZMARINE),\n ICE_VILLAGER_STATUE(Resources.ICE_VILLAGER_STATUE, EnumGraveType.VILLAGER_STATUE, EnumGraveMaterial.ICE),\n // DOGS GRAVES\n WOODEN_DOG_STATUE(Resources.WOODEN_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.WOOD),\n SANDSTONE_DOG_STATUE(Resources.SANDSTONE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_DOG_STATUE(Resources.RED_SANDSTONE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_DOG_STATUE(Resources.STONE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.STONE),\n DIORITE_DOG_STATUE(Resources.DIORITE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.DIORITE),\n ANDESITE_DOG_STATUE(Resources.ANDESITE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.ANDESITE),\n GRANITE_DOG_STATUE(Resources.GRANITE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.GRANITE),\n IRON_DOG_STATUE(Resources.IRON_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.IRON),\n GOLDEN_DOG_STATUE(Resources.GOLDEN_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.GOLD),\n DIAMOND_DOG_STATUE(Resources.DIAMOND_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.DIAMOND),\n EMERALD_DOG_STATUE(Resources.EMERALD_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.EMERALD),\n LAPIS_DOG_STATUE(Resources.LAPIS_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.LAPIS),\n REDSTONE_DOG_STATUE(Resources.REDSTONE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_DOG_STATUE(Resources.OBSIDIAN_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_DOG_STATUE(Resources.QUARTZ_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_DOG_STATUE(Resources.PRIZMARINE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.PRIZMARINE),\n ICE_DOG_STATUE(Resources.ICE_DOG_STATUE, EnumGraveType.DOG_STATUE, EnumGraveMaterial.ICE),\n // CATS GRAVES\n WOODEN_CAT_STATUE(Resources.WOODEN_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.WOOD),\n SANDSTONE_CAT_STATUE(Resources.SANDSTONE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_CAT_STATUE(Resources.RED_SANDSTONE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_CAT_STATUE(Resources.STONE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.STONE),\n DIORITE_CAT_STATUE(Resources.DIORITE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.DIORITE),\n ANDESITE_CAT_STATUE(Resources.ANDESITE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.ANDESITE),\n GRANITE_CAT_STATUE(Resources.GRANITE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.GRANITE),\n IRON_CAT_STATUE(Resources.IRON_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.IRON),\n GOLDEN_CAT_STATUE(Resources.GOLDEN_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.GOLD),\n DIAMOND_CAT_STATUE(Resources.DIAMOND_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.DIAMOND),\n EMERALD_CAT_STATUE(Resources.EMERALD_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.EMERALD),\n LAPIS_CAT_STATUE(Resources.LAPIS_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.LAPIS),\n REDSTONE_CAT_STATUE(Resources.REDSTONE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_CAT_STATUE(Resources.OBSIDIAN_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_CAT_STATUE(Resources.QUARTZ_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_CAT_STATUE(Resources.PRIZMARINE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.PRIZMARINE),\n ICE_CAT_STATUE(Resources.ICE_CAT_STATUE, EnumGraveType.CAT_STATUE, EnumGraveMaterial.ICE),\n // HORSES GRAVES\n WOODEN_HORSE_STATUE(Resources.GRAVE_WOODEN_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.WOOD),\n SANDSTONE_HORSE_STATUE(Resources.GRAVE_SANDSTONE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_HORSE_STATUE(Resources.GRAVE_RED_SANDSTONE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_HORSE_STATUE(Resources.GRAVE_STONE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.STONE),\n DIORITE_HORSE_STATUE(Resources.GRAVE_DIORITE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.DIORITE),\n ANDESITE_HORSE_STATUE(Resources.GRAVE_ANDESITE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.ANDESITE),\n GRANITE_HORSE_STATUE(Resources.GRAVE_GRANITE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.GRANITE),\n IRON_HORSE_STATUE(Resources.GRAVE_IRON_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.IRON),\n GOLDEN_HORSE_STATUE(Resources.GRAVE_GOLDEN_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.GOLD),\n DIAMOND_HORSE_STATUE(Resources.GRAVE_DIAMOND_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.DIAMOND),\n EMERALD_HORSE_STATUE(Resources.GRAVE_EMERALD_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.EMERALD),\n LAPIS_HORSE_STATUE(Resources.GRAVE_LAPIS_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.LAPIS),\n REDSTONE_HORSE_STATUE(Resources.GRAVE_REDSTONE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_HORSE_STATUE(Resources.GRAVE_OBSIDIAN_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_HORSE_STATUE(Resources.GRAVE_QUARTZ_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_HORSE_STATUE(Resources.GRAVE_PRIZMARINE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.PRIZMARINE),\n ICE_HORSE_STATUE(Resources.GRAVE_ICE_HORSE_STATUE, EnumGraveType.HORSE_STATUE, EnumGraveMaterial.ICE),\n // CREEPER STATUES\n WOODEN_CREEPER_STATUE(Resources.WOODEN_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.WOOD),\n SANDSTONE_CREEPER_STATUE(Resources.SANDSTONE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.SANDSTONE),\n RED_SANDSTONE_CREEPER_STATUE(Resources.RED_SANDSTONE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.RED_SANDSTONE),\n STONE_CREEPER_STATUE(Resources.STONE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.STONE),\n DIORITE_CREEPER_STATUE(Resources.DIORITE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.DIORITE),\n ANDESITE_CREEPER_STATUE(Resources.ANDESITE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.ANDESITE),\n GRANITE_CREEPER_STATUE(Resources.GRANITE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.GRANITE),\n IRON_CREEPER_STATUE(Resources.IRON_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.IRON),\n GOLDEN_CREEPER_STATUE(Resources.GOLDEN_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.GOLD),\n DIAMOND_CREEPER_STATUE(Resources.DIAMOND_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.DIAMOND),\n EMERALD_CREEPER_STATUE(Resources.EMERALD_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.EMERALD),\n LAPIS_CREEPER_STATUE(Resources.LAPIS_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.LAPIS),\n REDSTONE_CREEPER_STATUE(Resources.REDSTONE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.REDSTONE),\n OBSIDIAN_CREEPER_STATUE(Resources.OBSIDIAN_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.OBSIDIAN),\n QUARTZ_CREEPER_STATUE(Resources.QUARTZ_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.QUARTZ),\n PRIZMARINE_CREEPER_STATUE(Resources.PRIZMARINE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.PRIZMARINE),\n ICE_CREEPER_STATUE(Resources.ICE_CREEPER_STATUE, EnumGraveType.CREEPER_STATUE, EnumGraveMaterial.ICE),\n // CORPSES\n STARVED_CORPSE(Resources.SKELETON, EnumGraveType.STARVED_CORPSE, EnumGraveMaterial.OTHER),\n WITHERED_CORPSE(Resources.WITHER_SKELETON, EnumGraveType.WITHERED_CORPSE, EnumGraveMaterial.OTHER),\n // SWORD\n SWORD(null, EnumGraveType.SWORD, EnumGraveMaterial.OTHER);\n\n\n private String name;\n private ResourceLocation texture;\n private EnumGraveType graveType;\n private EnumGraveMaterial material;\n\n private EnumGraves(ResourceLocation texture, EnumGraveType graveType, EnumGraveMaterial material) {\n this.name = getName(graveType);\n this.texture = texture;\n this.graveType = graveType;\n this.material = material;\n }\n\n @Override\n public String getUnLocalizedName() {\n return this.name;\n }\n\n public ResourceLocation getTexture() {\n return this.texture;\n }\n\n public EnumGraveType getGraveType() {\n return graveType;\n }\n\n public EnumGraveMaterial getMaterial() {\n return material;\n }\n\n /**\n * Returns the grave type with the specified ID, or VERTICAL_PLATE if none found.\n *\n * @param id Grave Id\n */\n public static EnumGraves getById(int id) {\n if (id < values().length) {\n return values()[id];\n }\n return STONE_VERTICAL_PLATE;\n }\n\n public static EnumGraves getByTypeAndMaterial(EnumGraveType graveType, EnumGraveMaterial material) {\n for (EnumGraves grave : EnumGraves.values()) {\n if (grave.getGraveType().equals(graveType) && grave.getMaterial().equals(material)) {\n return grave;\n }\n }\n return STONE_VERTICAL_PLATE;\n }\n\n private static String getName(EnumGraveType graveType) {\n switch (graveType) {\n case VERTICAL_PLATE:\n default:\n return \"block.gravestone.gravestone\";\n case CROSS:\n return \"block.gravestone.cross\";\n case OBELISK:\n return \"block.gravestone.obelisk\";\n case CELTIC_CROSS:\n return \"block.gravestone.celtic_cross\";\n case HORIZONTAL_PLATE:\n return \"block.gravestone.plate\";\n case VILLAGER_STATUE:\n return \"block.gravestone.villager_statue\";\n case DOG_STATUE:\n return \"block.gravestone.dog_statue\";\n case CAT_STATUE:\n return \"block.gravestone.cat_statue\";\n case HORSE_STATUE:\n return \"block.gravestone.horse_statue\";\n case CREEPER_STATUE:\n return \"block.gravestone.creeper_statue\";\n case STARVED_CORPSE:\n return \"block.gravestone.starved_corpse\";\n case WITHERED_CORPSE:\n return \"block.gravestone.withered_corpse\";\n case SWORD:\n return \"block.gravestone.sword\";\n }\n }\n}", "public class Config {\n\n private static Configuration config;\n private static Config instance;\n private static String path;\n // CATEGORIES\n public static final String CATEGORY_COMPATIBILITY = \"compatibility\";\n public static final String CATEGORY_GRAVES = \"graves\";\n\n private Config(String path, File configFile) {\n this.config = new Configuration(configFile);\n this.path = path;\n getConfigs();\n }\n\n public static Config getInstance(String path, String configFile) {\n if (instance == null) {\n return new Config(path, new File(path + configFile));\n } else {\n return instance;\n }\n }\n\n public final void getConfigs() {\n config.load();\n gravesConfig();\n compatibilityConfigs();\n config.save();\n getGravesText();\n }\n\n\n public static boolean generatePlayerGraves;\n public static boolean generateVillagerGraves;\n public static boolean generatePetGraves;\n public static boolean generateGravesInLava;\n public static int graveItemsCount;\n public static boolean canPlaceGravesEveryWhere;\n public static boolean generateSwordGraves;\n public static boolean removeEmptyGraves;\n public static boolean showGravesRemovingMessages;\n public static boolean onlyOwnerCanLootGrave;\n public static boolean renderGravesFlowers;\n public static boolean vanillaRendererForSwordsGraves;\n public static boolean generateEmptyPlayerGraves;\n public static boolean dropGraveBlockAtDestruction;\n public static List<Integer> playerGravesDimensionalBlackList;\n public static boolean createBackups;\n\n public static List<GraveStoneHelper.RestrictedArea> restrictGraveGenerationInArea;\n\n private static void gravesConfig() {\n canPlaceGravesEveryWhere = config.get(CATEGORY_GRAVES, \"AllowToPlaceGravesEveryWhere\", false).getBoolean(false);\n generatePlayerGraves = config.get(CATEGORY_GRAVES, \"GeneratePlayersGraves\", true).getBoolean(true);\n generateVillagerGraves = config.get(CATEGORY_GRAVES, \"GenerateVillagersGraves\", true).getBoolean(true);\n generatePetGraves = config.get(CATEGORY_GRAVES, \"GeneratePetsGraves\", true).getBoolean(true);\n generateGravesInLava = config.get(CATEGORY_GRAVES, \"GenerateGravesInLava\", true).getBoolean(true);\n generateSwordGraves = config.get(CATEGORY_GRAVES, \"GenerateSwordGraves\", true).getBoolean(true);\n generateEmptyPlayerGraves = config.get(CATEGORY_GRAVES, \"GenerateEmptyPlayerGraves\", true).getBoolean(true);\n onlyOwnerCanLootGrave = config.get(CATEGORY_GRAVES, \"OnlyOwnerCanLootGrave\", false).getBoolean(false);\n\n\n // store items\n Property graveItemsCountProperty = config.get(CATEGORY_GRAVES, \"AmountOfSavedItems\", 100);\n graveItemsCountProperty.setComment(\"This value is amount of items which should be saved in percents. It should be in range of 0 an 100!\");\n graveItemsCount = graveItemsCountProperty.getInt();\n\n if (graveItemsCount > 100 || graveItemsCount < 0) {\n graveItemsCount = 100;\n }\n\n removeEmptyGraves = config.get(CATEGORY_GRAVES, \"RemoveEmptyGraves\", false).getBoolean(false);\n showGravesRemovingMessages = config.get(CATEGORY_GRAVES, \"ShowGravesRemovingMessages\", true).getBoolean(true);\n dropGraveBlockAtDestruction = config.get(CATEGORY_GRAVES, \"DropGraveBlockAtDestruction\", true).getBoolean(true);\n\n renderGravesFlowers = config.get(CATEGORY_GRAVES, \"RenderGravesFlowers\", true).getBoolean(true);\n vanillaRendererForSwordsGraves = config.get(CATEGORY_GRAVES, \"VanillaRendererForSwordsGraves\", true).getBoolean(true);\n\n Property restrictGraveGenerationInAreaProperty = config.get(CATEGORY_GRAVES, \"RestrictGraveGenerationInArea\", \"\");\n restrictGraveGenerationInAreaProperty.setComment(\"List of coordinates in which graves generation must be disabled. \\\"dimension_id,start_x,start_y,start_z,end_x,end_y,end_z;\\\". Dimension id is optional - it will be set to 0 by default.\");\n String ar = restrictGraveGenerationInAreaProperty.getString();\n String[] areas = ar.split(\";\");\n restrictGraveGenerationInArea = new ArrayList<>(areas.length);\n for (String area : areas) {\n GraveStoneHelper.RestrictedArea restrictedArea = GraveStoneHelper.RestrictedArea.getFromString(area);\n if (restrictedArea != null) {\n restrictGraveGenerationInArea.add(restrictedArea);\n }\n }\n\n playerGravesDimensionalBlackList = ConfigsHelper.getDimensionList(config, CATEGORY_GRAVES, \"PlayerGravesDimensionalBlackList\", \"\",\n \"List of dimension ids in which player's graves will not be generated at death\");\n\n createBackups = config.get(CATEGORY_GRAVES, \"CreateBackups\", true).getBoolean();\n }\n\n\n // COMPATIBILITY\n public static boolean storeBattlegearItems;\n public static boolean storeTheCampingModItems;\n public static boolean storeBaublesItems;\n public static boolean storeMaricultureItems;\n public static boolean storeRpgInventoryItems;\n public static boolean storeGalacticraftItems;\n public static boolean storeBackpacksItems;\n public static boolean enableArsMagicaSoulbound;\n public static boolean enableEnderIOSoulbound;\n public static boolean enableTconstructSoulbound;\n public static boolean enableTwilightForestKeeping;\n public static boolean addThaumcraftSwordsAsGravestones;\n\n private static void compatibilityConfigs() {\n\n// storeBattlegearItems = config.get(CATEGORY_COMPATIBILITY, \"StoreBattlegearItems\", true).getBoolean(true);\n storeTheCampingModItems = config.get(CATEGORY_COMPATIBILITY, \"StoreTheCampingModItems\", true).getBoolean(true);\n// storeBaublesItems = config.get(CATEGORY_COMPATIBILITY, \"StoreBaublesItems\", true).getBoolean(true);\n// storeMaricultureItems = config.get(CATEGORY_COMPATIBILITY, \"StoreMaricultureItems\", true).getBoolean(true);\n// storeRpgInventoryItems = config.get(CATEGORY_COMPATIBILITY, \"StoreRpgInventoryItems\", true).getBoolean(true);\n// storeGalacticraftItems = config.get(CATEGORY_COMPATIBILITY, \"StoreGalacticraftItems\", true).getBoolean(true);\n// storeBackpacksItems = config.get(CATEGORY_COMPATIBILITY, \"StoreBackpacksItems\", true).getBoolean(true);\n\n// enableArsMagicaSoulbound = config.get(CATEGORY_COMPATIBILITY, \"EnableArsMagicaSoulbound\", true).getBoolean(true);\n// enableEnderIOSoulbound = config.get(CATEGORY_COMPATIBILITY, \"EnableEnderIOSoulbound\", true).getBoolean(true);\n// enableTconstructSoulbound = config.get(CATEGORY_COMPATIBILITY, \"EnableTconstructSoulbound\", true).getBoolean(true);\n// enableTwilightForestKeeping = config.get(CATEGORY_COMPATIBILITY, \"EnableTwilightForestCharmsOfKeeping\", true).getBoolean(true);\n\n addThaumcraftSwordsAsGravestones = config.get(CATEGORY_COMPATIBILITY, \"AddThaumcraftSwordsAsGravestones\", true).getBoolean(true);\n }\n\n // grave names\n public static ArrayList<String> graveNames;\n public static ArrayList<String> graveDogsNames;\n public static ArrayList<String> graveCatsNames;\n public static ArrayList<String> graveDeathMessages;\n\n private void getGravesText() {\n graveNames = readStringsFromFile(path + \"graveNames.txt\", GravesDefaultText.NAMES);\n graveDogsNames = readStringsFromFile(path + \"graveDogsNames.txt\", GravesDefaultText.DOG_NAMES);\n graveCatsNames = readStringsFromFile(path + \"graveCatsNames.txt\", GravesDefaultText.CAT_NAMES);\n graveDeathMessages = readStringsFromFile(path + \"graveDeathMessages.txt\", GravesDefaultText.DEATH_TEXT);\n }\n\n /*\n * Read text from file if it exist or get default text\n */\n private static ArrayList<String> readStringsFromFile(String fileName, String[] defaultValues) {\n ArrayList<String> list = new ArrayList<String>();\n list.addAll(Arrays.asList(defaultValues));\n\n return list;\n }\n}", "public class Resources {\n\n public static final String MOD_NAME = ModInfo.ID.toLowerCase();\n public static final String BLOCK_LOCATION = MOD_NAME + \":textures/blocks/\";\n public static final String GRAVES_LOCATION = MOD_NAME + \":textures/graves/\";\n public static final String STATUES_LOCATION = MOD_NAME + \":textures/statues/\";\n public static final String SWORDS_LOCATION = MOD_NAME + \":textures/swords/\";\n\n // gui\n public static final ResourceLocation CHEST_GUI = new ResourceLocation(\"textures/gui/container/generic_54.png\");\n\n // skull\n public static final ResourceLocation SKELETON_SKULL = new ResourceLocation(BLOCK_LOCATION + \"skeleton_skull.png\");\n public static final ResourceLocation WITHER_SKULL = new ResourceLocation(BLOCK_LOCATION + \"wither_skull.png\");\n public static final ResourceLocation ZOMBIE_SKULL = new ResourceLocation(BLOCK_LOCATION + \"zombie_skull.png\");\n public static final ResourceLocation STRAY_SKULL = new ResourceLocation(BLOCK_LOCATION + \"stray_skull.png\");\n\n // entities\n public static final ResourceLocation SKELETON = new ResourceLocation(\"textures/entity/skeleton/skeleton.png\");\n public static final ResourceLocation WITHER_SKELETON = new ResourceLocation(\"textures/entity/skeleton/wither_skeleton.png\");\n\n // models - graves\n // vertical plates\n public static final ResourceLocation GRAVE_WOODEN_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/wooden.png\");\n public static final ResourceLocation GRAVE_SANDSTONE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/sandstone.png\");\n public static final ResourceLocation GRAVE_RED_SANDSTONE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/redsandstone.png\");\n public static final ResourceLocation GRAVE_STONE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/stone.png\");\n public static final ResourceLocation GRAVE_DIORITE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/diorite.png\");\n public static final ResourceLocation GRAVE_ANDESITE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/andesite.png\");\n public static final ResourceLocation GRAVE_GRANITE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/granite.png\");\n public static final ResourceLocation GRAVE_IRON_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/iron.png\");\n public static final ResourceLocation GRAVE_GOLDEN_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/golden.png\");\n public static final ResourceLocation GRAVE_DIAMOND_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/diamond.png\");\n public static final ResourceLocation GRAVE_EMERALD_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/emerald.png\");\n public static final ResourceLocation GRAVE_LAPIS_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/lapis.png\");\n public static final ResourceLocation GRAVE_REDSTONE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/redstone.png\");\n public static final ResourceLocation GRAVE_OBSIDIAN_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/obsidian.png\");\n public static final ResourceLocation GRAVE_QUARTZ_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/quartz.png\");\n public static final ResourceLocation GRAVE_PRIZMARINE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/prizmarine.png\");\n public static final ResourceLocation GRAVE_ICE_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/ice.png\");\n public static final ResourceLocation GRAVE_MOSSY_VERTICAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"vertical_plate/mossy.png\");\n // crosses\n public static final ResourceLocation GRAVE_WOODEN_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/wooden.png\");\n public static final ResourceLocation GRAVE_SANDSTONE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/sandstone.png\");\n public static final ResourceLocation GRAVE_RED_SANDSTONE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/redsandstone.png\");\n public static final ResourceLocation GRAVE_STONE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/stone.png\");\n public static final ResourceLocation GRAVE_DIORITE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/diorite.png\");\n public static final ResourceLocation GRAVE_ANDESITE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/andesite.png\");\n public static final ResourceLocation GRAVE_GRANITE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/granite.png\");\n public static final ResourceLocation GRAVE_IRON_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/iron.png\");\n public static final ResourceLocation GRAVE_GOLDEN_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/golden.png\");\n public static final ResourceLocation GRAVE_DIAMOND_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/diamond.png\");\n public static final ResourceLocation GRAVE_EMERALD_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/emerald.png\");\n public static final ResourceLocation GRAVE_LAPIS_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/lapis.png\");\n public static final ResourceLocation GRAVE_REDSTONE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/redstone.png\");\n public static final ResourceLocation GRAVE_OBSIDIAN_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/obsidian.png\");\n public static final ResourceLocation GRAVE_QUARTZ_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/quartz.png\");\n public static final ResourceLocation GRAVE_PRIZMARINE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/prizmarine.png\");\n public static final ResourceLocation GRAVE_ICE_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/ice.png\");\n public static final ResourceLocation GRAVE_MOSSY_CROSS = new ResourceLocation(GRAVES_LOCATION + \"cross/mossy.png\");\n // horisontal plates\n public static final ResourceLocation GRAVE_WOODEN_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/wooden.png\");\n public static final ResourceLocation GRAVE_SANDSTONE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/sandstone.png\");\n public static final ResourceLocation GRAVE_RED_SANDSTONE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/redsandstone.png\");\n public static final ResourceLocation GRAVE_STONE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/stone.png\");\n public static final ResourceLocation GRAVE_DIORITE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/diorite.png\");\n public static final ResourceLocation GRAVE_ANDESITE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/andesite.png\");\n public static final ResourceLocation GRAVE_GRANITE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/granite.png\");\n public static final ResourceLocation GRAVE_IRON_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/iron.png\");\n public static final ResourceLocation GRAVE_GOLDEN_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/golden.png\");\n public static final ResourceLocation GRAVE_DIAMOND_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/diamond.png\");\n public static final ResourceLocation GRAVE_EMERALD_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/emerald.png\");\n public static final ResourceLocation GRAVE_LAPIS_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/lapis.png\");\n public static final ResourceLocation GRAVE_REDSTONE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/redstone.png\");\n public static final ResourceLocation GRAVE_OBSIDIAN_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/obsidian.png\");\n public static final ResourceLocation GRAVE_QUARTZ_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/quartz.png\");\n public static final ResourceLocation GRAVE_PRIZMARINE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/prizmarine.png\");\n public static final ResourceLocation GRAVE_ICE_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/ice.png\");\n public static final ResourceLocation GRAVE_MOSSY_HORISONTAL_PLATE = new ResourceLocation(GRAVES_LOCATION + \"horizontal_plate/mossy.png\");\n // horses graves\n public static final ResourceLocation GRAVE_WOODEN_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/wooden.png\");\n public static final ResourceLocation GRAVE_SANDSTONE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/sandstone.png\");\n public static final ResourceLocation GRAVE_RED_SANDSTONE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/redsandstone.png\");\n public static final ResourceLocation GRAVE_STONE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/stone.png\");\n public static final ResourceLocation GRAVE_DIORITE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/diorite.png\");\n public static final ResourceLocation GRAVE_ANDESITE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/andesite.png\");\n public static final ResourceLocation GRAVE_GRANITE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/granite.png\");\n public static final ResourceLocation GRAVE_IRON_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/iron.png\");\n public static final ResourceLocation GRAVE_GOLDEN_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/golden.png\");\n public static final ResourceLocation GRAVE_DIAMOND_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/diamond.png\");\n public static final ResourceLocation GRAVE_EMERALD_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/emerald.png\");\n public static final ResourceLocation GRAVE_LAPIS_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/lapis.png\");\n public static final ResourceLocation GRAVE_REDSTONE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/redstone.png\");\n public static final ResourceLocation GRAVE_OBSIDIAN_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/obsidian.png\");\n public static final ResourceLocation GRAVE_QUARTZ_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/quartz.png\");\n public static final ResourceLocation GRAVE_PRIZMARINE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/prizmarine.png\");\n public static final ResourceLocation GRAVE_ICE_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/ice.png\");\n public static final ResourceLocation GRAVE_MOSSY_HORSE_STATUE = new ResourceLocation(GRAVES_LOCATION + \"horse/mossy.png\");\n\n\n // obelisk\n public static final ResourceLocation WOODEN_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/wooden.png\");\n public static final ResourceLocation SANDSTONE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/sandstone.png\");\n public static final ResourceLocation RED_SANDSTONE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/redsandstone.png\");\n public static final ResourceLocation STONE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/stone.png\");\n public static final ResourceLocation DIORITE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/diorite.png\");\n public static final ResourceLocation ANDESITE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/andesite.png\");\n public static final ResourceLocation GRANITE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/granite.png\");\n public static final ResourceLocation IRON_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/iron.png\");\n public static final ResourceLocation GOLDEN_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/golden.png\");\n public static final ResourceLocation DIAMOND_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/diamond.png\");\n public static final ResourceLocation EMERALD_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/emerald.png\");\n public static final ResourceLocation LAPIS_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/lapis.png\");\n public static final ResourceLocation REDSTONE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/redstone.png\");\n public static final ResourceLocation OBSIDIAN_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/obsidian.png\");\n public static final ResourceLocation QUARTZ_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/quartz.png\");\n public static final ResourceLocation PRIZMARINE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/prizmarine.png\");\n public static final ResourceLocation ICE_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/ice.png\");\n public static final ResourceLocation MOSSY_OBELISK = new ResourceLocation(STATUES_LOCATION + \"obelisk/mossy.png\");\n // celtic crosses\n public static final ResourceLocation WOODEN_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/wooden.png\");\n public static final ResourceLocation SANDSTONE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/sandstone.png\");\n public static final ResourceLocation RED_SANDSTONE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/redsandstone.png\");\n public static final ResourceLocation STONE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/stone.png\");\n public static final ResourceLocation DIORITE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/diorite.png\");\n public static final ResourceLocation ANDESITE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/andesite.png\");\n public static final ResourceLocation GRANITE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/granite.png\");\n public static final ResourceLocation IRON_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/iron.png\");\n public static final ResourceLocation GOLDEN_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/golden.png\");\n public static final ResourceLocation DIAMOND_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/diamond.png\");\n public static final ResourceLocation EMERALD_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/emerald.png\");\n public static final ResourceLocation LAPIS_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/lapis.png\");\n public static final ResourceLocation REDSTONE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/redstone.png\");\n public static final ResourceLocation OBSIDIAN_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/obsidian.png\");\n public static final ResourceLocation QUARTZ_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/quartz.png\");\n public static final ResourceLocation PRIZMARINE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/prizmarine.png\");\n public static final ResourceLocation ICE_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/ice.png\");\n public static final ResourceLocation MOSSY_CELTIC_CROSS = new ResourceLocation(STATUES_LOCATION + \"celtic_cross/mossy.png\");\n // villagers statues\n public static final ResourceLocation WOODEN_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/wooden.png\");\n public static final ResourceLocation SANDSTONE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/sandstone.png\");\n public static final ResourceLocation RED_SANDSTONE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/redsandstone.png\");\n public static final ResourceLocation STONE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/stone.png\");\n public static final ResourceLocation DIORITE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/diorite.png\");\n public static final ResourceLocation ANDESITE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/andesite.png\");\n public static final ResourceLocation GRANITE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/granite.png\");\n public static final ResourceLocation IRON_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/iron.png\");\n public static final ResourceLocation GOLDEN_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/golden.png\");\n public static final ResourceLocation DIAMOND_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/diamond.png\");\n public static final ResourceLocation EMERALD_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/emerald.png\");\n public static final ResourceLocation LAPIS_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/lapis.png\");\n public static final ResourceLocation REDSTONE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/redstone.png\");\n public static final ResourceLocation OBSIDIAN_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/obsidian.png\");\n public static final ResourceLocation QUARTZ_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/quartz.png\");\n public static final ResourceLocation PRIZMARINE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/prizmarine.png\");\n public static final ResourceLocation ICE_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/ice.png\");\n public static final ResourceLocation MOSSY_VILLAGER_STATUE = new ResourceLocation(STATUES_LOCATION + \"villager/mossy.png\");\n // dogs statues\n public static final ResourceLocation WOODEN_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/wooden.png\");\n public static final ResourceLocation SANDSTONE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/sandstone.png\");\n public static final ResourceLocation RED_SANDSTONE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/redsandstone.png\");\n public static final ResourceLocation STONE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/stone.png\");\n public static final ResourceLocation DIORITE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/diorite.png\");\n public static final ResourceLocation ANDESITE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/andesite.png\");\n public static final ResourceLocation GRANITE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/granite.png\");\n public static final ResourceLocation IRON_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/iron.png\");\n public static final ResourceLocation GOLDEN_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/golden.png\");\n public static final ResourceLocation DIAMOND_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/diamond.png\");\n public static final ResourceLocation EMERALD_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/emerald.png\");\n public static final ResourceLocation LAPIS_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/lapis.png\");\n public static final ResourceLocation REDSTONE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/redstone.png\");\n public static final ResourceLocation OBSIDIAN_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/obsidian.png\");\n public static final ResourceLocation QUARTZ_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/quartz.png\");\n public static final ResourceLocation PRIZMARINE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/prizmarine.png\");\n public static final ResourceLocation ICE_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/ice.png\");\n public static final ResourceLocation MOSSY_DOG_STATUE = new ResourceLocation(STATUES_LOCATION + \"dog/mossy.png\");\n // cats statues\n public static final ResourceLocation WOODEN_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/wooden.png\");\n public static final ResourceLocation SANDSTONE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/sandstone.png\");\n public static final ResourceLocation RED_SANDSTONE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/redsandstone.png\");\n public static final ResourceLocation STONE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/stone.png\");\n public static final ResourceLocation DIORITE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/diorite.png\");\n public static final ResourceLocation ANDESITE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/andesite.png\");\n public static final ResourceLocation GRANITE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/granite.png\");\n public static final ResourceLocation IRON_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/iron.png\");\n public static final ResourceLocation GOLDEN_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/golden.png\");\n public static final ResourceLocation DIAMOND_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/diamond.png\");\n public static final ResourceLocation EMERALD_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/emerald.png\");\n public static final ResourceLocation LAPIS_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/lapis.png\");\n public static final ResourceLocation REDSTONE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/redstone.png\");\n public static final ResourceLocation OBSIDIAN_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/obsidian.png\");\n public static final ResourceLocation QUARTZ_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/quartz.png\");\n public static final ResourceLocation PRIZMARINE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/prizmarine.png\");\n public static final ResourceLocation ICE_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/ice.png\");\n public static final ResourceLocation MOSSY_CAT_STATUE = new ResourceLocation(STATUES_LOCATION + \"cat/mossy.png\");\n // creepers statues\n public static final ResourceLocation WOODEN_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/wooden.png\");\n public static final ResourceLocation SANDSTONE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/sandstone.png\");\n public static final ResourceLocation RED_SANDSTONE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/redsandstone.png\");\n public static final ResourceLocation STONE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/stone.png\");\n public static final ResourceLocation DIORITE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/diorite.png\");\n public static final ResourceLocation ANDESITE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/andesite.png\");\n public static final ResourceLocation GRANITE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/granite.png\");\n public static final ResourceLocation IRON_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/iron.png\");\n public static final ResourceLocation GOLDEN_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/golden.png\");\n public static final ResourceLocation DIAMOND_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/diamond.png\");\n public static final ResourceLocation EMERALD_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/emerald.png\");\n public static final ResourceLocation LAPIS_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/lapis.png\");\n public static final ResourceLocation REDSTONE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/redstone.png\");\n public static final ResourceLocation OBSIDIAN_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/obsidian.png\");\n public static final ResourceLocation QUARTZ_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/quartz.png\");\n public static final ResourceLocation PRIZMARINE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/prizmarine.png\");\n public static final ResourceLocation ICE_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/ice.png\");\n public static final ResourceLocation MOSSY_CREEPER_STATUE = new ResourceLocation(STATUES_LOCATION + \"creeper/mossy.png\");\n // swords\n public static final ResourceLocation WOODEN_SWORD = new ResourceLocation(SWORDS_LOCATION + \"wooden.png\");\n public static final ResourceLocation STONE_SWORD = new ResourceLocation(SWORDS_LOCATION + \"stone.png\");\n public static final ResourceLocation IRON_SWORD = new ResourceLocation(SWORDS_LOCATION + \"iron.png\");\n public static final ResourceLocation GOLDEN_SWORD = new ResourceLocation(SWORDS_LOCATION + \"golden.png\");\n public static final ResourceLocation DIAMOND_SWORD = new ResourceLocation(SWORDS_LOCATION + \"diamond.png\");\n\n // models - parts\n public static final ResourceLocation CREEPER_AURA = new ResourceLocation(\"textures/entity/creeper/creeper_armor.png\");\n public static final ResourceLocation SWORD_AURA = new ResourceLocation(\"textures/misc/enchanted_item_glint.png\");\n\n}", "@SideOnly(Side.CLIENT)\npublic abstract class ModelGraveStone extends ModelBase {\n\n public abstract void renderAll();\n\n protected void setRotation(ModelRenderer model, float x, float y, float z) {\n model.rotateAngleX = x;\n model.rotateAngleY = y;\n model.rotateAngleZ = z;\n }\n\n /**\n * Custom render\n */\n public void customRender(boolean enchanted) {\n if (enchanted) {\n renderEnchanted();\n } else {\n renderAll();\n }\n }\n\n /**\n * Sets the models various rotation angles then renders the model.\n */\n @Override\n public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {\n }\n\n public void renderEnchanted() {\n renderAll();\n renderEnchantment();\n }\n\n protected void renderEnchantment() {\n float tickModifier = (float) (Minecraft.getSystemTime() % 3000L) / 3000F * 48;\n TileEntityGraveStoneRenderer.instance.bindTextureByName(Resources.SWORD_AURA);\n\n GlStateManager.enableBlend();\n GlStateManager.depthFunc(GL11.GL_EQUAL);\n GlStateManager.depthMask(false);\n float color = 0.5F;\n GlStateManager.color(color, color, color, 1);\n\n for (int i = 0; i < 3; i++) {\n GlStateManager.disableLighting();\n GlStateManager.blendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE);\n float color2 = 0.76F;\n GlStateManager.color(0.5F * color2, 0.25F * color2, 0.8F * color2, 1);\n GlStateManager.matrixMode(GL11.GL_TEXTURE);\n GlStateManager.loadIdentity();\n\n float var23 = tickModifier * (0.001F + i * 0.0015F) * 15;\n float scale = 0.33F;\n GlStateManager.scale(scale, scale, scale);\n GlStateManager.rotate(30 - i * 60, 0, 0, 1);\n GlStateManager.translate(0, var23, 0);\n GlStateManager.matrixMode(GL11.GL_MODELVIEW);\n\n renderAll();\n }\n\n GlStateManager.matrixMode(GL11.GL_TEXTURE);\n GlStateManager.loadIdentity();\n GlStateManager.matrixMode(GL11.GL_MODELVIEW);\n GlStateManager.enableLighting();\n GlStateManager.depthMask(true);\n GlStateManager.depthFunc(GL11.GL_LEQUAL);\n GlStateManager.disableBlend();\n }\n\n public void setPedestalTexture(ResourceLocation texture) {\n }\n}", "public class TileEntityGraveStone extends TileEntityGrave implements ITickable, ISpawnerEntity {\n\n public static GraveSpawnerHelper graveSpawnerHelper = new GraveSpawnerHelper();\n\n protected ItemStack sword = null;\n protected ItemStack flower = null;\n protected String playerId = \"\";\n protected boolean isPurified = false;\n protected int spawnerHelperId;\n protected GroupOfGravesSpawnerHelper spawnerHelper;\n protected ISpawner spawner;\n public static IFog fogHandler = new IFog() {\n };\n\n public TileEntityGraveStone() {\n super();\n spawner = graveSpawnerHelper.getSpawner(this);\n inventory = new GraveInventory(this);\n }\n\n public TileEntityGraveStone(World world) {\n this();\n this.setWorld(world);\n }\n\n @Override\n public void update() {\n if (spawnerHelperId != 0 && spawnerHelper == null) {\n Entity entity = this.getWorld().getEntityByID(spawnerHelperId);\n\n if (entity instanceof GroupOfGravesSpawnerHelper) {\n spawnerHelper = (GroupOfGravesSpawnerHelper) entity;\n }\n }\n\n spawner.update();\n\n fogHandler.addFog(this.getWorld(), this.pos);\n }\n\n @Override\n public World getIWorld() {\n return getWorld();\n }\n\n @Override\n public BlockPos getIPos() {\n return getPos();\n }\n\n @Override\n public boolean receiveClientEvent(int par1, int par2) {\n if (par1 == 1 && this.getWorld().isRemote) {\n spawner.setMinDelay();\n }\n\n return true;\n }\n\n @Override\n public void readFromNBT(NBTTagCompound nbtTag) {\n super.readFromNBT(nbtTag);\n // age\n age = nbtTag.getInteger(\"Age\");\n // grave loot\n inventory.readItems(nbtTag);\n // death text\n deathText.readText(nbtTag);\n // sword\n readSwordInfo(nbtTag);\n // flower\n readFlowerInfo(nbtTag);\n // owner\n playerId = nbtTag.getString(\"PlayerId\");\n\n isPurified = nbtTag.getBoolean(\"Purified\");\n\n //spawnerHelper\n if (nbtTag.hasKey(\"SpawnerHelperId\")) {\n spawnerHelperId = nbtTag.getInteger(\"SpawnerHelperId\");\n }\n }\n\n @Override\n public NBTTagCompound writeToNBT(NBTTagCompound nbtTag) {\n nbtTag = super.writeToNBT(nbtTag);\n // age\n nbtTag.setInteger(\"Age\", age);\n // grave loot\n inventory.saveItems(nbtTag);\n // death text\n deathText.saveText(nbtTag);\n // sword\n writeSwordInfo(nbtTag);\n // flower\n writeFlowerInfo(nbtTag);\n // owner\n nbtTag.setString(\"PlayerId\", playerId);\n\n nbtTag.setBoolean(\"Purified\", isPurified);\n\n //spawnerHelper\n if (haveSpawnerHelper()) {\n nbtTag.setInteger(\"SpawnerHelperId\", spawnerHelper.getEntityId());\n }\n return nbtTag;\n }\n\n private void readSwordInfo(NBTTagCompound nbtTag) {\n if (nbtTag.hasKey(\"Sword\")) {\n sword = new ItemStack(nbtTag.getCompoundTag(\"Sword\"));\n }\n }\n\n private void writeSwordInfo(NBTTagCompound nbtTag) {\n if (sword != null) {\n NBTTagCompound swordNBT = new NBTTagCompound();\n sword.writeToNBT(swordNBT);\n nbtTag.setTag(\"Sword\", swordNBT);\n }\n }\n\n private void readFlowerInfo(NBTTagCompound nbtTag) {\n if (nbtTag.hasKey(\"Flower\")) {\n flower = new ItemStack(nbtTag.getCompoundTag(\"Flower\"));\n }\n }\n\n private void writeFlowerInfo(NBTTagCompound nbtTag) {\n if (flower != null) {\n NBTTagCompound flowerNBT = new NBTTagCompound();\n flower.writeToNBT(flowerNBT);\n nbtTag.setTag(\"Flower\", flowerNBT);\n }\n }\n\n public ItemStack getSword() {\n return this.sword;\n }\n\n public void setSword(ItemStack sword) {\n this.sword = sword;\n }\n\n public void dropSword() {\n if (this.sword != null) {\n this.inventory.dropItem(this.sword, this.getWorld(), this.pos);\n }\n }\n\n public boolean isSwordGrave() {\n return sword != null;\n }\n\n public boolean canBeMossy() {\n return !isSwordGrave() && this.getGraveType() != EnumGraves.STARVED_CORPSE && this.getGraveType() != EnumGraves.WITHERED_CORPSE;\n }\n\n\n public ItemStack getFlower() {\n return this.flower;\n }\n\n public void setFlower(ItemStack flower) {\n this.flower = flower;\n }\n\n public void dropFlower() {\n if (this.flower != null) {\n this.inventory.dropItem(this.flower, this.getWorld(), this.pos);\n }\n }\n\n public boolean hasFlower() {\n return flower != null;\n }\n\n public EnumGraves getGraveType() {\n return EnumGraves.getById(graveType);\n }\n\n public boolean isEmpty() {\n return inventory.isEmpty();\n }\n\n // @Override\n // public void setGraveContent(Random random, boolean isPetGrave, GraveInventory.GraveContentType contentType, GraveInventory.GraveCorpseContentType corpseType) {\n //// setRandomAge();//TODO\n //// setRandomFlower(random);//TODO\n // }\n\n\n public String getOwner() {\n return this.playerId;\n }\n\n public void setOwner(String playerId) {\n this.playerId = playerId;\n }\n\n public boolean canBeLooted(EntityPlayer player) {\n if (Config.onlyOwnerCanLootGrave) {\n if (player != null) {\n String playerId = player.getUniqueID().toString();\n return player.isCreative() || StringUtils.isBlank(this.playerId) || playerId.equals(this.playerId) || inventory.getGraveContent().isEmpty();\n }\n return false;\n }\n return true;\n }\n\n @Override\n public boolean haveSpawnerHelper() {\n return spawnerHelper != null;\n }\n\n @Override\n public GroupOfGravesSpawnerHelper getSpawnerHelper() {\n return spawnerHelper;\n }\n\n public void setSpawnerHelper(GroupOfGravesSpawnerHelper spawnerHelper) {\n this.spawnerHelper = spawnerHelper;\n if (spawnerHelper != null) {\n this.spawnerHelperId = spawnerHelper.getEntityId();\n }\n }\n\n public boolean isPurified() {\n return isPurified;\n }\n\n public void setPurified(boolean isPurified) {\n this.isPurified = isPurified;\n }\n}" ]
import com.google.common.collect.Maps; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderEntityItem; import net.minecraft.client.renderer.texture.LayeredTexture; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import nightkosh.gravestone.api.grave.EnumGraveType; import nightkosh.gravestone.block.enums.EnumGraves; import nightkosh.gravestone.config.Config; import nightkosh.gravestone.core.Resources; import nightkosh.gravestone.models.block.ModelGraveStone; import nightkosh.gravestone.models.block.graves.*; import nightkosh.gravestone.tileentity.TileEntityGraveStone; import org.lwjgl.opengl.GL11; import java.util.HashMap; import java.util.Map;
package nightkosh.gravestone.renderer.tileentity; /** * GraveStone mod * * @author NightKosh * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ @SideOnly(Side.CLIENT) public class TileEntityGraveStoneRenderer extends TileEntityRenderer { protected static final Map<EnumGraves, ResourceLocation> mossyTexturesMap = Maps.newHashMap(); public static ModelGraveStone verticalPlate = new ModelVerticalPlateGraveStone(); public static ModelGraveStone cross = new ModelCrossGraveStone(); public static ModelGraveStone obelisk = new ModelObeliskGravestone(); public static ModelGraveStone celticCross = new ModelCelticCrossGravestone(); public static ModelGraveStone horizontalPlate = new ModelHorizontalPlateGraveStone(); public static ModelGraveStone villagerStatue = new ModelVillagerStatueGravestone(); public static ModelGraveStone dogStatue = new ModelDogStatueGraveStone(); public static ModelGraveStone catStatue = new ModelCatStatueGraveStone(); public static ModelGraveStone horseStatue = new ModelHorseGraveStone(); public static ModelGraveStone creeperStatue = new ModelCreeperStatueGravestone(); public static ModelGraveStone skeletonCorpse = new ModelSkeletonCorpseGravestone(false); public static ModelGraveStone witheredSkeletonCorpse = new ModelSkeletonCorpseGravestone(true); public static ModelGraveStone swordModel = new ModelSwordGraveStone(); public static TileEntityGraveStoneRenderer instance;
protected static final TileEntityGraveStone GRAVE_TE = new TileEntityGraveStone();
4
SergioDim3nsions/RealmContactsForAndroid
presentation/src/main/java/sergio/vasco/androidforexample/presentation/sections/main/MainPresenter.java
[ "public interface Bus {\n void post(Object object);\n void postInmediate(Object object);\n void register(Object object);\n void unregister(Object object);\n}", "public interface InteractorInvoker {\n void execute(Interactor interactor);\n void execute(Interactor interactor, InteractorPriority priority);\n}", "public class GetContactsFromDataBaseInteractor implements Interactor {\n\n private Bus bus;\n private GetContactsEvent event;\n private ContactsRepository contactsRepository;\n\n public GetContactsFromDataBaseInteractor(Bus bus, ContactsRepository contactsRepository) {\n this.bus = bus;\n this.contactsRepository = contactsRepository;\n this.event = new GetContactsEvent();\n }\n\n @Override public void execute() throws Throwable {\n List<Contact> contactList = contactsRepository.getContacts();\n event.setContactList(contactList);\n bus.post(event);\n }\n}", "public class InsertContactsIntoDataBaseInteractor implements Interactor {\n\n private Contact contact;\n private ContactsRepository contactsRepository;\n private Bus bus;\n\n public InsertContactsIntoDataBaseInteractor(Bus bus,ContactsRepository contactsRepository) {\n this.bus = bus;\n this.contactsRepository = contactsRepository;\n }\n\n @Override public void execute() throws Throwable {\n contactsRepository.insertContact(contact);\n }\n\n public void setContact(Contact contact) {\n this.contact = contact;\n }\n}", "public class GetContactsEvent extends BaseEvent {\n private List<Contact> contactList;\n\n public List<Contact> getContactList() {\n return contactList;\n }\n\n public void setContactList(List<Contact> contactList) {\n this.contactList = contactList;\n }\n}", "public class Contact {\n\n private int idContact;\n private String firstName;\n private String lastName;\n private int phone;\n private String email;\n\n public int getIdContact() {\n return idContact;\n }\n\n public void setIdContact(int idContact) {\n this.idContact = idContact;\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 int getPhone() {\n return phone;\n }\n\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n}", "public abstract class Presenter {\n public abstract void onResume();\n public abstract void onPause();\n}", "public class PresentationContactMapper {\n\n public Contact presentationContactToContact(PresentationContact presentationContact){\n Contact contact = new Contact();\n contact.setIdContact(presentationContact.getIdContact());\n contact.setFirstName(presentationContact.getFirstName());\n contact.setLastName(presentationContact.getLastName());\n contact.setEmail(presentationContact.getEmail());\n contact.setPhone(presentationContact.getPhone());\n return contact;\n }\n\n public PresentationContact contactToPresentationContact(Contact contact){\n PresentationContact presentationContact = new PresentationContact();\n presentationContact.setIdContact(contact.getIdContact());\n presentationContact.setFirstName(contact.getFirstName());\n presentationContact.setLastName(contact.getLastName());\n presentationContact.setEmail(contact.getEmail());\n presentationContact.setPhone(contact.getPhone());\n return presentationContact;\n }\n\n public List<PresentationContact> ContactsListToPresentationContactList(List<Contact> contactList){\n List<PresentationContact> presentationContactList = new ArrayList<>();\n\n for (Contact contact : contactList) {\n PresentationContact presentationContact = contactToPresentationContact(contact);\n presentationContactList.add(presentationContact);\n }\n return presentationContactList;\n }\n}", "public class PresentationContact {\n\n private int idContact;\n private String firstName;\n private String lastName;\n private int phone;\n private String email;\n\n public int getIdContact() {\n return idContact;\n }\n\n public void setIdContact(int idContact) {\n this.idContact = idContact;\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 int getPhone() {\n return phone;\n }\n\n public void setPhone(int phone) {\n this.phone = phone;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n}" ]
import java.util.List; import sergio.vasco.androidforexample.domain.abstractions.Bus; import sergio.vasco.androidforexample.domain.interactors.InteractorInvoker; import sergio.vasco.androidforexample.domain.interactors.main.GetContactsFromDataBaseInteractor; import sergio.vasco.androidforexample.domain.interactors.main.InsertContactsIntoDataBaseInteractor; import sergio.vasco.androidforexample.domain.interactors.main.events.GetContactsEvent; import sergio.vasco.androidforexample.domain.model.Contact; import sergio.vasco.androidforexample.presentation.Presenter; import sergio.vasco.androidforexample.presentation.mappers.PresentationContactMapper; import sergio.vasco.androidforexample.presentation.model.PresentationContact;
package sergio.vasco.androidforexample.presentation.sections.main; /** * Name: Sergio Vasco * Date: 14/1/16. */ public class MainPresenter extends Presenter { private MainView view; private Bus bus; private InteractorInvoker interactorInvoker; private InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor; private GetContactsFromDataBaseInteractor getContactsFromDataBaseInteractor; private PresentationContactMapper presentationContactMapper; public MainPresenter(MainView view, Bus bus, InteractorInvoker interactorInvoker, InsertContactsIntoDataBaseInteractor insertContactsIntoDataBaseInteractor, GetContactsFromDataBaseInteractor getContactsFromDataBaseInteractor, PresentationContactMapper presentationContactMapper) { this.view = view; this.bus = bus; this.interactorInvoker = interactorInvoker; this.insertContactsIntoDataBaseInteractor = insertContactsIntoDataBaseInteractor; this.getContactsFromDataBaseInteractor = getContactsFromDataBaseInteractor; this.presentationContactMapper = presentationContactMapper; }
public void insertContactIntoDataBase(PresentationContact presentationContact) {
8
Leviathan-Studio/CraftStudioAPI
src/mod/java/com/leviathanstudio/test/common/entity/EntityTest2.java
[ "@Mod(modid = CraftStudioApi.API_ID, name = CraftStudioApi.NAME, updateJSON = \"https://leviathan-studio.com/craftstudioapi/update.json\",\n version = \"1.0.0\",\n acceptedMinecraftVersions = \"1.12\")\npublic class CraftStudioApi\n{\n private static final Logger LOGGER = LogManager.getLogger(\"CraftStudio\");\n public static final String API_ID = \"craftstudioapi\";\n static final String NAME = \"CraftStudio API\";\n\n public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(CraftStudioApi.API_ID);\n\n @SidedProxy(clientSide = \"com.leviathanstudio.craftstudio.proxy.CSClientProxy\", serverSide = \"com.leviathanstudio.craftstudio.proxy.CSServerProxy\")\n private static CSCommonProxy proxy;\n\n @EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n CraftStudioApi.proxy.preInit(event);\n }\n\n public static Logger getLogger() {\n return CraftStudioApi.LOGGER;\n }\n\n /**\n * Helper to create an AnimationHandler to registry animation to your\n * entity/block\n *\n * @param <T>\n *\n * @param animated\n * Class which implements IAnimated (Entity or TileEntity)\n */\n public static <T extends IAnimated> AnimationHandler<T> getNewAnimationHandler(Class<T> animatedClass) {\n return CraftStudioApi.proxy.getNewAnimationHandler(animatedClass);\n\n }\n}", "public abstract class AnimationHandler<T extends IAnimated>\n{\n /** List of the channels name to give them ids */\n protected List<String> channelIds = new ArrayList<>();\n\n /**\n * Add animation to the IAnimated instance, entity or block\n *\n * @param modid\n * The id of your mod\n * @param animNameIn\n * The name of the animation you want to add\n * @param modelNameIn\n * The name of the parent model of your animation\n * @param looped\n * Is a looped or not animation\n */\n public void addAnim(String modid, String animNameIn, String modelNameIn, boolean looped) {\n ResourceLocation anim = new ResourceLocation(modid, animNameIn);\n this.channelIds.add(anim.toString());\n }\n\n /**\n * Add animation to the IAnimated instance, entity or block\n *\n * @param modid\n * The id of your mod\n * @param animNameIn\n * The name of the animation you want to add\n * @param modelNameIn\n * The name of the parent model of your animation\n * @param customChannelIn\n * Your custom channel for hard coded animations, (ex: lookAt)\n */\n public void addAnim(String modid, String animNameIn, CustomChannel customChannelIn) {\n ResourceLocation anim = new ResourceLocation(modid, animNameIn);\n this.channelIds.add(anim.toString());\n }\n\n /**\n * Add an inverted animation to the IAnimated instance, entity or block\n *\n * @param modid\n * The id of your mod\n * @param invertedAnimationName\n * The name of the inverted animation you want to add\n * @param animationToInvert\n * The name the animation you want to invert\n */\n public void addAnim(String modid, String invertedAnimationName, String animationToInvert) {\n ResourceLocation anim = new ResourceLocation(modid, invertedAnimationName);\n this.channelIds.add(anim.toString());\n }\n\n /**\n * Start an animation on client side.\n * \n * @param res\n * The animation to start.\n * @param startingFrame\n * The frame to start on.\n * @param animatedElement\n * The animated object.\n */\n public void startAnimation(String res, float startingFrame, T animatedElement) {\n if (animatedElement.isWorldRemote())\n this.clientStartAnimation(res, startingFrame, animatedElement);\n }\n\n /**\n * Start an animation across the network. This is just a message send, avoid\n * using with \"hold last keyframe\" animations or long animations. In those\n * cases, prefer using {@link #startAnimation(String, float, IAnimated)} and\n * a custom network updating system.\n * \n * @param res\n * The animation to start.\n * @param startingFrame\n * The frame to start on.\n * @param animatedElement\n * The animated object.\n * @param clientSend\n * If false, the packet will be send be the server only. If true,\n * the packet will be send by the clients only.\n */\n public void networkStartAnimation(String res, float startingFrame, T animatedElement, boolean clientSend) {\n if (animatedElement.isWorldRemote() == clientSend) {\n this.serverInitAnimation(res, startingFrame, animatedElement);\n CSNetworkHelper.sendIAnimatedEvent(\n new IAnimatedEventMessage(EnumIAnimatedEvent.START_ANIM, animatedElement, this.getAnimIdFromName(res), startingFrame));\n }\n }\n\n /**\n * Start an animation on this client only. Do nothing on server.\n * \n * @param res\n * The animation to start.\n * @param startingFrame\n * The frame to start on.\n * @param animatedElement\n * The object that is animated.\n * @return True, if the animation is successfully started.\n */\n protected abstract boolean clientStartAnimation(String res, float startingFrame, T animatedElement);\n\n /**\n * Initialize an animation on the server and wait for a\n * {@link #serverStartAnimation(String, float, IAnimated)}.\n * \n * @param res\n * The animation to initialize.\n * @param startingFrame\n * The frame the animation will be started on.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully initialized.\n */\n protected abstract boolean serverInitAnimation(String res, float startingFrame, T animatedElement);\n\n /**\n * Start an initialized animation on the server.\n * \n * @param res\n * The animation to start.\n * @param endingFrame\n * The ending frame of the animation.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully started.\n */\n protected abstract boolean serverStartAnimation(String res, float endingFrame, T animatedElement);\n\n public void stopAnimation(String res, T animatedElement) {\n if (animatedElement.isWorldRemote())\n this.clientStopAnimation(res, animatedElement);\n }\n\n /**\n * Stop an animation across the network.\n * \n * @param res\n * The animation to stop.\n * @param animatedElement\n * The animated object.\n * @param clientSend\n * If false, the packet will be send be the server only. If true,\n * the packet will be send by the clients only.\n */\n public void networkStopAnimation(String res, T animatedElement, boolean clientSend) {\n if (animatedElement.isWorldRemote() == clientSend) {\n this.serverStopAnimation(res, animatedElement);\n CSNetworkHelper.sendIAnimatedEvent(new IAnimatedEventMessage(EnumIAnimatedEvent.STOP_ANIM, animatedElement, this.getAnimIdFromName(res)));\n }\n }\n\n /**\n * Stop an animation on this client only.\n * \n * @param res\n * The animation to stop.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully stopped.\n */\n protected abstract boolean clientStopAnimation(String res, T animatedElement);\n\n /**\n * Stop an animation on the server only.\n * \n * @param res\n * The animation to stop.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully stopped.\n */\n protected abstract boolean serverStopAnimation(String res, T animatedElement);\n\n public void stopStartAnimation(String animToStop, String animToStart, float startingFrame, T animatedElement) {\n if (animatedElement.isWorldRemote())\n this.clientStopStartAnimation(animToStop, animToStart, startingFrame, animatedElement);\n }\n\n /**\n * Stop an animation and directly start another across the network.\n * \n * @param animToStop\n * The animation to stop.\n * @param animToStart\n * The animation to start.\n * @param startingFrame\n * The frame to start the animation on.\n * @param animatedElement\n * The animated object.\n * @param clientSend\n * If false, the packet will be send be the server only. If true,\n * the packet will be send by the clients only.\n */\n public void networkStopStartAnimation(String animToStop, String animToStart, float startingFrame, T animatedElement, boolean clientSend) {\n if (animatedElement.isWorldRemote() == clientSend) {\n this.serverStopStartAnimation(animToStop, animToStart, startingFrame, animatedElement);\n CSNetworkHelper.sendIAnimatedEvent(new IAnimatedEventMessage(EnumIAnimatedEvent.STOP_START_ANIM, animatedElement,\n this.getAnimIdFromName(animToStart), startingFrame, this.getAnimIdFromName(animToStop)));\n }\n }\n\n /**\n * Stop an animation and directly start another on this client. Same as\n * doing clientStopAnimation(); clientStartAnimation();\n * \n * @param animToStop\n * The animation to stop.\n * @param animToStart\n * The animation to start.\n * @param startingFrame\n * The frame to start the animation on.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully stopped and the other\n * animation was successfully started.\n */\n protected boolean clientStopStartAnimation(String animToStop, String animToStart, float startingFrame, T animatedElement) {\n boolean stopSucces = this.clientStopAnimation(animToStop, animatedElement);\n return this.clientStartAnimation(animToStart, startingFrame, animatedElement) && stopSucces;\n }\n\n /**\n * Stop an animation and directly initialize another on the server.\n * \n * @param animToStop\n * The animation to stop.\n * @param animToStart\n * The animation to initialize.\n * @param startingFrame\n * The frame to start the animation on.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully stopped and the other\n * animation was successfully initialized.\n */\n protected boolean serverStopStartAnimation(String animToStop, String animToStart, float startingFrame, T animatedElement) {\n boolean stopSucces = this.serverStopAnimation(animToStop, animatedElement);\n return this.serverInitAnimation(animToStart, startingFrame, animatedElement) && stopSucces;\n }\n\n /**\n * Update the animation. Should be done every ticks.\n * \n * @param animatedElement\n * The animated object.\n */\n public abstract void animationsUpdate(T animatedElement);\n\n /**\n * Check if an animation is active for an IAnimated.\n * \n * @param name\n * The name of the animation to check.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is running. False, otherwise.\n */\n public abstract boolean isAnimationActive(String name, T animatedElement);\n\n /**\n * Check if an hold animation is active for an IAnimated.\n *\n * @param name\n * The animation you want to check.\n * @param animatedElement\n * The object that is animated.\n * @return True, if the animation is running or holding on the last key,\n * false otherwise.\n */\n public abstract boolean isHoldAnimationActive(String name, T animatedElement);\n\n /**\n * Update the tick timer of the animation or stop it if it should.\n * \n * @param channel\n * The animation to update.\n * @param animatedElement\n * The animated object.\n * @return True, if the tick timer was updated. False, if the animation was\n * stopped.\n */\n public abstract boolean canUpdateAnimation(Channel channel, T animatedElement);\n\n /**\n * Get an animation name from its id. Used for network messages.\n * \n * @param id\n * The animation id.\n * @return The name of the animation, null if the id doesn't exist.\n */\n public String getAnimNameFromId(short id) {\n return this.channelIds.get(id);\n }\n\n /**\n * Get the id of an animation from its name. Used for network messages.\n * \n * @param name\n * The animation name.\n * @return The id of the animation, -1 if the animation doesn't exist.\n */\n public short getAnimIdFromName(String name) {\n return (short) this.channelIds.indexOf(name);\n }\n\n /**\n * Method called when a network message is received in the client.\n * \n * @param message\n * The message.\n * @return True, if the message was correctly processed and a response\n * should be send if it's needed.\n */\n public boolean onClientIAnimatedEvent(IAnimatedEventMessage message) {\n AnimationHandler hand = message.animated.getAnimationHandler();\n switch (EnumIAnimatedEvent.getEvent(message.event)) {\n case START_ANIM:\n return hand.clientStartAnimation(hand.getAnimNameFromId(message.animId), message.keyframeInfo, message.animated);\n case STOP_ANIM:\n return hand.clientStopAnimation(hand.getAnimNameFromId(message.animId), message.animated);\n case STOP_START_ANIM:\n return hand.clientStopStartAnimation(hand.getAnimNameFromId(message.optAnimId), hand.getAnimNameFromId(message.animId),\n message.keyframeInfo, message.animated);\n default:\n return false;\n }\n }\n\n /**\n * Methods called when a network message is received on the server.\n * \n * @param message\n * The message.\n * @return True, if the message was correctly processed and should be send\n * to all the clients in range.\n */\n public static boolean onServerIAnimatedEvent(IAnimatedEventMessage message) {\n AnimationHandler hand = message.animated.getAnimationHandler();\n switch (EnumIAnimatedEvent.getEvent(message.event)) {\n case START_ANIM:\n return hand.serverInitAnimation(hand.getAnimNameFromId(message.animId), message.keyframeInfo, message.animated);\n case ANSWER_START_ANIM:\n return hand.serverStartAnimation(hand.getAnimNameFromId(message.animId), message.keyframeInfo, message.animated);\n case STOP_ANIM:\n hand.serverStopAnimation(hand.getAnimNameFromId(message.animId), message.animated);\n return true;\n case STOP_START_ANIM:\n hand.serverStopStartAnimation(hand.getAnimNameFromId(message.optAnimId), hand.getAnimNameFromId(message.animId), message.keyframeInfo,\n message.animated);\n return true;\n default:\n return false;\n }\n }\n\n /**\n * A class that hold ticks and frames informations about an animation.\n * \n * @since 0.3.0\n * \n * @author Timmypote\n */\n public static class AnimInfo\n {\n /** The previous time the animation was updated.. */\n public long prevTime;\n /** The previous frame the animation was on. */\n public float currentFrame;\n\n /** Constructor */\n public AnimInfo(long prevTime, float currentFrame) {\n this.prevTime = prevTime;\n this.currentFrame = currentFrame;\n }\n }\n\n ///////////////////////////////////////\n // Overloaded methods for easier use //\n ///////////////////////////////////////\n\n /**\n * See {@link #startAnimation(String, String, float, IAnimated)}.<br>\n * startingFrame is set to 0.\n */\n public void startAnimation(String modid, String animationName, T animatedElement) {\n this.startAnimation(modid, animationName, 0.0F, animatedElement);\n }\n\n /**\n * Start an animation on this client only. Do nothing on server.\n * \n * @param modid\n * The ID of your mod.\n * @param animationName\n * The name of your animation you want to start.\n * @param startingFrame\n * The frame to start on.\n * @param animatedElement\n * The object that is animated.\n * @return True, if the animation is successfully started.\n */\n public void startAnimation(String modid, String animationName, float startingFrame, T animatedElement) {\n this.startAnimation(modid + \":\" + animationName, startingFrame, animatedElement);\n }\n\n /**\n * See\n * {@link #networkStartAnimation(String, String, IAnimated, boolean)}.<br>\n * clientSend is set to False.\n */\n public void networkStartAnimation(String modid, String animationName, T animatedElement) {\n this.networkStartAnimation(modid, animationName, 0.0F, animatedElement, false);\n }\n\n /**\n * See\n * {@link #networkStartAnimation(String, String, float, IAnimated, boolean)}.<br>\n * startingFrame is set to 0.\n */\n public void networkStartAnimation(String modid, String animationName, T animatedElement, boolean clientSend) {\n this.networkStartAnimation(modid, animationName, 0.0F, animatedElement, clientSend);\n }\n\n /**\n * Start an animation across the network. This is just a message send, avoid\n * using with \"hold last keyframe\" animations or long animations. In those\n * cases, prefer using\n * {@link #startAnimation(String, String, float, IAnimated)} and a custom\n * network updating system.\n *\n * @param modid\n * The ID of your mod\n * @param animationName\n * The name of your animation you want to start\n * @param startingFrame\n * The frame you want your animation to start\n * @param animatedElement\n * The IAnimated that is animated.\n * @param clientSend\n * If false, the packet will be send be the server only. If true,\n * the packet will be send by the clients only.\n */\n public void networkStartAnimation(String modid, String animationName, float startingFrame, T animatedElement, boolean clientSend) {\n this.networkStartAnimation(modid + \":\" + animationName, startingFrame, animatedElement, clientSend);\n }\n\n /**\n * Stop an animation on this client only.\n * \n * @param modid\n * The ID of your mod.\n * @param animationName\n * The name of your animation you want to stop.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully stopped.\n */\n public void stopAnimation(String modid, String animationName, T animatedElement) {\n this.stopAnimation(modid + \":\" + animationName, animatedElement);\n }\n\n /**\n * See\n * {@link #networkStopAnimation(String, String, IAnimated, boolean)}.<br>\n * clientSend is set to False.\n */\n public void networkStopAnimation(String modid, String animationName, T animatedElement) {\n this.networkStopAnimation(modid + \":\" + animationName, animatedElement, false);\n }\n\n /**\n * Stop an animation across the network.\n * \n * @param modid\n * The ID of your mod.\n * @param animationName\n * The name of your animation you want to stop.\n * @param animatedElement\n * The animated object.\n * @param clientSend\n * If false, the packet will be send be the server only. If true,\n * the packet will be send by the clients only.\n */\n public void networkStopAnimation(String modid, String animationName, T animatedElement, boolean clientSend) {\n this.networkStopAnimation(modid + \":\" + animationName, animatedElement, clientSend);\n }\n\n /**\n * See\n * {@link #stopStartAnimation(String, String, String, float, IAnimated)}.<br>\n * startingFrame is set to 0.\n */\n public void stopStartAnimation(String modid, String animToStop, String animToStart, T animatedElement) {\n this.stopStartAnimation(modid + \":\" + animToStop, modid + \":\" + animToStart, 0.0F, animatedElement);\n }\n\n /**\n * See\n * {@link #stopStartAnimation(String, String, String, String, float, IAnimated)}.<br>\n * modid1 and modid2 are set to the value of modid.\n * \n * @param modid\n * The ID of your mod.\n */\n public void stopStartAnimation(String modid, String animToStop, String animToStart, float startingFrame, T animatedElement) {\n this.stopStartAnimation(modid + \":\" + animToStop, modid + \":\" + animToStart, startingFrame, animatedElement);\n }\n\n /**\n * Stop an animation and directly start another on this client. Same as\n * doing clientStopAnimation(); clientStartAnimation();\n * \n * @param modid1\n * The ID of the mod of the animation you want to stop.\n * @param animToStop\n * The name of the animation to stop.\n * @param modid2\n * The ID of the mod of the animation you want to start.\n * @param animToStart\n * The name of your animation you want to start.\n * @param startingFrame\n * The frame to start the animation on.\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is successfully stopped and the other\n * animation was successfully started.\n */\n public void stopStartAnimation(String modid1, String animToStop, String modid2, String animToStart, float startingFrame, T animatedElement) {\n this.stopStartAnimation(modid1 + \":\" + animToStop, modid2 + \":\" + animToStart, startingFrame, animatedElement);\n }\n\n /**\n * See\n * {@link #networkStopStartAnimation(String, String, String, IAnimated, boolean)}.<br>\n * clientSend is set to False.\n */\n public void networkStopStartAnimation(String modid, String animToStop, String animToStart, T animatedElement) {\n this.networkStopStartAnimation(modid + \":\" + animToStop, modid + \":\" + animToStart, 0.0F, animatedElement, false);\n }\n\n /**\n * See\n * {@link #networkStopStartAnimation(String, String, String, float, IAnimated, boolean)}.<br>\n * startingFrame is set to 0.\n */\n public void networkStopStartAnimation(String modid, String animToStop, String animToStart, T animatedElement, boolean clientSend) {\n this.networkStopStartAnimation(modid + \":\" + animToStop, modid + \":\" + animToStart, 0.0F, animatedElement, clientSend);\n }\n\n /**\n * See\n * {@link #networkStopStartAnimation(String, String, String, String, float, IAnimated, boolean)}.<br>\n * modid1 and modid2 are set to the value of modid.\n * \n * @param modid\n * The ID of your mod.\n */\n public void networkStopStartAnimation(String modid, String animToStop, String animToStart, float startingFrame, T animatedElement,\n boolean clientSend) {\n this.networkStopStartAnimation(modid + \":\" + animToStop, modid + \":\" + animToStart, startingFrame, animatedElement, clientSend);\n }\n\n /**\n * Stop an animation and directly start another across the network.\n * \n * @param modid1\n * The ID of the mod of the animation you want to stop.\n * @param animToStop\n * The name of the animation to stop.\n * @param modid2\n * The ID of the mod of the animation you want to start.\n * @param animToStart\n * The name of your animation you want to start.\n * @param startingFrame\n * The frame to start the animation on.\n * @param animatedElement\n * The animated object.\n * @param clientSend\n * If false, the packet will be send be the server only. If true,\n * the packet will be send by the clients only.\n */\n public void networkStopStartAnimation(String modid1, String animToStop, String modid2, String animToStart, float startingFrame, T animatedElement,\n boolean clientSend) {\n this.networkStopStartAnimation(modid1 + \":\" + animToStop, modid2 + \":\" + animToStart, startingFrame, animatedElement, clientSend);\n }\n\n /**\n * Check if an animation is active for an IAnimated.\n * \n * @param modid\n * The ID of your mod\n * @param animationName\n * The name of the animation you want to check\n * @param animatedElement\n * The animated object.\n * @return True, if the animation is running. False, otherwise.\n */\n public boolean isAnimationActive(String modid, String animationName, T animatedElement) {\n return this.isAnimationActive(modid + \":\" + animationName, animatedElement);\n }\n}", "public interface IAnimated\n{\n /**\n * Getter to call custom {@link AnimationHandler} class to call useful\n * methods.\n *\n * @see AnimationHandler#addAnim addAnim()\n * @see AnimationHandler#startAnimation startAnimation()\n * @see AnimationHandler#stopAnimation stopAnimation()\n * @see AnimationHandler#isAnimationActive isAnimationActive()\n *\n * @param <T>\n * The animated object class'.\n */\n public <T extends IAnimated> AnimationHandler<T> getAnimationHandler();\n\n /**\n * Getter for the dimension.\n * \n * @return The dimension of the object as a int.\n */\n public int getDimension();\n\n /**\n * Getter for the x coordinate.\n * \n * @return The position on the x axis of the object.\n */\n public double getX();\n\n /**\n * Getter for the y coordinate.\n * \n * @return The position on the y axis of the object.\n */\n public double getY();\n\n /**\n * Getter for the z coordinate.\n * \n * @return The position on the z axis of the object.\n */\n public double getZ();\n\n /**\n * Check if the world of this object is remote or not.\n * \n * @return True, if the world is remote. False, otherwise.\n */\n public boolean isWorldRemote();\n}", "@Mod(name = \"TestMod\", modid = Mod_Test.MODID)\npublic class Mod_Test\n{\n public static final String MODID = \"testmod\";\n\n @SidedProxy(clientSide = \"com.leviathanstudio.test.proxy.ClientProxy\", serverSide = \"com.leviathanstudio.test.proxy.CommonProxy\")\n private static CommonProxy proxy;\n\n @Instance(Mod_Test.MODID)\n private static Mod_Test instance;\n\n public static Mod_Test getInstance() {\n return instance;\n }\n\n public static CommonProxy getProxy() {\n return proxy;\n }\n}", "public class AnimationLootAt extends CustomChannel\n{\n private String headPart;\n\n public AnimationLootAt(String headPartIn) {\n super(\"lookat\");\n this.headPart = headPartIn;\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void update(CSModelRenderer parts, IAnimated animated) {\n if (animated instanceof EntityLiving)\n if (parts.boxName.equals(this.headPart)) {\n EntityLiving entityL = (EntityLiving) animated;\n float diff = entityL.getRotationYawHead() - entityL.renderYawOffset;\n Quat4f quat = MathHelper.quatFromEuler(entityL.rotationPitch, 0.0F, diff);\n Quat4f quat2 = new Quat4f(parts.getDefaultRotationAsQuaternion());\n quat.mul(quat2);\n parts.getRotationMatrix().set(quat);\n parts.getRotationMatrix().transpose();\n }\n }\n\n}" ]
import com.leviathanstudio.craftstudio.CraftStudioApi; import com.leviathanstudio.craftstudio.common.animation.AnimationHandler; import com.leviathanstudio.craftstudio.common.animation.IAnimated; import com.leviathanstudio.test.common.Mod_Test; import com.leviathanstudio.test.pack.animation.AnimationLootAt; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumHand; import net.minecraft.world.World;
package com.leviathanstudio.test.common.entity; public class EntityTest2 extends EntityAnimal implements IAnimated {
protected static AnimationHandler animHandler = CraftStudioApi.getNewAnimationHandler(EntityTest2.class);
1
allan-huang/remote-procedure-call
src/main/java/tw/me/ychuang/rpc/client/ChannelProxy.java
[ "public class Command {\n\tprivate static final Logger log = LoggerFactory.getLogger(Command.class);\n\n\t/**\n\t * A kind of constructor\n\t * \n\t * @param skeleton A skeleton's ID\n\t * @param method A skeleton's method\n\t * @param staticMethod true if the skeleton's method is static\n\t */\n\tpublic Command(String skeleton, String method, boolean staticMethod) {\n\t\tsuper();\n\t\tthis.skeleton = skeleton;\n\t\tthis.method = method;\n\t\tthis.staticMethod = staticMethod;\n\t}\n\n\t/**\n\t * A skeleton's ID\n\t */\n\tprivate final String skeleton;\n\n\t/**\n\t * Getter method for field 'skeleton'\n\t * \n\t * @return skeleton\n\t */\n\tpublic String getSkeleton() {\n\t\treturn this.skeleton;\n\t}\n\n\t/**\n\t * A skeleton's method that will be executed\n\t */\n\tprivate final String method;\n\n\t/**\n\t * Getter method for field 'method'\n\t * \n\t * @return method\n\t */\n\tpublic String getMethod() {\n\t\treturn this.method;\n\t}\n\n\t/**\n\t * The skeleton's method whether is static or not\n\t */\n\tprivate final boolean staticMethod;\n\n\t/**\n\t * Getter method for field 'staticMethod'\n\t * \n\t * @return staticMethod\n\t */\n\tpublic boolean isStaticMethod() {\n\t\treturn this.staticMethod;\n\t}\n\n\t/**\n\t * A value list of the specified parameters are sent for executing a remote skeleton\n\t */\n\tprivate List<Object> parameters = new ArrayList<>();\n\n\t/**\n\t * Getter method for field 'parameters'\n\t * \n\t * @return parameters\n\t */\n\tpublic List<Object> getParameters() {\n\t\treturn this.parameters;\n\t}\n\n\t/**\n\t * A class list of the specified parameters are sent for executing a remote skeleton\n\t */\n\tprivate List<Class> paramClasses = new ArrayList<>();\n\n\t/**\n\t * Getter method for field 'paramClasses'\n\t * \n\t * @return paramClasses\n\t */\n\tpublic List<Class> getParamClasses() {\n\t\treturn this.paramClasses;\n\t}\n\n\t/**\n\t * Adds the pair of a parameter and its class\n\t * \n\t * @param parameter a parameter\n\t * @param paramClass a parameter class\n\t */\n\tpublic void addParameter(Object parameter, Class paramClass) {\n\t\tthis.parameters.add(parameter);\n\t\tthis.paramClasses.add(paramClass);\n\t}\n\n\t/**\n\t * A convenient method for field 'parameters'\n\t * \n\t * @return parameters\n\t */\n\tpublic Object[] findParameters() {\n\t\tObject[] parameters = new Object[0];\n\t\tif (this.parameters != null && false == this.parameters.isEmpty()) {\n\t\t\tparameters = this.parameters.toArray();\n\t\t}\n\n\t\treturn parameters;\n\t}\n\n\t/**\n\t * A convenient method for field 'parameterClasses'\n\t * \n\t * @return parameterClasses\n\t */\n\tpublic Class[] findParamClasses() {\n\t\tClass[] paramClasses = new Class[0];\n\t\tif (this.paramClasses != null && false == this.paramClasses.isEmpty()) {\n\t\t\tparamClasses = new Class[this.paramClasses.size()];\n\t\t\tfor (int i = 0; i < this.paramClasses.size(); i++) {\n\t\t\t\tparamClasses[i] = this.paramClasses.get(i);\n\t\t\t}\n\t\t}\n\n\t\treturn paramClasses;\n\t}\n}", "public final class Constants {\n\n\tpublic static int DEFAULT_THREAD_SIZE = Runtime.getRuntime().availableProcessors() * 2;\n\n\tpublic static int RECONNECT_DELAY = 15;\n\n\tpublic static int MAX_RETRY_TIMES = 3;\n\n\tpublic static int CANCEL_WAITING_REQUEST_DELAY = 7;\n\n\tpublic static int CONNECT_TIMEOUT = 15000;\n\n\tpublic static int HEARTBEAT_PERIOD = 60;\n\n\tpublic static String REQUEST_BOUNDARY = new String(new byte[] { 0 }, CharsetUtil.UTF_8);\n\n\tpublic static long DEFAULT_PERIOD = 10;\n\n\tpublic static TimeUnit DEFAULT_UNIT = TimeUnit.SECONDS;\n\n\t/**\n\t * Channel Selection Type<br>\n\t * <ul>\n\t * <li>Round-Robin</li>\n\t * <li>Workload</li>\n\t * </ul>\n\t */\n\tpublic enum ChannelSelectionType {\n\t\tround_robin, workload;\n\n\t\tpublic static List<String> asLabels() {\n\t\t\tList<String> labels = new ArrayList<String>();\n\t\t\tfor (ChannelSelectionType type : ChannelSelectionType.values()) {\n\t\t\t\tlabels.add(type.toString());\n\t\t\t}\n\t\t\treturn labels;\n\t\t}\n\t}\n\n\t/**\n\t * The caller should be prevented from constructing objects of this class, by declaring this private constructor.\n\t */\n\tprivate Constants() {\n\t\t// this prevents even the native class from\n\t\t// calling this ctor as well :\n\t\tthrow new AssertionError();\n\t}\n}", "public class Request {\n\tprivate static final Logger log = LoggerFactory.getLogger(Request.class);\n\n\t/**\n\t * A specific kind of request is sent to the remote server if it idles too long.\n\t */\n\tpublic static final Request HEARTBEAT = new Request(0L, null);\n\n\t/**\n\t * A kind of constructor\n\t * \n\t * @param id unique id\n\t * @param command a command\n\t */\n\tpublic Request(Long id, Command command) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.command = command;\n\t}\n\n\t/**\n\t * Request's id\n\t */\n\tprivate final Long id;\n\n\t/**\n\t * Getter method for field 'id'\n\t * \n\t * @return request's unqiue id\n\t */\n\tpublic Long getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * A command is wrapped in this request\n\t */\n\tprivate final Command command;\n\n\t/**\n\t * Getter method for field 'command'\n\t * \n\t * @return a command\n\t */\n\tpublic Command getCommand() {\n\t\treturn this.command;\n\t}\n\n\t/**\n\t * A convenience method\n\t * \n\t * @return this request whether a heartbeat message or not\n\t */\n\tpublic boolean isHeartbeat() {\n\t\treturn this.id == 0;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString format = String.format(\"Request-%d\", this.id);\n\n\t\treturn format;\n\t}\n}", "public class Response {\n\tprivate static final Logger log = LoggerFactory.getLogger(Response.class);\n\n\t/**\n\t * A kind of constructor\n\t * \n\t * @param id unique id\n\t * @param result a result\n\t */\n\tpublic Response(Long id, Result result, String resultClass) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.result = result;\n\t\tthis.resultClass = resultClass;\n\t}\n\n\t/**\n\t * Response's id\n\t */\n\tprivate final Long id;\n\n\t/**\n\t * Getter method for field 'id'\n\t * \n\t * @return response's unqiue id\n\t */\n\tpublic Long getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * A result is wrapped in this response\n\t */\n\tprivate final Result result;\n\n\t/**\n\t * Getter method for field 'result'\n\t * \n\t * @return a result\n\t */\n\tpublic Result getResult() {\n\t\treturn this.result;\n\t}\n\n\t/**\n\t * A class name of result\n\t */\n\tprivate final String resultClass;\n\n\t/**\n\t * Getter method for field 'resultClass'\n\t * \n\t * @return a class name of a result\n\t */\n\tpublic String getResultClass() {\n\t\treturn this.resultClass;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString format = String.format(\"Response-%d\", this.id);\n\n\t\treturn format;\n\t}\n}", "public class ResponseFuture<T> implements Future<T> {\n\tprivate static final Logger log = LoggerFactory.getLogger(ResponseFuture.class);\n\n\t/**\n\t * A real response\n\t */\n\tprivate volatile T response;\n\n\t/**\n\t * True if this response future has been cancelled\n\t */\n\tprivate volatile boolean cancelled = false;\n\n\t/**\n\t * Blocks the current stub thread until getting a real response or a timeout\n\t */\n\tprivate final CountDownLatch responseLatch;\n\n\t/**\n\t * A pool retains all response futures are waiting to receive a real response returned from server\n\t */\n\tprivate final ConcurrentMap<Long, ResponseFuture<T>> futurePool;\n\n\t/**\n\t * A kind of constructor\n\t * \n\t * @param id response's id\n\t * @param futurePool response future pool\n\t */\n\tpublic ResponseFuture(Long id, ConcurrentMap<Long, ResponseFuture<T>> futurePool) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.responseLatch = new CountDownLatch(1);\n\t\tthis.futurePool = futurePool;\n\t}\n\n\t/**\n\t * Cancels this future and singals blocked stub thread\n\t */\n\t@Override\n\tpublic boolean cancel(boolean mayInterruptIfRunning) {\n\t\tif (this.isDone()) {\n\t\t\treturn false;\n\n\t\t} else {\n\t\t\tthis.responseLatch.countDown();\n\t\t\tthis.cancelled = true;\n\t\t\tthis.futurePool.remove(this.getId());\n\n\t\t\treturn false == this.isDone();\n\t\t}\n\t}\n\n\t/**\n\t * Response's id\n\t */\n\tprivate final Long id;\n\n\t/**\n\t * Getter method for field 'id'\n\t * \n\t * @return response's id\n\t */\n\tpublic Long getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * Whether this future is cancelled or not\n\t */\n\t@Override\n\tpublic boolean isCancelled() {\n\t\treturn this.cancelled;\n\t}\n\n\t/**\n\t * Whether this future is done or not\n\t */\n\t@Override\n\tpublic boolean isDone() {\n\t\treturn this.responseLatch.getCount() == 0;\n\t}\n\n\t/**\n\t * Blocks the current stub thread until getting a real response\n\t */\n\t@Override\n\tpublic T get() throws InterruptedException {\n\t\ttry {\n\t\t\tthis.responseLatch.await();\n\n\t\t} catch (InterruptedException e) {\n\t\t\tthis.futurePool.remove(this.getId());\n\t\t\tthrow e;\n\t\t}\n\n\t\treturn this.response;\n\t}\n\n\t/**\n\t * Blocks the current stub thread until getting a real response or a timeout\n\t */\n\t@Override\n\tpublic T get(long timeout, TimeUnit unit) throws InterruptedException {\n\t\ttry {\n\t\t\tthis.responseLatch.await(timeout, unit);\n\n\t\t} catch (InterruptedException e) {\n\t\t\tthis.futurePool.remove(this.getId());\n\t\t\tthrow e;\n\t\t}\n\n\t\treturn this.response;\n\t}\n\n\t/**\n\t * Commits a response for signaling the blocking stub thread\n\t * \n\t * @param response a real response\n\t */\n\tpublic void commit(T response) {\n\t\tthis.response = response;\n\t\tthis.responseLatch.countDown();\n\n\t\tthis.futurePool.remove(this.getId());\n\t}\n}", "public class ClientSideException extends RpcException {\n\t/**\n\t * Constructor\n\t * \n\t * @param message the description of this exception\n\t */\n\tpublic ClientSideException(String message) {\n\t\tsuper(message);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param cause the cause of this exception\n\t */\n\tpublic ClientSideException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param message the description of this exception\n\t * @param cause the cause of this exception\n\t */\n\tpublic ClientSideException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param message the description of this exception\n\t * @param cause the cause of this exception\n\t * @param context a context stores the contextual information\n\t */\n\tpublic ClientSideException(String message, Throwable cause, ExceptionContext context) {\n\t\tsuper(message, cause, context);\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * @see org.apache.commons.lang3.exception.ContextedRuntimeException#addContextValue(java.lang.String, java.lang.Object)\n\t */\n\tpublic ClientSideException addContextValue(String label, Object value) {\n\t\tsuper.addContextValue(label, value);\n\n\t\treturn this;\n\t}\n}", "public class RpcException extends ContextedException {\n\t/**\n\t * Constructor\n\t * \n\t * @param message the description of this exception\n\t */\n\tpublic RpcException(String message) {\n\t\tsuper(message);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param cause the cause of this exception\n\t */\n\tpublic RpcException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param message the description of this exception\n\t * @param cause the cause of this exception\n\t */\n\tpublic RpcException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param message the description of this exception\n\t * @param cause the cause of this exception\n\t * @param context a context stores the contextual information\n\t */\n\tpublic RpcException(String message, Throwable cause, ExceptionContext context) {\n\t\tsuper(message, cause, context);\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * @see org.apache.commons.lang3.exception.ContextedRuntimeException#addContextValue(java.lang.String, java.lang.Object)\n\t */\n\tpublic RpcException addContextValue(String label, Object value) {\n\t\tsuper.addContextValue(label, value);\n\n\t\treturn this;\n\t}\n}", "public abstract class JsonSerializer {\n\t/**\n\t * Apply a lazy-loaded singleton - Initialization on Demand Holder.<br>\n\t * see detail on right side: http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom\n\t */\n\tprivate static class LazyHolder {\n\t\tprivate static final JsonSerializer INSTANCE = new GsonSerializer();\n\t}\n\n\tpublic static JsonSerializer getInstance() {\n\t\treturn LazyHolder.INSTANCE;\n\t}\n\n\tprotected JsonSerializer() {\n\t\tsuper();\n\t}\n\n\t/**\n\t * Serializes an object into its equivalent json string\n\t * \n\t * @param src an object\n\t * @param srcClass the specific class of src object.\n\t * @return a json string represents the specified object\n\t */\n\tpublic abstract String toJson(Object src, Class srcClass);\n\n\t/**\n\t * Serializes an object into its equivalent json string\n\t * \n\t * @param src an object\n\t * @return a json element represents the specified object\n\t */\n\tpublic abstract JsonElement toJsonElement(Object src);\n\n\t/**\n\t * Deserializes a json string into an object of the specified class\n\t * \n\t * @param jsonString a json string\n\t * @param srcClass a specific class of the specified object\n\t * @return the specified object\n\t */\n\tpublic abstract <T> T fromJson(String jsonString, Class<T> srcClass);\n\n\t/**\n\t * Deserializes a json element into an object of the specified class\n\t * \n\t * @param jsonElement\n\t * @param srcClass an object of the specified object.\n\t * @return the specified object\n\t */\n\tpublic abstract <T> T fromJsonElement(JsonElement jsonElement, Class<T> srcClass);\n\n}" ]
import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.util.CharsetUtil; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tw.me.ychuang.rpc.Command; import tw.me.ychuang.rpc.Constants; import tw.me.ychuang.rpc.Request; import tw.me.ychuang.rpc.Response; import tw.me.ychuang.rpc.ResponseFuture; import tw.me.ychuang.rpc.exception.ClientSideException; import tw.me.ychuang.rpc.exception.RpcException; import tw.me.ychuang.rpc.json.JsonSerializer;
/** * Getter method for field 'serverHost' * * @return The host / IP of the remote host */ public String getServerHost() { return this.serverHost; } /** * The port number that the remote host listens on */ private final int serverPort; /** * Getter method for field 'serverPort' * * @return The port number that the remote host listens on */ public int getServerPort() { return this.serverPort; } /** * A Netty channel */ private Channel channel; /** * Getter method for field 'channel' * * @return a Netty channel */ public Channel getChannel() { return this.channel; } /** * Setter method for field 'channel' * * @param channel a Netty channel */ public void setChannel(Channel channel) { this.channel = channel; // update latest state of channel if (this.channel.isActive()) { this.channelState = ChannelStateType.active; } else { this.channelState = ChannelStateType.inactive; } } /** * A retained Netty bootstrap in channel proxy for reconnecting purpose */ private Bootstrap bootstrap; /** * Getter method for field 'bootstrap' * * @return a Netty bootstrap */ public Bootstrap getBootstrap() { return this.bootstrap; } /** * Setter method for field 'bootstrap' * * @param channel a Netty bootstrap */ public void setBootstrap(Bootstrap bootstrap) { this.bootstrap = bootstrap; } /** * The channel manager, also it is a container that manages all channel proxies. */ private ClientChannelManager manager; /** * Getter method for field 'manager' * * @return a channel manager */ public ClientChannelManager getManager() { return this.manager; } /** * Setter method for field 'manager' * * @param manager a channel manager */ public void setManager(ClientChannelManager manager) { this.manager = manager; } /** * Sends a command to a remote server by a Netty channel * * @param command a command * @return A future of response implements an asynchronous future pattern. * @throws RpcException if there is no available channel */ public ResponseFuture<Response> send(Command command) throws RpcException { if (false == this.isAvailable()) { RpcException error = new ClientSideException("This channel proxy is unavailable. channel proxy: " + this); log.warn(error.getMessage(), error); throw error; } // get a unique id for each request final Long id = this.nextId(); log.debug("Start to send a request. id: {}", id); // serialize a request with a command to a json message Request request = new Request(id, command);
String requestJson = JsonSerializer.getInstance().toJson(request, Request.class);
7
kaklakariada/fritzbox-java-api
src/main/java/com/github/kaklakariada/fritzbox/TestDriver.java
[ "public enum EnergyStatsTimeRange {\n TEN_MINUTES(\"EnergyStats_10\"), //\n ONE_HOUR(\"EnergyStats_hour\"), //\n ONE_DAY(\"EnergyStats_24h\"), //\n ONE_WEEK(\"EnergyStats_week\"), //\n ONE_MONTH(\"EnergyStats_month\"), //\n ONE_YEAR(\"EnergyStats_year\");\n\n private final String command;\n\n private EnergyStatsTimeRange(String command) {\n this.command = command;\n }\n}", "public abstract class AbstractDeviceStatistics {\n\n /**\n * Supply the Statistics gathered for a chosen grid\n * \n * @param grid\n * grid\n * @return Optional - avoid NPE if no statistics present\n */\n public Optional<Statistics> getStatisticsByGrid(final int grid) {\n return getStats()\n .stream()\n .filter(stats -> stats.getGrid() == grid)\n .findAny();\n }\n\n /**\n * All classes implementing this abstract class need to provide a \"getStats\"-method\n * \n * @return List\n */\n public abstract List<Statistics> getStats();\n\n /**\n * AVM gathers just integer numbers. We know the precision only from documentation, it is never provided by returned\n * responses from Fritz!Box. So we add this information here to the statistics.\n * \n * @param stats statistics to which to add the measurment unit\n * @param measurementUnit the unit to add to the statistics\n * @return statistics with measurement units\n */\n protected List<Statistics> getStats(final List<Statistics> stats, final MeasurementUnit measurementUnit) {\n return stats\n .stream()\n .map(stat -> {\n stat.setMeasurementUnit(measurementUnit);\n return stat;\n })\n .collect(Collectors.toList());\n }\n\n /**\n * All classes implementing this abstract class need to provide a \"statisticsToString\"-method\n * \n * @return List\n */\n protected abstract List<String> statisticsToString();\n\n /**\n * @param type statistics type\n * @return statistics as one line per grid\n */\n protected List<String> statisticsToString(final String type) {\n return getStats()\n .stream()\n .map(stats -> statisticsToString(type, stats))\n .collect(Collectors.toList());\n }\n\n /**\n * Form a line from a single statistic.\n * \n * @param type statistics type\n * @param statistics statistic to convert to {@link String}\n * @return statistic as a line\n */\n private String statisticsToString(final String type, final Statistics statistics) {\n return String.format(\"[%s] count=%s,grid=%s values=[%s]\", type, statistics.getCount(), statistics.getGrid(),\n statistics.getCsvValues());\n }\n}", "@Root(name = \"device\")\npublic class Device {\n\n @Attribute(name = \"identifier\", required = true)\n private String identifier;\n @Attribute(name = \"id\")\n private String id;\n @Attribute(name = \"functionbitmask\")\n private int functionBitmask;\n @Attribute(name = \"fwversion\")\n private String firmwareVersion;\n @Attribute(name = \"manufacturer\")\n private String manufacturer;\n\n @Attribute(name = \"productname\")\n private String productName;\n\n @Element(name = \"present\")\n private String present;\n @Element(name = \"txbusy\", required = false)\n private String txbusy;\n @Element(name = \"name\")\n private String name;\n\n @Element(name = \"batterylow\", required = false)\n private Integer batterylow;\n @Element(name = \"battery\", required = false)\n private Integer battery;\n @Element(name = \"switch\", required = false)\n private SwitchState switchState;\n @Element(name = \"simpleonoff\", required = false)\n private SimpleOnOffState simpleOnOff;\n @Element(name = \"powermeter\", required = false)\n private PowerMeter powerMeter;\n @Element(name = \"temperature\", required = false)\n private Temperature temperature;\n @Element(name = \"hkr\", required = false)\n private Hkr hkr;\n @Element(name = \"levelcontrol\", required = false)\n private LevelControl levelControl;\n @Element(name = \"colorcontrol\", required = false)\n private ColorControl colorControl;\n @Element(name = \"etsiunitinfo\", required = false)\n private EtsiUnitInfo etsiUnitInfo;\n @ElementList(name = \"buttons\", required = false, inline = true)\n private List<Button> buttons;\n @Element(name = \"humidity\", required = false)\n private Humidity humidity;\n @Element(name = \"blind\", required = false)\n private Blind blind;\n @Element(name = \"alert\", required = false)\n private Alert alert;\n\n public String getIdentifier() {\n return identifier;\n }\n\n public String getId() {\n return id;\n }\n\n public int getFunctionBitmask() {\n return functionBitmask;\n }\n\n public String getFirmwareVersion() {\n return firmwareVersion;\n }\n\n public String getManufacturer() {\n return manufacturer;\n }\n\n public String getProductName() {\n return productName;\n }\n\n public boolean isPresent() {\n return \"1\".equals(present);\n }\n\n public boolean isTxBusy() {\n return \"1\".equals(txbusy);\n }\n\n public String getName() {\n return name;\n }\n\n public Optional<Boolean> isBatterylow() {\n return Optional.ofNullable(batterylow).map(value -> 1 == value);\n }\n\n public Optional<Integer> getBattery() {\n return Optional.ofNullable(battery);\n }\n\n public SwitchState getSwitchState() {\n return switchState == null || switchState.isNull() ? null : switchState;\n }\n\n public PowerMeter getPowerMeter() {\n return powerMeter;\n }\n\n public Temperature getTemperature() {\n return temperature;\n }\n\n public Hkr getHkr() {\n return hkr;\n }\n\n public Blind getBlind() {\n return blind;\n }\n\n public Alert getAlert() {\n return alert;\n }\n\n public SimpleOnOffState getSimpleOnOff() {\n return simpleOnOff;\n }\n\n public LevelControl getLevelControl() {\n return levelControl;\n }\n\n public ColorControl getColorControl() {\n return colorControl;\n }\n\n public EtsiUnitInfo getEtsiUnitInfo() {\n return etsiUnitInfo;\n }\n\n public List<Button> getButtons() {\n return buttons;\n }\n\n public String getPresent() {\n return present;\n }\n\n public String getTxbusy() {\n return txbusy;\n }\n\n public Integer getBatterylow() {\n return batterylow;\n }\n\n public Humidity getHumidity() {\n return humidity;\n }\n\n @Override\n public String toString() {\n return \"Device [identifier=\" + identifier + \", id=\" + id + \", functionBitmask=\" + functionBitmask\n + \", firmwareVersion=\" + firmwareVersion + \", manufacturer=\" + manufacturer + \", productName=\"\n + productName + \", present=\" + present + \", txbusy=\" + txbusy + \", name=\" + name + \", batterylow=\"\n + batterylow + \", battery=\" + battery + \", switchState=\" + switchState + \", simpleOnOff=\" + simpleOnOff\n + \", powerMeter=\" + powerMeter + \", temperature=\" + temperature + \", hkr=\" + hkr + \"]\";\n }\n}", "@Root(name = \"devicelist\")\npublic class DeviceList {\n\n @Attribute(name = \"version\")\n private String apiVersion;\n\n @ElementList(name = \"device\", type = Device.class, inline = true)\n private List<Device> devices;\n\n @ElementList(name = \"group\", type = Group.class, inline = true, required = false)\n private List<Group> groups;\n\n\n @Attribute(name = \"fwversion\", required = false, empty = \"n/a\")\n private String firmwareVersion;\n\n public String getApiVersion() {\n return apiVersion;\n }\n\n public List<Device> getDevices() {\n return devices;\n }\n\n public List<Group> getGroups() {\n return groups;\n }\n\n public Device getDeviceByIdentifier(String identifier) {\n return devices.stream() //\n .filter(d -> identifierMatches(d, identifier)) //\n .findFirst().orElse(null);\n }\n\n public List<String> getDeviceIdentifiers() {\n return devices.stream() //\n .map(Device::getIdentifier) //\n .collect(toList());\n }\n\n public String getFirmwareVersion() {\n return firmwareVersion;\n }\n\n private static boolean identifierMatches(Device device, String identifier) {\n return normalizeIdentifier(device.getIdentifier()).equals(normalizeIdentifier(identifier));\n }\n\n private static String normalizeIdentifier(String identifier) {\n return identifier.replace(\" \", \"\");\n }\n\n public Group getGroupById(String id) {\n return groups.stream()\n .filter(group -> group.getId().equals(id))\n .findFirst()\n .orElse(null);\n }\n\n @Override\n public String toString() {\n return \"DeviceList [apiVersion=\" + apiVersion + \", devices=\" + devices + \"]\";\n }\n}", "public enum MeasurementUnit {\n TEMPERATURE(\"C\", 0.1, Temperature.class), \n VOLTAGE(\"V\", 0.001, Voltage.class), \n POWER(\"W\", 0.01, Power.class), \n ENERGY(\"Wh\", 1, Energy.class), \n HUMIDITY(\"%\", 1, Humidity.class);\n\n private final String unit;\n private final Number precision;\n private final Class<?> mapper;\n\n MeasurementUnit(String unit, Number precision, Class<?> mapper) {\n this.unit = unit;\n this.precision = precision;\n this.mapper = mapper;\n }\n\n public String getUnit() {\n return unit;\n }\n\n public Number getPrescision() {\n return precision;\n }\n\n public Class<?> getMapper() {\n return mapper;\n }\n\n public static MeasurementUnit getMatchingMeasurementUnit(Class<?> caller) {\n for (MeasurementUnit iterator : MeasurementUnit.values()) {\n if (caller.isAssignableFrom(iterator.getMapper())) {\n return iterator;\n }\n }\n throw new MissingClassException(String.format(\"Could not detect enum of type 'MeasurementUnit' associated to class '%s'\", caller.toString()));\n }\n}", "@Root(name = \"powermeter\", strict = false)\npublic class PowerMeter {\n\n @Element(name = \"voltage\", required = false)\n private int voltageMilliVolt;\n @Element(name = \"power\", required = false)\n private int powerMilliWatt;\n @Element(name = \"energy\", required = false)\n private int energyWattHours;\n\n public float getVoltageVolt() {\n return voltageMilliVolt / 1000F;\n }\n\n public float getPowerWatt() {\n return powerMilliWatt / 1000F;\n }\n\n public int getEnergyWattHours() {\n return energyWattHours;\n }\n\n public int getPowerMilliWatt() {\n return powerMilliWatt;\n }\n\n @Override\n public String toString() {\n return \"PowerMeter [voltage=\" + getVoltageVolt() + \", energyWattHours=\" + energyWattHours + \", powerWatt=\"\n + getPowerWatt() + \"]\";\n }\n}", "@Root(name = \"stats\")\npublic class Statistics {\n\n private MeasurementUnit measurementUnit;\n\n @Attribute(name = \"count\", required = false)\n private int count;\n\n @Attribute(name = \"grid\", required = false)\n private int grid;\n\n @Text()\n private String csvValues;\n\n public int getCount() {\n return count;\n }\n\n public int getGrid() {\n return grid;\n }\n\n /**\n * Provide the gathered data as provided by Fritz!Box\n * \n * @return\n */\n public String getCsvValues() {\n return csvValues;\n }\n\n /**\n * Just for unit test provided. Therefore it is set to protected\n */\n protected void setCsvValues(String csvValues) {\n this.csvValues = csvValues;\n }\n\n /**\n * Provide the gathered data as computed as meant to be used by AVM\n * \n * @return\n */\n public List<Optional<Number>> getValues() {\n if (getCsvValues() == null) {\n return new ArrayList<>();\n }\n return Arrays.asList(getCsvValues().split(\",\"))\n .stream()\n .map(aValue -> Optional.ofNullable(computeValue(aValue)))\n .collect(Collectors.toList());\n }\n\n /**\n * Provide the measurement unit to be used with the statistics.\n * <p>\n * Consists of:\n * <ul>\n * <li>measurment unit [V, W, Wh, %]</li>\n * <li>precision as double to multiply with the gathered Integer</li>\n * </ul>\n * Sample: The Voltage is measured in 'V' (Volt) and has a precision of '0.001'. The number 237123 provided by the\n * statistics must be multiplied by the precision which gives us 237.123 V.\n * \n * @return\n */\n public MeasurementUnit getMeasurementUnit() {\n return measurementUnit;\n }\n\n public void setMeasurementUnit(final MeasurementUnit measurementUnit) {\n this.measurementUnit = measurementUnit;\n }\n\n protected Number computeValue(String aValue) {\n Number numberValue = null;\n if (StringHelper.isIntegerNumber(aValue)) {\n Integer intValue = Integer.valueOf(aValue.trim());\n if (measurementUnit.getPrescision() instanceof Double) {\n numberValue = Double.valueOf(intValue * (Double) measurementUnit.getPrescision());\n } else {\n numberValue = Integer.valueOf(intValue * (Integer) measurementUnit.getPrescision());\n }\n return numberValue;\n }\n return null;\n }\n}" ]
import com.github.kaklakariada.fritzbox.model.homeautomation.Device; import com.github.kaklakariada.fritzbox.model.homeautomation.DeviceList; import com.github.kaklakariada.fritzbox.model.homeautomation.MeasurementUnit; import com.github.kaklakariada.fritzbox.model.homeautomation.PowerMeter; import com.github.kaklakariada.fritzbox.model.homeautomation.Statistics; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.kaklakariada.fritzbox.EnergyStatisticsService.EnergyStatsTimeRange; import com.github.kaklakariada.fritzbox.model.homeautomation.AbstractDeviceStatistics;
/** * A Java API for managing FritzBox HomeAutomation * Copyright (C) 2017 Christoph Pirkl <christoph at users.sourceforge.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.kaklakariada.fritzbox; public class TestDriver { private static final Logger LOG = LoggerFactory.getLogger(TestDriver.class); public static void main(String[] args) throws InterruptedException { final Properties config = readConfig(Paths.get("application.properties")); final String url = config.getProperty("fritzbox.url"); final String username = config.getProperty("fritzbox.username", null); final String password = config.getProperty("fritzbox.password"); LOG.info("Logging in to '{}' with username '{}'", url, username); final HomeAutomation homeAutomation = HomeAutomation.connect(url, username, password); final DeviceList devices = homeAutomation.getDeviceListInfos(); LOG.info("Found {} devices", devices.getDevices().size()); for (final Device device : devices.getDevices()) { LOG.info("\t{}", device); } final List<String> ids = homeAutomation.getSwitchList(); LOG.info("Found {} device ids: {}", ids.size(), ids); if (devices.getDevices().isEmpty()) { homeAutomation.logout(); return; } final String ain = ids.get(0); // testEnergyStats(homeAutomation, devices.getDevices().get(0).getId()); testEnergyStatsNew(homeAutomation, ain); testVoltageStatsNew(homeAutomation, ain); testHomeAutomation(homeAutomation, ain); } private static void testEnergyStats(HomeAutomation homeAutomation, String deviceId) { final EnergyStatisticsService service = homeAutomation.getEnergyStatistics();
for (final EnergyStatsTimeRange timeRange : EnergyStatsTimeRange.values()) {
0
luoyuan800/IPMIUtil4J
src/main/java/example/GetFruInfo.java
[ "public class IPMIClient {\n\tprivate String IPMI_META_COMMAND = \"\";\n\tprivate String user;\n\tprivate String password;\n\tprivate String host;\n\tprivate CipherSuite cs;\n\tprivate boolean systemPowerUp;\n\tprivate Platform platform;\n\tpublic String getHost() {\n\t\treturn host;\n\t}\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\tpublic CipherSuite getCs() {\n\t\treturn cs;\n\t}\n\n\t/**\n\t * IPMIClient is representative as the target device which support IPMI\n\t * @param host The BMC network address( IPMI card IP)\n\t * @param user The IPMI user name config in the BMC\n\t * @param password The IPMI password config for the user\n\t * @param cs Cipher suite must support when doing initialize\n\t * @see param.CipherSuite\n\t * @param platform The project you want to run in which platform. It was very important.\n\t */\n\tpublic IPMIClient(String host, String user, String password, CipherSuite cs, Platform platform){\n\t\tthis.host = host;\n\t\tthis.password = password;\n\t\tthis.user = user;\n\t\tthis.cs = cs;\n\t\tIPMI_META_COMMAND = platform.getIPMI_META_COMMAND();\n\t\tthis.platform = platform;\n\t}\n\n\t/**\n\t * Verify if this IPMI device could reach by IPMI command.\n\t * @return true, IPMI is eable\n\t * \t\t false, IPMI command faile, maybe this device did not support IPMI or the BMC is down.\n\t */\n\tpublic boolean verify(){\n\t\tChassisStatusRequest request = new ChassisStatusRequest();\n\t\tChassisStatusRespond chassis = request.sendTo(this);\n\t\tsystemPowerUp = chassis.isPowerOn();\n\t\treturn chassis.isChassisStatusOk();\n\t}\n\n\t/**\n\t * Power up the system install in the target device\n\t * @return true, power up complete\n\t */\n\tpublic boolean powerUpSystem(){\n\t\tResetRequest request = new ResetRequest();\n\t\trequest.setPowerUpSystem(true);\n\t\tif(request.sendTo(this).hasRespond()){\n\t\t\tsystemPowerUp = true;\n\t\t\treturn true;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Power down the system in target device chassis\n\t * @return If return true, the IPMIClient.powerUp will set as false\n\t */\n\tpublic boolean powerDownSystem(){\n\t\tResetRequest request = new ResetRequest();\n\t\trequest.setPowerDownSystem(true);\n\t\tif(request.sendTo(this).hasRespond()){\n\t\t\tsystemPowerUp = false;\n\t\t\treturn true;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Power cycle the system in target device chassis\n\t * Will try to check if the system already power up,\n\t * if not, just power up system,\n\t * if yes, will do the restart.\n\t * @return If return true, the IPMIClient.powerUp will set as true\n\t */\n\tpublic boolean powerCycleSystem(){\n\t\tif(systemPowerUp) {\n\t\t\tResetRequest request = new ResetRequest();\n\t\t\trequest.setPowerCycleSystem(true);\n\t\t\treturn request.sendTo(this).hasRespond();\n\t\t}else{\n\t\t\tsystemPowerUp = powerUpSystem();\n\t\t\treturn systemPowerUp;\n\t\t}\n\t}\n\n\t/**\n\t * This command will different for different Platform\n\t * @see param.Platform\n\t * @return The ipmiutil command format for different platforms.\n\t */\n\tpublic String getIPMI_META_COMMAND() {\n\t\treturn IPMI_META_COMMAND;\n\t}\n\n\t/**\n\t * This is not a real time status of the target device system\n\t * If the powerUpSystem() or powerCycleSystem() have been called before, this status will set as true\n\t * @return\n\t * @see #powerUpSystem()\n\t * @see #powerCycleSystem()\n\t */\n\tpublic boolean isSystemPowerUp() {\n\t\treturn systemPowerUp;\n\t}\n\n\tpublic Platform getPlatform() {\n\t\treturn platform;\n\t}\n}", "public class ComponentFru extends Fru {\n\n public ComponentFru(String name) {\n super(name);\n }\n}", "public enum CipherSuite {\n\tcs0(0,\"NONE\", \"NONE\", \"NONE\"),\n cs1(1,\"SHA1\", \"NONE\", \"NONE\"),\n cs2(2,\"SHA1\", \"SHA1_96\", \"NONE\"),\n cs3(3,\"SHA1\", \"SHA1_96\", \"AES_CBC128\"),\n cs4(4,\"SHA1\", \"SHA1_96\", \"XRC4_128\"),\n cs5(5,\"SHA1\", \"SHA1_96\", \"XRC4_40\"),\n cs6(6,\"MD5\", \"NONE\", \"NONE\"),\n cs7(7,\"MD5\", \"MD5_128\", \"NONE\"),\n cs8(8,\"MD5\", \"MD5_128\", \"AES_CBC128\"),\n cs9(9,\"MD5\", \"MD5_128\", \"XRC4_128\"),\n cs10(10,\"MD5\", \"MD5_128\", \"XRC4_40\"),\n cs11(11,\"MD5\", \"MD5_128\", \"NONE\"),\n cs12(12,\"MD5\", \"MD5_128\", \"AES_CBC128\"),\n cs13(13,\"MD5\", \"MD5_128\", \"XRC4_128\"),\n cs14(14,\"MD5\", \"MD5_128\", \"XRC4_40\");\n\tprivate String aa, ia,ca;\n\tprivate int id;\n private CipherSuite(int id, String aa, String ia, String ca) {\n this.aa = aa;\n this.ia = ia;\n this.ca = ca;\n this.id = id;\n }\n public String getAuthenticationAlgorithm(){\n \treturn aa;\n }\n public String getIntegrityAlgorithm(){\n \treturn ia;\n }\n public String getConfidentialityAlgorithm(){\n \treturn ca;\n }\n public int getId(){\n \treturn id;\n }\n}", "public enum Platform {\n TIGPT1U(\"\"),\n NSC2U(\"\"),\n Ubuntu(\"/bin/sh -c ipmiutil\"),\n Linux(\"/bin/sh -c ipmiutil\"),\n Win32(\"cmd.exe /C ipmiutil-win32/ipmiutil\"),\n Win64(\"cmd.exe /C ipmiutil-win64/ipmiutil\");\n\n private String IPMI_META_COMMAND;\n private Platform(String command){\n IPMI_META_COMMAND = command;\n }\n\n public String getIPMI_META_COMMAND() {\n return IPMI_META_COMMAND;\n }\n}", "public class FruRequest extends AbstractRequest {\n private Command command = new Command();\n\n public void setCommand(Command command) {\n this.command = command;\n }\n\n private static final Pattern\n fruTypeP = Pattern.compile(\"^(Component|Mainboard) FRU Size +: +(\\\\d*)$\"),\n pmfP = Pattern.compile(\"^Product Manufacturer: +(.*)$\"),\n pNameP = Pattern.compile(\"^Product Name : (.*)$\"),\n ppNumP = Pattern.compile(\"^Product Part Number : (.*)$\"),\n pVerP = Pattern.compile(\"^Product Version : (.*)$\"),\n pSerNumP = Pattern.compile(\"^Product Serial Num : (.*)$\"),\n pAssTagP = Pattern.compile(\"^Product Asset Tag : *(.*)$\"),\n pFRUFileIDP = Pattern.compile(\"^Product FRU File ID : *(.*)$\"),\n cTypeP = Pattern.compile(\"^Chassis Type : (.*)$\"),\n cPartNumP = Pattern.compile(\"^Chassis Part Number : (.*)$\"),\n cSerNumP = Pattern.compile(\"^Chassis Serial Num : *(.*)$\"),\n cOEMFieldP = Pattern.compile(\"^Chassis OEM Field : (.*)$\"),\n bMfgTimeP = Pattern.compile(\"^Board Mfg DateTime : (.*)$\"),\n bMfP = Pattern.compile(\"^Board Manufacturer : (.*)$\"),\n bPNameP = Pattern.compile(\"^Board Product Name : (.*)$\"),\n bSerNumP = Pattern.compile(\"^Board Serial Number : (.*)$\"),\n bPartNumP = Pattern.compile(\"^Board Part Number : (.*)$\"),\n bFRUFileIDP = Pattern.compile(\"Board FRU File ID : (.*)\"),\n bOEMFileIDP = Pattern.compile(\"^Board OEM Field : *(.*)$\"),\n sysGUIDP = Pattern.compile(\"^System GUID : (.*)$\"),\n biosVerP = Pattern.compile(\"^BIOS Version : (.*)$\"),\n endP = Pattern.compile(\"fruconfig, completed successfully\");\n\n @Override\n public FruRespond sendTo(IPMIClient client) {\n OutputResult or;\n FruRespond fr = new FruRespond();\n String order = buildCommand(client);\n or = command.exeCmd(order);\n if (or != null && or.isNotEmpty()) {\n Fru fru = null;\n String name = \"\";\n for (String line : or) {\n if (StringUtils.isNotEmpty(line)) {\n Matcher matcher = fruTypeP.matcher(line);\n if (matcher.find()) {\n if (matcher.group(1).matches(\"Component\")) {\n fru = new ComponentFru(name);\n } else if (matcher.group(1).matches(\"Mainboard\")) {\n fru = new MainboardFru(name);\n } else {\n fru = new OtherFru(name);\n }\n fru.setFruSize(Integer.parseInt(matcher.group(2)));\n fr.addFru(fru);\n continue;\n }\n if (fru != null) {\n matcher = pmfP.matcher(line);\n if (matcher.find()) {\n fru.setProductManufacturer(matcher.group(1));\n continue;\n }\n matcher = pNameP.matcher(line);\n if (matcher.find()) {\n fru.setProductName(matcher.group(1));\n continue;\n }\n matcher = ppNumP.matcher(line);\n if (matcher.find()) {\n fru.setProductPartNumber(matcher.group(1));\n continue;\n }\n matcher = pVerP.matcher(line);\n if (matcher.find()) {\n fru.setProductVersion(matcher.group(1));\n continue;\n }\n matcher = pSerNumP.matcher(line);\n if (matcher.find()) {\n fru.setProductSerialNum(matcher.group(1));\n continue;\n }\n matcher = pAssTagP.matcher(line);\n if (matcher.find()) {\n fru.setProductAssetTag(matcher.group(1));\n continue;\n }\n matcher = pFRUFileIDP.matcher(line);\n if (matcher.find()) {\n fru.setProductFRUFileID(matcher.group(1));\n continue;\n }\n matcher = cTypeP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setChassisType(matcher.group(1));\n continue;\n }\n matcher = cPartNumP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setChassisPartNumber(matcher.group(1));\n continue;\n }\n matcher = cSerNumP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setChassisSerialNum(matcher.group(1));\n continue;\n }\n matcher = cOEMFieldP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setChassisOEMField(matcher.group(1));\n continue;\n }\n matcher = bMfgTimeP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardMfgDateTime(matcher.group(1));\n continue;\n }\n matcher = bMfP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardManufacturer(matcher.group(1));\n continue;\n }\n matcher = bPNameP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardProductName(matcher.group(1));\n continue;\n }\n matcher = bSerNumP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardSerialNumber(matcher.group(1));\n continue;\n }\n matcher = bPartNumP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardPartNumber(matcher.group(1));\n continue;\n }\n matcher = bFRUFileIDP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardFRUFileID(matcher.group(1));\n continue;\n }\n matcher = bOEMFileIDP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBoardOEMField(matcher.group(1));\n continue;\n }\n matcher = sysGUIDP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setSystemGUID(matcher.group(1));\n continue;\n }\n matcher = biosVerP.matcher(line);\n if (matcher.find()) {\n ((MainboardFru) fru).setBiosVersion(matcher.group(1));\n continue;\n }\n matcher = endP.matcher(line);\n if (matcher.find()) {\n fr.setSuccess(true);\n break;\n }\n }\n name = line;\n }\n }\n }\n return fr;\n }\n\n @Override\n public String getCommandString() {\n String commandString = \"fru\";\n return commandString;\n }\n}", "public class FruRespond implements IPMIRespond{\n private List<Fru> frus;\n private boolean isSuccess;\n public synchronized void addFru(Fru fru){\n if(frus == null){\n frus = new ArrayList<Fru>();\n }\n frus.add(fru);\n }\n @Override\n public boolean hasRespond() {\n return isSuccess;\n }\n\n public void setSuccess(boolean isSuccess) {\n this.isSuccess = isSuccess;\n }\n\n public <T> List<T> getFrus(Class clazz){\n if(frus == null){\n return Collections.emptyList();\n }\n List<T> rs = new ArrayList<T>(frus.size());\n for(Fru fru : frus){\n if(fru.getClass().equals(clazz)){\n rs.add((T)fru);\n }\n }\n return rs;\n }\n}" ]
import client.IPMIClient; import model.ComponentFru; import param.CipherSuite; import param.Platform; import request.FruRequest; import respond.FruRespond;
/* * GetFruInfo.java * Date: 7/10/2015 * Time: 11:04 AM * * Copyright 2015 luoyuan. * ALL RIGHTS RESERVED. */ package example; /** * An example for how to use FruRequest to get the Fru info */ public class GetFruInfo { public static void main(String[]args){
IPMIClient client = new IPMIClient("10.1.1.146", "Adminstrator", "1234567890", CipherSuite.cs3, Platform.Win64 );
2
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProvider.java
[ "public static class Files implements FilesColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build();\n\n\tpublic static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME,\n\t\t\tCOMMENT, NODE_ID };\n\tpublic static final String DEFAULT_SORT = NAME + \" ASC\";\n\n\tpublic static String getId(Uri uri) {\n\t\treturn uri.getLastPathSegment();\n\t}\n\n\tpublic static String getFilename(Uri uri) {\n\t\treturn uri.getPathSegments().get(1);\n\t}\n\n\tpublic static Uri buildFilenameUri(String filename) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(filename)\n\t\t\t\t.appendPath(\"filename\").build();\n\t}\n\n\tpublic static Uri buildIdUri(Long fileId) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(fileId.toString()).build();\n\t}\n}", "public static class OrgData implements OrgDataColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build();\n\n\tpublic static final Uri CONTENT_URI_TODOS =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build();\n\tpublic static final String DEFAULT_SORT = ID + \" ASC\";\n\tpublic static final String NAME_SORT = NAME + \" ASC\";\n\tpublic static final String POSITION_SORT = POSITION + \" ASC\";\n\tpublic static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED,\n\t\t\tPARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY};\n\n\tpublic static String getId(Uri uri) {\n\t\treturn uri.getPathSegments().get(1);\n\t}\n\n\tpublic static Uri buildIdUri(String id) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(id).build();\n\t}\n\n\tpublic static Uri buildIdUri(Long id) {\n\t\treturn buildIdUri(id.toString());\n\t}\n\n\tpublic static Uri buildChildrenUri(String parentId) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(parentId).appendPath(\"children\").build();\n\t}\n\n\tpublic static Uri buildChildrenUri(long node_id) {\n\t\treturn buildChildrenUri(Long.toString(node_id));\n\t}\n}", "public static class Search implements OrgDataColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).build();\n\n\tpublic static String getSearchTerm(Uri uri) {\n\t\treturn uri.getLastPathSegment();\n\t}\n}", "public static class Timestamps implements TimestampsColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build();\n\tpublic static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY};\n\n\tpublic static Uri buildIdUri(Long id) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(id.toString()).build();\n\t}\n\n\tpublic static String getId(Uri uri) {\n\t\treturn uri.getLastPathSegment();\n\t}\n}", "public interface Tables {\n\tString TIMESTAMPS = \"timestamps\";\n\tString FILES = \"files\";\n\tString PRIORITIES = \"priorities\";\n\tString TAGS = \"tags\";\n\tString TODOS = \"todos\";\n\tString ORGDATA = \"orgdata\";\n}", "public class SelectionBuilder {\n private static final String TAG = \"SelectionBuilder\";\n private static final boolean LOGV = false;\n\n private String mTable = null;\n private Map<String, String> mProjectionMap = new HashMap<String, String>();\n private StringBuilder mSelection = new StringBuilder();\n private ArrayList<String> mSelectionArgs = new ArrayList<String>();\n\n /**\n * Reset any internal state, allowing this builder to be recycled.\n */\n public SelectionBuilder reset() {\n mTable = null;\n mSelection.setLength(0);\n mSelectionArgs.clear();\n return this;\n }\n\n /**\n * Append the given selection clause to the internal state. Each clause is\n * surrounded with parenthesis and combined using {@code AND}.\n */\n public SelectionBuilder where(String selection, String... selectionArgs) {\n if (TextUtils.isEmpty(selection)) {\n if (selectionArgs != null && selectionArgs.length > 0) {\n throw new IllegalArgumentException(\n \"Valid selection required when including arguments=\");\n }\n\n // Shortcut when clause is empty\n return this;\n }\n\n if (mSelection.length() > 0) {\n mSelection.append(\" AND \");\n }\n\n mSelection.append(\"(\").append(selection).append(\")\");\n if (selectionArgs != null) {\n for (String arg : selectionArgs) {\n mSelectionArgs.add(arg);\n }\n }\n\n return this;\n }\n\n public SelectionBuilder table(String table) {\n mTable = table;\n return this;\n }\n\n private void assertTable() {\n if (mTable == null) {\n throw new IllegalStateException(\"Table not specified\");\n }\n }\n\n public SelectionBuilder mapToTable(String column, String table) {\n mProjectionMap.put(column, table + \".\" + column);\n return this;\n }\n\n public SelectionBuilder map(String fromColumn, String toClause) {\n mProjectionMap.put(fromColumn, toClause + \" AS \" + fromColumn);\n return this;\n }\n\n /**\n * Return selection string for current internal state.\n *\n * @see #getSelectionArgs()\n */\n public String getSelection() {\n return mSelection.toString();\n }\n\n /**\n * Return selection arguments for current internal state.\n *\n * @see #getSelection()\n */\n public String[] getSelectionArgs() {\n return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);\n }\n\n private void mapColumns(String[] columns) {\n for (int i = 0; i < columns.length; i++) {\n final String target = mProjectionMap.get(columns[i]);\n if (target != null) {\n columns[i] = target;\n }\n }\n }\n\n @Override\n public String toString() {\n return \"SelectionBuilder[table=\" + mTable + \", selection=\" + getSelection()\n + \", selectionArgs=\" + Arrays.toString(getSelectionArgs()) + \"]\";\n }\n\n /**\n * Execute query using the current internal state as {@code WHERE} clause.\n */\n public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {\n return query(db, columns, null, null, orderBy, null);\n }\n\n /**\n * Execute query using the current internal state as {@code WHERE} clause.\n */\n public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,\n String having, String orderBy, String limit) {\n assertTable();\n if (columns != null) mapColumns(columns);\n return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,\n orderBy, limit);\n }\n\n /**\n * Execute update using the current internal state as {@code WHERE} clause.\n */\n public int update(SQLiteDatabase db, ContentValues values) {\n assertTable();\n return db.update(mTable, values, getSelection(), getSelectionArgs());\n }\n\n /**\n * Execute delete using the current internal state as {@code WHERE} clause.\n */\n public int delete(SQLiteDatabase db) {\n assertTable();\n return db.delete(mTable, getSelection(), getSelectionArgs());\n }\n}" ]
import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Search; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgDatabase.Tables; import com.matburt.mobileorg.util.SelectionBuilder;
package com.matburt.mobileorg.orgdata; public class OrgProvider extends ContentProvider { public static final String AUTHORITY = OrgContract.CONTENT_AUTHORITY; private static final int ORGDATA = 100; private static final int ORGDATA_ID = 101; private static final int ORGDATA_PARENT = 102; private static final int ORGDATA_CHILDREN = 103; private static final int FILES = 200; private static final int FILES_ID = 201; private static final int FILES_FILENAME = 202; private static final int TAGS = 400; private static final int TODOS = 500; private static final int PRIORITIES = 600; private static final int SEARCH = 700; private static final int TIMESTAMPS = 800; private static final int TIMESTAMPS_ID = 801; private static final UriMatcher uriMatcher = buildUriMatcher(); private static UriMatcher buildUriMatcher() { final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AUTHORITY, Tables.ORGDATA, ORGDATA); uriMatcher.addURI(AUTHORITY, Tables.ORGDATA + "/*", ORGDATA_ID); uriMatcher.addURI(AUTHORITY, Tables.ORGDATA + "/*/parent", ORGDATA_PARENT); uriMatcher.addURI(AUTHORITY, Tables.ORGDATA + "/*/children", ORGDATA_CHILDREN); uriMatcher.addURI(AUTHORITY, Tables.FILES, FILES); uriMatcher.addURI(AUTHORITY, Tables.FILES + "/*", FILES_ID); uriMatcher.addURI(AUTHORITY, Tables.FILES + "/*/filename", FILES_FILENAME); uriMatcher.addURI(AUTHORITY, Tables.TAGS , TAGS); uriMatcher.addURI(AUTHORITY, Tables.TODOS, TODOS); uriMatcher.addURI(AUTHORITY, Tables.PRIORITIES, PRIORITIES); uriMatcher.addURI(AUTHORITY, "search/*", SEARCH); uriMatcher.addURI(AUTHORITY, Tables.TIMESTAMPS, TIMESTAMPS); uriMatcher.addURI(AUTHORITY, Tables.TIMESTAMPS + "/*", TIMESTAMPS_ID); return uriMatcher; } @Override public boolean onCreate() { return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { final SQLiteDatabase db = OrgDatabase.getInstance().getReadableDatabase(); final SelectionBuilder builder = buildSelectionFromUri(uri); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } @Override public Uri insert(Uri uri, ContentValues contentValues) { final String tableName = getTableNameFromUri(uri); if (contentValues == null) contentValues = new ContentValues(); SQLiteDatabase db = OrgDatabase.getInstance().getWritableDatabase(); long rowId = 0; try { rowId = db.insert(tableName, null, contentValues); } catch (Exception e) { e.printStackTrace(); } if (rowId > 0) { Uri noteUri = ContentUris.withAppendedId(uri, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } else throw new SQLException("Failed to insert row into " + uri); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = OrgDatabase.getInstance().getWritableDatabase(); final SelectionBuilder builder = buildSelectionFromUri(uri); int count = builder.where(selection, selectionArgs).delete(db); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SQLiteDatabase db = OrgDatabase.getInstance().getWritableDatabase(); final SelectionBuilder builder = buildSelectionFromUri(uri); int count = builder.where(selection, selectionArgs).update(db, values); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { // TODO Auto-generated method stub return null; } private SelectionBuilder buildSelectionFromUri(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); switch (uriMatcher.match(uri)) { case ORGDATA: return builder.table(Tables.ORGDATA); case ORGDATA_ID:
return builder.table(Tables.ORGDATA).where(OrgData.ID + "=?", OrgData.getId(uri));
1
SilentChaos512/ScalingHealth
src/main/java/net/silentchaos512/scalinghealth/capability/DifficultyAffectedCapability.java
[ "@Mod(ScalingHealth.MOD_ID)\npublic class ScalingHealth {\n public static final String MOD_ID = \"scalinghealth\";\n public static final String MOD_NAME = \"Scaling Health\";\n public static final String VERSION = \"2.5.3\";\n\n public static final Random random = new Random();\n\n public static final ItemGroup SH = new ItemGroup(MOD_ID) {\n @Override\n public ItemStack createIcon() {\n return new ItemStack(ModItems.HEART_CRYSTAL.asItem());\n }\n };\n\n public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);\n\n public ScalingHealth() {\n Config.init();\n Network.init();\n ModLoot.init();\n\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);\n FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);\n\n MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);\n MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);\n MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);\n }\n\n private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {\n event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId(\"table_loot_mod\")));\n }\n\n private void commonSetup(FMLCommonSetupEvent event) {\n DifficultyAffectedCapability.register();\n DifficultySourceCapability.register();\n PlayerDataCapability.register();\n PetHealthCapability.register();\n DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);\n }\n\n private void serverAboutToStart(FMLServerAboutToStartEvent event) {\n ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());\n }\n\n @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)\n public static class ClientForge {\n static {\n MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);\n MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);\n\n DebugOverlay.init();\n }\n\n @SubscribeEvent\n public static void clientSetup(FMLClientSetupEvent event) {\n KeyManager.registerBindings();\n }\n }\n\n public static String getVersion() {\n return getVersion(false);\n }\n\n public static String getVersion(boolean correctInDev) {\n Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);\n if (o.isPresent()) {\n String str = o.get().getModInfo().getVersion().toString();\n if (correctInDev && \"NONE\".equals(str))\n return VERSION;\n return str;\n }\n return \"0.0.0\";\n }\n\n public static ResourceLocation getId(String path) {\n return new ResourceLocation(MOD_ID, path);\n }\n}", "public final class Config {\n // config/scaling-health\n private static final Path SH_CONFIG_DIR = resolve(FMLPaths.CONFIGDIR.get(), \"scaling-health\");\n\n private static final ConfigSpecWrapper WRAPPER_GAME = ConfigSpecWrapper.create(resolve(SH_CONFIG_DIR, \"game_settings.toml\"));\n private static final ConfigSpecWrapper WRAPPER_CLIENT = ConfigSpecWrapper.create(resolve(SH_CONFIG_DIR, \"client.toml\"));\n private static final ConfigSpecWrapper WRAPPER_COMMON = ConfigSpecWrapper.create(resolve(SH_CONFIG_DIR, \"common.toml\"));\n\n public static final Client CLIENT = new Client(WRAPPER_CLIENT);\n public static final Common COMMON = new Common(WRAPPER_COMMON);\n public static final GameConfig GENERAL = new GameConfig(WRAPPER_GAME);\n\n public static class Client {\n // Debug\n public final EnumValue<Anchor> debugOverlayAnchor;\n public final DoubleValue debugOverlayTextScale;\n\n // Health Icons\n public final EnumValue<HeartIconStyle> heartIconStyle;\n public final ColorList heartColors;\n public final BooleanValue lastHeartOutline;\n public final IntValue lastHeartOutlineColor;\n public final BooleanValue heartColorLooping;\n // Heart Tanks\n public final BooleanValue heartTanks;\n\n // Health Text\n public final EnumValue<HealthTextStyle> healthTextStyle;\n public final DoubleValue healthTextScale;\n public final IntValue healthTextOffsetX;\n public final IntValue healthTextOffsetY;\n public final EnumValue<HealthTextColor> healthTextColorStyle;\n public final IntValue healthTextFullColor;\n public final IntValue healthTextEmptyColor;\n\n // Absorption Icons\n public final EnumValue<AbsorptionIconStyle> absorptionIconStyle;\n public final ColorList absorptionHeartColors;\n\n // Absorption Text\n public final EnumValue<HealthTextStyle> absorptionTextStyle;\n public final IntValue absorptionTextOffsetX;\n public final IntValue absorptionTextOffsetY;\n public final IntValue absorptionTextColor;\n\n // Difficulty\n public final BooleanValue warnWhenSleeping;\n // Difficulty Meter\n public final EnumValue<DifficultyMeterShow> difficultyMeterShow;\n public final DoubleValue difficultyMeterShowTime;\n public final EnumValue<Anchor> difficultyMeterAnchor;\n public final IntValue difficultyMeterOffsetX;\n public final IntValue difficultyMeterOffsetY;\n public final DoubleValue difficultyMeterTextScale;\n\n Client(ConfigSpecWrapper wrapper) {\n debugOverlayAnchor = wrapper\n .builder(\"debug.overlay.anchor\")\n .comment(\"Position of debug overlay\", EnumValue.allValuesComment(Anchor.class))\n .defineEnum(Anchor.TOP_RIGHT);\n debugOverlayTextScale = wrapper\n .builder(\"debug.overlay.textScale\")\n .comment(\"Overlay text size, where 1 is standard-sized text\")\n .defineInRange(0.75, 0.01, Double.MAX_VALUE);\n\n //region Health Hearts\n\n wrapper.comment(\"hearts.health.icons\", \"Settings for heart rows\");\n\n heartIconStyle = wrapper\n .builder(\"hearts.health.icons.style\")\n .comment(\"Heart style\",\n \"REPLACE_ALL: All rows replaced with Scaling Health style hearts\",\n \"REPLACE_AFTER_FIRST_ROW: Leave the first row vanilla style, Scaling Health style for additional rows\",\n \"VANILLA: Do not change heart rendering (use this if you want another mod to handle heart rendering)\")\n .defineEnum(HeartIconStyle.REPLACE_ALL);\n heartColors = new ColorList(wrapper, \"hearts.health.icons.colors\",\n \"The color of each row of hearts. If the player has more rows than colors, it starts over from the beginning.\",\n 0xBF0000, // 0 red\n 0xE66000, // 25 orange-red\n 0xE69900, // 40 orange\n 0xE6D300, // 55 yellow\n 0x99E600, // 80 lime\n 0x4CE600, // 100 green\n 0x00E699, // 160 teal\n 0x00E6E6, // 180 aqua\n 0x0099E6, // 200 sky blue\n 0x0000E6, // 240 blue\n 0x9900E6, // 280 dark purple\n 0xD580FF, // 280 light purple\n 0x8C8C8C, // 0 gray\n 0xE6E6E6 // 0 white\n );\n lastHeartOutline = wrapper\n .builder(\"hearts.health.icons.lastHeartOutline\")\n .comment(\"The player's highest heart will get an outline around it.\")\n .define(true);\n lastHeartOutlineColor = wrapper\n .builder(\"hearts.health.icons.lastHeartOutlineColor\")\n .comment(\"The color of the last heart outline, if enabled (see lastHeartOutline)\")\n .defineColorInt(Color.VALUE_WHITE);\n heartColorLooping = wrapper\n .builder(\"hearts.health.icons.colorLooping\")\n .comment(\"If true, heart colors will 'loop around' to the first color after going through the\",\n \"entire list. Set false to have every row after the last have the same color.\")\n .define(true);\n\n // Tanks\n heartTanks = wrapper\n .builder(\"hearts.health.tanks.enabled\")\n .comment(\"Enable heart tanks, the small icons above your hearts which indicate the number of filled health rows\")\n .define(true);\n\n wrapper.comment(\"hearts.health.text\", \"Settings for the text displayed next to the heart rows\");\n\n healthTextStyle = wrapper\n .builder(\"hearts.health.text.style\")\n .comment(\"Style of health text\", EnumValue.allValuesComment(HealthTextStyle.class))\n .defineEnum(HealthTextStyle.ROWS);\n healthTextScale = wrapper\n .builder(\"hearts.health.text.scale\")\n .comment(\"Health text scale, relative to its normal size (which varies by style)\")\n .defineInRange(1.0, 0.01, Double.MAX_VALUE);\n healthTextOffsetX = wrapper\n .builder(\"hearts.health.text.offsetX\")\n .comment(\"Fine-tune text position\")\n .defineInRange(0, Integer.MIN_VALUE, Integer.MAX_VALUE);\n healthTextOffsetY = wrapper\n .builder(\"hearts.health.text.offsetY\")\n .comment(\"Fine-tune text position\")\n .defineInRange(0, Integer.MIN_VALUE, Integer.MAX_VALUE);\n\n healthTextColorStyle = wrapper\n .builder(\"hearts.health.text.color.style\")\n .comment(\"Health text color style.\",\n \"TRANSITION: Gradually goes from full color to empty color as health is lost\",\n \"PSYCHEDELIC: Taste the rainbow!\",\n \"SOLID: Just stays at full color regardless of health\")\n .defineEnum(HealthTextColor.TRANSITION);\n healthTextFullColor = wrapper\n .builder(\"hearts.health.text.color.full\")\n .comment(\"Color when health is full or style is SOLID\")\n .defineColorInt(0x4CFF4C);\n healthTextEmptyColor = wrapper\n .builder(\"hearts.health.text.color.empty\")\n .comment(\"Color when health is empty and style is TRANSITION\")\n .defineColorInt(0xFF4C4C);\n\n //endregion\n\n //region Absorption Hearts\n\n absorptionIconStyle = wrapper\n .builder(\"hearts.absorption.icons.style\")\n .comment(\"Style of absorption icons\", EnumValue.allValuesComment(AbsorptionIconStyle.class))\n .defineEnum(AbsorptionIconStyle.SHIELD);\n absorptionHeartColors = new ColorList(wrapper, \"hearts.absorption.icons.colors\",\n \"The color of each row of absorption hearts. If the player has more rows than colors, it starts over from the beginning.\",\n 0xBF0000, // 0 red\n 0xE66000, // 25 orange-red\n 0xE69900, // 40 orange\n 0xE6D300, // 55 yellow\n 0x99E600, // 80 lime\n 0x4CE600, // 100 green\n 0x00E699, // 160 teal\n 0x00E6E6, // 180 aqua\n 0x0099E6, // 200 sky blue\n 0x0000E6, // 240 blue\n 0x9900E6, // 280 dark purple\n 0xD580FF, // 280 light purple\n 0x8C8C8C, // 0 gray\n 0xE6E6E6 // 0 white\n );\n\n EnumSet<HealthTextStyle> absorptionTextStyleValidValues = EnumSet.of(\n HealthTextStyle.DISABLED, HealthTextStyle.HEALTH_ONLY, HealthTextStyle.ROWS);\n absorptionTextStyle = wrapper\n .builder(\"hearts.absorption.text.style\")\n .comment(\"Style for absorption text. Because there is no 'max' value, the options are more limited.\",\n EnumValue.validValuesComment(absorptionTextStyleValidValues))\n .defineEnum(HealthTextStyle.DISABLED, absorptionTextStyleValidValues);\n absorptionTextOffsetX = wrapper\n .builder(\"hearts.absorption.text.offsetX\")\n .comment(\"Fine-tune text position\")\n .defineInRange(0, Integer.MIN_VALUE, Integer.MAX_VALUE);\n absorptionTextOffsetY = wrapper\n .builder(\"hearts.absorption.text.offsetY\")\n .comment(\"Fine-tune text position\")\n .defineInRange(0, Integer.MIN_VALUE, Integer.MAX_VALUE);\n absorptionTextColor = wrapper\n .builder(\"hearts.absorption.text.color\")\n .comment(\"The color of the absorption text\")\n .defineColorInt(Color.VALUE_WHITE);\n\n //endregion\n\n //region Difficulty\n\n warnWhenSleeping = wrapper\n .builder(\"difficulty.warnWhenSleeping\")\n .comment(\"Display a warning to players trying to sleep, to remind them their difficulty may change. Sleeping is still allowed.\")\n .define(true);\n\n difficultyMeterShow = wrapper\n .builder(\"difficulty.meter.show\")\n .comment(\"When to show the difficulty meter.\",\n \" SOMETIMES will show the meter for a few seconds every so often.\",\n \"KEYPRESS will make the meter keybinded\",\n \"ALWAYS and NEVER should be obvious enough.\")\n .defineEnum(DifficultyMeterShow.SOMETIMES);\n difficultyMeterShowTime = wrapper\n .builder(\"difficulty.meter.showDuration\")\n .comment(\"Show the difficulty meter for this many seconds (only on SOMETIMES mode)\")\n .defineInRange(8, 0, Double.MAX_VALUE);\n\n difficultyMeterAnchor = wrapper\n .builder(\"difficulty.meter.position.anchor\")\n .comment(\"Position of the difficulty meter.\", EnumValue.allValuesComment(Anchor.class))\n .defineEnum(Anchor.BOTTOM_LEFT);\n difficultyMeterOffsetX = wrapper\n .builder(\"difficulty.meter.position.offsetX\")\n .comment(\"Fine-tune the difficulty meter's position\")\n .defineInRange(5, Integer.MIN_VALUE, Integer.MAX_VALUE);\n difficultyMeterOffsetY = wrapper\n .builder(\"difficulty.meter.position.offsetY\")\n .comment(\"Fine-tune the difficulty meter's position\")\n .defineInRange(-30, Integer.MIN_VALUE, Integer.MAX_VALUE);\n difficultyMeterTextScale = wrapper\n .builder(\"difficulty.meter.text.scale\")\n .comment(\"Scale of text on the difficulty meter\")\n .defineInRange(0.6, 0, Double.MAX_VALUE);\n\n //endregion\n }\n }\n\n public static class Common {\n public final BooleanValue debugMaster;\n public final Supplier<Boolean> debugShowOverlay;\n public final Supplier<Boolean> debugLogEntitySpawns;\n public final Supplier<Boolean> debugLogScaledDamage;\n public final Supplier<Boolean> debugLogEquipmentEntries;\n\n public final BooleanValue crystalsAddHealth;\n public final BooleanValue xpAddHealth;\n public final BooleanValue crystalsRegenHealth;\n public final BooleanValue crystalsAddPetHealth;\n\n public final BooleanValue crystalsAddDamage;\n\n public final BooleanValue hpCrystalsOreGen;\n public final BooleanValue powerCrystalsOreGen;\n\n public final BooleanValue mobDamageIncrease;\n public final BooleanValue mobHpIncrease;\n\n public final BooleanValue playerDamageScaling;\n public final BooleanValue mobDamageScaling;\n\n public final BooleanValue enableDifficulty;\n public final BooleanValue enableBlights;\n\n Common(ConfigSpecWrapper wrapper) {\n wrapper.comment(\"features\",\n \"All SH features can be disabled here. False to disable.\");\n\n crystalsAddHealth = wrapper\n .builder(\"features.crystalsAddHealth\")\n .comment(\"Enable player bonus hp by crystals.\")\n .define(true);\n\n xpAddHealth = wrapper\n .builder(\"features.xpAddHealth\")\n .comment(\"Enable player bonus hp by xp.\")\n .define(true);\n\n crystalsRegenHealth = wrapper\n .builder(\"features.crystalsRegenHealth\")\n .comment(\"Enable player regen hp by crystals.\")\n .define(true);\n\n crystalsAddPetHealth = wrapper\n .builder(\"features.crystalsAddPetHealth\")\n .comment(\"Enable pet add hp by crystals.\")\n .define(true);\n\n crystalsAddDamage = wrapper\n .builder(\"features.crystalsAddDamage\")\n .comment(\"Enable player add damage by crystals.\")\n .define(true);\n\n hpCrystalsOreGen = wrapper\n .builder(\"features.hpCrystalsOreGen\")\n .comment(\"Enable ore gen of health crystals. Still drops as loot.\")\n .define(true);\n\n powerCrystalsOreGen = wrapper\n .builder(\"features.powerCrystalsOreGen\")\n .comment(\"Enable ore gen of power crystals. Still drops as loot.\")\n .define(true);\n\n mobHpIncrease = wrapper\n .builder(\"features.mobHpIncrease\")\n .comment(\"Mobs will gain bonus health with difficulty.\")\n .define(true);\n\n mobDamageIncrease = wrapper\n .builder(\"features.mobDamageIncrease\")\n .comment(\"Mobs will gain bonus damage with difficulty.\")\n .define(true);\n\n playerDamageScaling = wrapper\n .builder(\"features.playerDamageScaling\")\n .comment(\"Enable player damage scaling.\")\n .define(true);\n\n mobDamageScaling = wrapper\n .builder(\"features.mobDamageScaling\")\n .comment(\"Enable mob damage scaling.\")\n .define(true);\n\n enableDifficulty = wrapper\n .builder(\"features.enableDifficulty\")\n .comment(\"Enable difficulty system. If disabled, everything will have 0 difficulty.\")\n .define(true);\n\n enableBlights = wrapper\n .builder(\"features.enableBlights\")\n .comment(\"Enable blights. If disabled, no blights will spawn.\")\n .define(true);\n\n\n\n wrapper.comment(\"debug\",\n \"Debug settings are intended for tuning configs or diagnosing issues.\",\n \"They may decrease performance and should be disabled for normal play.\");\n\n debugMaster = wrapper\n .builder(\"debug.masterSwitch\")\n .comment(\"Must be true for other debug settings to apply\")\n .define(false);\n debugShowOverlay = withMasterCheck(wrapper\n .builder(\"debug.showOverlay\")\n .comment(\"Show some text in-game about player health, difficulty, and maybe other things.\")\n .define(true));\n debugLogEntitySpawns = withMasterCheck(wrapper\n .builder(\"debug.logEntitySpawns\")\n .comment(\"Log details of entity spawns, including effects of difficulty.\",\n \"This creates a lot of log spam, and will likely lag the game.\")\n .define(false));\n debugLogScaledDamage = withMasterCheck(wrapper\n .builder(\"debug.logDamageScaling\")\n .comment(\"Log details of scaled damage, useful for fine-tuning damage scaling.\",\n \"May create a fair amount of log spam, but shouldn't slow down the game too much.\")\n .define(true));\n debugLogEquipmentEntries = withMasterCheck(wrapper\n .builder(\"debug.logEquipmentEntries\")\n .comment(\"Log details of equipment entries.\",\n \"Likely going to lag slightly, mostly depending on the difficulty\")\n .define(true));\n }\n\n Supplier<Boolean> withMasterCheck(BooleanValue option) {\n return () -> debugMaster.get() && option.get();\n }\n }\n\n private Config() {}\n\n public static void init() {\n WRAPPER_CLIENT.validate();\n WRAPPER_COMMON.validate();\n GENERAL.validate();\n }\n\n private static Path resolve(Path parent, String path) {\n // Ensure directories exist\n File directory = parent.toFile();\n if (!directory.exists() && !directory.mkdirs()) {\n // Failed to create directories... should probably let this crash\n ScalingHealth.LOGGER.error(\"Failed to create config directory '{}'. This won't end well...\",\n directory.getAbsolutePath());\n }\n return parent.resolve(path);\n }\n}", "@Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID)\npublic final class DifficultyEvents {\n private static final boolean PRINT_DEBUG_INFO = true;\n\n public static final Marker MARKER = MarkerManager.getMarker(\"Difficulty\");\n\n private DifficultyEvents() {}\n\n @SubscribeEvent\n public static void onAttachEntityCapabilities(AttachCapabilitiesEvent<Entity> event) {\n Entity entity = event.getObject();\n if (DifficultyAffectedCapability.canAttachTo(entity)) {\n event.addCapability(DifficultyAffectedCapability.NAME, new DifficultyAffectedCapability());\n }\n if (EnabledFeatures.difficultyEnabled() && DifficultySourceCapability.canAttachTo(entity)) {\n debug(() -> \"attach difficulty source\");\n event.addCapability(DifficultySourceCapability.NAME, new DifficultySourceCapability());\n }\n if (PlayerDataCapability.canAttachTo(entity)) {\n debug(() -> \"attach player data\");\n event.addCapability(PlayerDataCapability.NAME, new PlayerDataCapability());\n }\n if(EnabledFeatures.petBonusHpEnabled() && PetHealthCapability.canAttachTo(entity)){\n debug(()-> \"attach pet data\");\n event.addCapability(PetHealthCapability.NAME, new PetHealthCapability());\n }\n }\n\n @SubscribeEvent\n public static void onAttachWorldCapabilities(AttachCapabilitiesEvent<World> event) {\n World world = event.getObject();\n if (Config.COMMON.enableDifficulty.get() && DifficultySourceCapability.canAttachTo(world)) {\n DifficultySourceCapability cap = new DifficultySourceCapability();\n event.addCapability(DifficultySourceCapability.NAME, cap);\n DifficultySourceCapability.setOverworldCap(cap);\n }\n }\n\n @SubscribeEvent\n public static void onLivingUpdate(LivingEvent.LivingUpdateEvent event) {\n LivingEntity entity = event.getEntityLiving();\n if (entity.world.isRemote) return;\n\n // Tick mobs, which will calculate difficulty when appropriate and apply changes\n if (entity instanceof MobEntity)\n entity.getCapability(DifficultyAffectedCapability.INSTANCE).ifPresent(data->\n data.tick((MobEntity)entity));\n\n if(entity instanceof TameableEntity) {\n if(!((TameableEntity) entity).isTamed()) return;\n entity.getCapability(PetHealthCapability.INSTANCE).ifPresent(data ->\n data.tick((TameableEntity) entity));\n }\n\n // Tick difficulty source, such as players, except if exempted\n if (entity instanceof PlayerEntity && entity.world.getGameTime() % 20 == 0) {\n entity.getCapability(DifficultySourceCapability.INSTANCE).ifPresent(source->{\n boolean exempt = SHDifficulty.isPlayerExempt((PlayerEntity) entity);\n source.setExempt(exempt);\n if(exempt) return;\n float change = (float) SHDifficulty.changePerSecond();\n source.setDifficulty(source.getDifficulty() + change);\n });\n }\n }\n\n @SubscribeEvent\n public static void onMobDeath(LivingDeathEvent event) {\n if(!(event.getEntityLiving() instanceof MobEntity)) return;\n MobEntity entity = (MobEntity) event.getEntityLiving();\n if (event.getSource() == null || event.getEntity().world.isRemote)\n return;\n\n Entity entitySource = event.getSource().getTrueSource();\n boolean isTamedAnimal = entitySource instanceof TameableEntity && ((TameableEntity) entitySource).isTamed();\n if (entitySource instanceof PlayerEntity ) {\n SHDifficulty.setSourceDifficulty((PlayerEntity) entitySource, SHDifficulty.applyKillMutator(entity, (PlayerEntity) entitySource));\n return;\n }\n if(isTamedAnimal){\n TameableEntity pet = (TameableEntity) entitySource;\n if(pet.getOwner() instanceof PlayerEntity)\n SHDifficulty.setSourceDifficulty(((PlayerEntity) pet.getOwner()), SHDifficulty.applyKillMutator(entity, (PlayerEntity) pet.getOwner()));\n }\n }\n\n @SubscribeEvent\n public static void onWorldTick(TickEvent.WorldTickEvent event) {\n if(event.phase == TickEvent.Phase.START) return;\n World world = event.world;\n if (world.isRemote) return;\n\n // Tick world difficulty source\n if (world.getGameTime() % 20 == 0) {\n world.getCapability(DifficultySourceCapability.INSTANCE).ifPresent(source -> {\n float change = (float) SHDifficulty.changePerSecond();\n source.setDifficulty(source.getDifficulty() + change);\n });\n }\n }\n\n @SubscribeEvent\n public static void onPlayerTick(TickEvent.PlayerTickEvent event) {\n if(event.phase == TickEvent.Phase.START) return;\n PlayerEntity player = event.player;\n if (player.world.isRemote) return;\n player.getCapability(PlayerDataCapability.INSTANCE).ifPresent(data -> data.tick(player));\n }\n\n @SubscribeEvent\n public static void onPlayerClone(PlayerEvent.Clone event) {\n // Player is cloned. Copy capabilities before applying health/difficulty changes if needed.\n PlayerEntity original = event.getOriginal();\n PlayerEntity clone = event.getPlayer();\n\n IPlayerData ogData = SHPlayers.getPlayerData(original);\n ogData.setXpHearts(original, SHPlayers.hpFromCurrentXp(clone.experienceLevel));\n\n debug(() -> \"onPlayerClone\");\n copyCapability(PlayerDataCapability.INSTANCE, original, clone);\n copyCapability(DifficultySourceCapability.INSTANCE, original, clone);\n\n // If not dead, player is returning from the End\n if (!event.isWasDeath()) return;\n\n // Apply death mutators\n IPlayerData data = SHPlayers.getPlayerData(clone);\n data.setXpHearts(clone, SHPlayers.hpFromCurrentXp(clone.experienceLevel));\n int newCrystals = SHPlayers.getCrystalCountFromHealth(SHPlayers.getHealthAfterDeath(original));\n notifyOfChanges(clone, \"heart crystal(s)\", data.getHeartByCrystals(), newCrystals);\n data.setHeartByCrystals(clone, newCrystals);\n\n IDifficultySource source = SHDifficulty.source(clone);\n float newDifficulty = (float) SHDifficulty.getDifficultyAfterDeath(clone);\n notifyOfChanges(clone, \"difficulty\", source.getDifficulty(), newDifficulty);\n source.setDifficulty(newDifficulty);\n }\n\n @SubscribeEvent\n public static void onPlayerJoinServer(PlayerEvent.PlayerLoggedInEvent event) {\n PlayerEntity player = event.getPlayer();\n player.getCapability(PlayerDataCapability.INSTANCE).ifPresent(data -> {\n ScalingHealth.LOGGER.info(\"Updating stats for {}\", player.getScoreboardName());\n data.updateStats(player);\n });\n }\n\n private static void notifyOfChanges(PlayerEntity player, String valueName, float oldValue, float newValue) {\n float diff = newValue - oldValue;\n String line = String.format(\"%s %.2f %s\", diff > 0 ? \"gained\" : \"lost\", diff, valueName);\n if(diff != 0)\n player.sendMessage(new StringTextComponent(line));\n ScalingHealth.LOGGER.info(\"Player {}\", line);\n }\n\n private static <T> void copyCapability(Capability<T> capability, ICapabilityProvider original, ICapabilityProvider clone) {\n original.getCapability(capability).ifPresent(dataOriginal ->\n clone.getCapability(capability).ifPresent(dataClone -> {\n INBT nbt = capability.getStorage().writeNBT(capability, dataOriginal, null);\n capability.getStorage().readNBT(capability, dataClone, null, nbt);\n }));\n }\n\n private static void debug(Supplier<?> msg) {\n if (PRINT_DEBUG_INFO && ScalingHealth.LOGGER.isDebugEnabled())\n ScalingHealth.LOGGER.debug(MARKER, msg.get());\n }\n}", "public final class MobDifficultyHandler {\n private MobDifficultyHandler() {}\n\n public static void process(MobEntity entity, IDifficultyAffected data) {\n // Already dead?\n if (!entity.isAlive()) return;\n\n // Make blight?\n // getDiff is used not affectiveDiff since the blight modifier has no play (deciding to make it blight or not)\n boolean makeBlight = shouldBecomeBlight(entity, data.getDifficulty());\n setEntityProperties(entity, data, makeBlight);\n }\n\n public static boolean shouldBecomeBlight(MobEntity entity, float difficulty) {\n if (!SHMobs.canBecomeBlight(entity)) return false;\n\n double chance = getBlightChance(difficulty);\n if(chance == 1) return true;\n\n return MathUtils.tryPercentage(ScalingHealth.random, chance);\n }\n\n private static double getBlightChance(float difficulty) {\n return SHMobs.blightChance() * difficulty / SHDifficulty.maxValue();\n }\n\n public static void setEntityProperties(MobEntity entity, IDifficultyAffected data, boolean makeBlight) {\n if (!entity.isAlive()) return;\n\n boolean isHostile = entity instanceof IMob;\n\n if (makeBlight) {\n data.setIsBlight(true);\n if(EntityGroup.from(entity) == EntityGroup.BOSS){\n StringTextComponent name = (StringTextComponent) new StringTextComponent(\"Blight \" + entity.getName().getString()).setStyle(new Style().setColor(TextFormatting.DARK_PURPLE));\n entity.setCustomName(name);\n }\n }\n\n //Get difficulty after making blight or not. This will determine if a blight's diff is multiplied\n final float difficulty = data.affectiveDifficulty(); if(difficulty <= 0) return;\n\n // Random potion effect\n SHMobs.getMobPotionConfig().tryApply(entity, difficulty);\n\n if(EnabledFeatures.mobHpIncreaseEnabled()){\n\n double healthBoost = difficulty;\n IAttributeInstance attributeMaxHealth = entity.getAttribute(SharedMonsterAttributes.MAX_HEALTH);\n double baseMaxHealth = attributeMaxHealth.getBaseValue();\n double healthMultiplier = isHostile\n ? SHMobs.healthHostileMultiplier()\n : SHMobs.healthPassiveMultiplier();\n\n healthBoost *= healthMultiplier;\n\n double diffIncrease = 2 * healthMultiplier * difficulty * ScalingHealth.random.nextFloat();\n healthBoost += diffIncrease;\n\n if(ScalingHealthCommonEvents.spawnerSpawns.contains(entity.getUniqueID())){\n healthBoost *= SHMobs.spawnerHealth();\n ScalingHealthCommonEvents.spawnerSpawns.remove(entity.getUniqueID());\n }\n\n // Apply extra health and damage.\n MobHealthMode mode = EntityGroup.from(entity).getHealthMode();\n double healthModAmount = mode.getModifierValue(healthBoost, baseMaxHealth);\n ModifierHandler.setMaxHealth(entity, healthModAmount, mode.getOperator());\n }\n\n // Increase attack damage.\n if(EnabledFeatures.mobDamageIncreaseEnabled()){\n double damageBoost;\n\n float diffIncrease = difficulty * ScalingHealth.random.nextFloat();\n damageBoost = diffIncrease * SHMobs.damageBoostScale();\n // Clamp the value so it doesn't go over the maximum config.\n double max = SHMobs.maxDamageBoost();\n if (max > 0f) {\n damageBoost = MathHelper.clamp(damageBoost, 0, max);\n }\n\n ModifierHandler.addAttackDamage(entity, damageBoost, AttributeModifier.Operation.ADDITION);\n }\n }\n}", "public final class SHDifficulty {\n private SHDifficulty() {throw new IllegalAccessError(\"Utility class\");}\n\n public static IDifficultyAffected affected(ICapabilityProvider entity) {\n return entity.getCapability(DifficultyAffectedCapability.INSTANCE)\n .orElseGet(DifficultyAffectedCapability::new);\n }\n\n public static IDifficultySource source(ICapabilityProvider source) {\n return source.getCapability(DifficultySourceCapability.INSTANCE)\n .orElseGet(DifficultySourceCapability::new);\n }\n\n public static void setSourceDifficulty(PlayerEntity player, double difficulty){\n IDifficultySource source = SHDifficulty.source(player);\n if (!MathUtils.doublesEqual(source.getDifficulty(), difficulty)) {\n // Update difficulty after sleeping\n source.setDifficulty((float) difficulty); //player diff\n SHDifficulty.source(player.world).setDifficulty((float) difficulty); //world diff\n }\n }\n\n @SuppressWarnings(\"TypeMayBeWeakened\")\n public static double getDifficultyOf(Entity entity) {\n if (entity instanceof PlayerEntity)\n return source(entity).getDifficulty();\n return affected(entity).affectiveDifficulty();\n }\n\n public static Collection<Tuple<BlockPos, IDifficultySource>> allPlayerSources(IWorld world, Vec3i center, long radius) {\n Collection<Tuple<BlockPos, IDifficultySource>> list = new ArrayList<>();\n\n // Get players\n playersInRange(world, center, radius).forEach(player -> list.add(new Tuple<>(player.getPosition(), SHDifficulty.source(player))));\n return list;\n }\n\n public static Stream<? extends PlayerEntity> playersInRange(IWorld world, Vec3i center, long radius) {\n return world.getPlayers().stream().filter(p -> radius <= 0 || MCMathUtils.distanceSq(p, center) < searchRadiusSquared());\n }\n\n public static int searchRadius() {\n final int radius = Config.GENERAL.difficulty.searchRadius.get();\n return radius <= 0 ? Integer.MAX_VALUE : radius;\n }\n\n public static long searchRadiusSquared() {\n final long radius = searchRadius();\n return radius * radius;\n }\n\n public static double areaDifficulty(World world, BlockPos pos) {\n return areaDifficulty(world, pos, true);\n }\n\n public static double areaDifficulty(World world, BlockPos pos, boolean groupBonus) {\n return areaMode().getAreaDifficulty(world, pos, groupBonus);\n }\n\n public static double locationMultiplier(IWorldReader world, BlockPos pos) {\n return Config.GENERAL.difficulty.getLocationMultiplier(world, pos);\n }\n\n public static double lunarMultiplier(World world) {\n GameConfig config = Config.GENERAL;\n if (!config.difficulty.lunarCyclesEnabled.get()) return 1.0;\n List<? extends Double> values = config.difficulty.lunarCycleMultipliers.get();\n if (values.isEmpty()) return 1.0;\n int phase = world.getDimension().getMoonPhase(world.getGameTime());\n return values.get(MathHelper.clamp(phase, 0, values.size() - 1));\n }\n\n public static double withGroupBonus(World world, BlockPos pos, double difficulty) {\n return difficulty * EvalVars.apply(world, pos, null, Config.GENERAL.difficulty.groupAreaBonus.get());\n }\n\n public static AreaDifficultyMode areaMode() {\n return Config.GENERAL.difficulty.areaMode.get();\n }\n\n public static double clamp(double difficulty) {\n return MathHelper.clamp(difficulty, minValue(), maxValue());\n }\n\n public static boolean ignoreYAxis(){\n return Config.GENERAL.difficulty.ignoreYAxis.get();\n }\n\n public static double distanceFactor() {\n return Config.GENERAL.difficulty.distanceFactor.get();\n }\n\n public static double minValue() {\n return Config.GENERAL.difficulty.minValue.get();\n }\n\n public static double maxValue() {\n return Config.GENERAL.difficulty.maxValue.get();\n }\n\n public static double changePerSecond() {\n return Config.GENERAL.difficulty.changePerSecond.get();\n }\n\n public static double idleModifier() {\n return Config.GENERAL.difficulty.idleMultiplier.get();\n }\n\n public static boolean afkMessage(){\n return Config.GENERAL.difficulty.afkMessage.get();\n }\n\n public static double timeBeforeAfk() {\n return Config.GENERAL.difficulty.timeBeforeAfk.get();\n }\n\n public static boolean isPlayerExempt(PlayerEntity player){\n return Config.GENERAL.difficulty.isPlayerExempt(player);\n }\n\n public static double getDifficultyAfterDeath(PlayerEntity player) {\n return EvalVars.apply(player, Config.GENERAL.difficulty.onPlayerDeath.get());\n }\n\n public static double applyKillMutator(MobEntity entity, PlayerEntity player){\n return EvalVars.apply(player, Config.GENERAL.difficulty.getKillMutator(entity));\n }\n\n public static double diffOnPlayerSleep(PlayerEntity entity){\n return EvalVars.apply(entity, Config.GENERAL.difficulty.onPlayerSleep.get());\n }\n\n public static String sleepWarningMessage(){\n return Config.GENERAL.difficulty.sleepWarningMessage.get();\n }\n\n public static List<? extends String> getDamageBlacklistedMods(){\n return Config.GENERAL.damageScaling.modBlacklist.get();\n }\n}", "public final class SHMobs {\n private SHMobs() { throw new IllegalAccessError(\"Utility class\"); }\n\n public static boolean allowsDifficultyChanges(MobEntity entity) {\n return !EntityTags.DIFFICULTY_EXEMPT.contains(entity.getType());\n }\n\n public static double blightChance() {\n return Config.GENERAL.mobs.blightChance.get();\n }\n\n public static boolean canBecomeBlight(MobEntity entity) {\n return EnabledFeatures.blightsEnabled() && !EntityTags.BLIGHT_EXEMPT.contains(entity.getType());\n }\n\n public static boolean isBlight(MobEntity entity) {\n return SHDifficulty.affected(entity).isBlight();\n }\n\n public static double getBlightDifficultyMultiplier() {\n return Config.GENERAL.mobs.blightDiffModifier.get();\n }\n\n public static boolean notifyOnDeath(){\n return Config.GENERAL.mobs.notifyOnBlightDeath.get();\n }\n\n public static double healthPassiveMultiplier(){\n return Config.GENERAL.mobs.passiveMultiplier.get();\n }\n\n public static double healthHostileMultiplier(){\n return Config.GENERAL.mobs.hostileMultiplier.get();\n }\n\n public static MobPotionConfig getMobPotionConfig(){\n return Config.GENERAL.mobs.randomPotions;\n }\n\n public static double passivePotionChance(){\n return Config.GENERAL.mobs.peacefulPotionChance.get();\n }\n\n public static double hostilePotionChance(){\n return Config.GENERAL.mobs.hostilePotionChance.get();\n }\n\n public static MobHealthMode healthMode(){\n return Config.GENERAL.mobs.healthMode.get();\n }\n\n public static double spawnerHealth(){\n return Config.GENERAL.mobs.spawnerModifier.get();\n }\n\n public static double xpBoost(){\n return Config.GENERAL.mobs.xpBoost.get();\n }\n\n public static double xpBlightBoost(){\n return Config.GENERAL.mobs.xpBlightBoost.get();\n }\n\n public static double damageBoostScale() {\n return Config.GENERAL.mobs.damageBoostScale.get();\n }\n\n public static double maxDamageBoost() {\n return Config.GENERAL.mobs.maxDamageBoost.get();\n }\n}" ]
import net.minecraft.entity.MobEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.capabilities.*; import net.minecraftforge.common.util.LazyOptional; import net.silentchaos512.scalinghealth.ScalingHealth; import net.silentchaos512.scalinghealth.config.Config; import net.silentchaos512.scalinghealth.event.DifficultyEvents; import net.silentchaos512.scalinghealth.utils.MobDifficultyHandler; import net.silentchaos512.scalinghealth.utils.SHDifficulty; import net.silentchaos512.scalinghealth.utils.SHMobs; import javax.annotation.Nonnull; import javax.annotation.Nullable;
package net.silentchaos512.scalinghealth.capability; public class DifficultyAffectedCapability implements IDifficultyAffected, ICapabilitySerializable<CompoundNBT> { @CapabilityInject(IDifficultyAffected.class) public static Capability<IDifficultyAffected> INSTANCE = null;
public static ResourceLocation NAME = ScalingHealth.getId("difficulty_affected");
0
Lordmau5/FFS
src/main/java/com/lordmau5/ffs/client/gui/GuiValve.java
[ "@Mod(modid = FancyFluidStorage.MODID, name = \"Fancy Fluid Storage\", dependencies = \"after:waila\")\npublic class FancyFluidStorage {\n public static final String MODID = \"ffs\";\n public static final TankManager tankManager = new TankManager();\n public static Block blockFluidValve;\n public static Block blockTankComputer;\n public static Item itemTitEgg;\n public static Item itemTit;\n @Mod.Instance(MODID)\n public static FancyFluidStorage INSTANCE;\n\n @SidedProxy(clientSide = \"com.lordmau5.ffs.proxy.ClientProxy\", serverSide = \"com.lordmau5.ffs.proxy.CommonProxy\")\n private static IProxy PROXY;\n\n @SuppressWarnings(\"deprecation\")\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n Compatibility.INSTANCE.init();\n\n ModBlocksAndItems.preInit(event);\n\n NetworkRegistry.INSTANCE.registerGuiHandler(FancyFluidStorage.INSTANCE, new GuiHandler());\n NetworkHandler.registerChannels(event.getSide());\n\n TOPCompatibility.register();\n\n PROXY.preInit();\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n ModRecipes.init();\n\n PROXY.init(event);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n GenericUtil.init();\n\n ForgeChunkManager.setForcedChunkLoadingCallback(INSTANCE, (tickets, world) -> {\n if ( tickets != null && tickets.size() > 0 )\n GenericUtil.initChunkLoadTicket(world, tickets.get(0));\n });\n }\n\n @SubscribeEvent\n public void onWorldUnload(WorldEvent.Unload event) {\n if ( event.getWorld().isRemote ) {\n FancyFluidStorage.tankManager.removeAllForDimension(event.getWorld().provider.getDimension());\n }\n }\n}", "public abstract class FFSPacket {\n public abstract void encode(ByteBuf buffer);\n\n public abstract void decode(ByteBuf buffer);\n\n public static abstract class Client {\n public static class OnTankBuild extends FFSPacket {\n private int dimensionId;\n private BlockPos valvePos;\n private TreeMap<Integer, List<LayerBlockPos>> airBlocks;\n private TreeMap<Integer, List<LayerBlockPos>> frameBlocks;\n\n public OnTankBuild() {\n }\n\n public OnTankBuild(AbstractTankValve valve) {\n this.dimensionId = valve.getWorld().provider.getDimension();\n this.valvePos = valve.getPos();\n this.airBlocks = valve.getAirBlocks();\n this.frameBlocks = valve.getFrameBlocks();\n }\n\n @Override\n public void encode(ByteBuf buffer) {\n buffer.writeInt(this.dimensionId);\n buffer.writeLong(this.valvePos.toLong());\n\n buffer.writeInt(this.airBlocks.size());\n for (int layer : this.airBlocks.keySet()) {\n buffer.writeInt(layer);\n buffer.writeInt(this.airBlocks.get(layer).size());\n for (LayerBlockPos pos : this.airBlocks.get(layer)) {\n buffer.writeLong(pos.toLong());\n buffer.writeInt(pos.getLayer());\n }\n }\n\n buffer.writeInt(this.frameBlocks.size());\n for (int layer : this.frameBlocks.keySet()) {\n buffer.writeInt(layer);\n buffer.writeInt(this.frameBlocks.get(layer).size());\n for (LayerBlockPos pos : this.frameBlocks.get(layer)) {\n buffer.writeLong(pos.toLong());\n buffer.writeInt(pos.getLayer());\n }\n }\n }\n\n @Override\n public void decode(ByteBuf buffer) {\n this.dimensionId = buffer.readInt();\n this.valvePos = BlockPos.fromLong(buffer.readLong());\n\n this.airBlocks = new TreeMap<>();\n int layerSize = buffer.readInt();\n for (int i = 0; i < layerSize; i++) {\n int layer = buffer.readInt();\n int airBlockSize = buffer.readInt();\n List<LayerBlockPos> layerBlocks = new ArrayList<>();\n for (int j = 0; j < airBlockSize; j++) {\n layerBlocks.add(new LayerBlockPos(BlockPos.fromLong(buffer.readLong()), buffer.readInt()));\n }\n this.airBlocks.put(layer, layerBlocks);\n }\n\n this.frameBlocks = new TreeMap<>();\n layerSize = buffer.readInt();\n for (int i = 0; i < layerSize; i++) {\n int layer = buffer.readInt();\n int frameBlockSize = buffer.readInt();\n List<LayerBlockPos> layerBlocks = new ArrayList<>();\n for (int j = 0; j < frameBlockSize; j++) {\n layerBlocks.add(new LayerBlockPos(BlockPos.fromLong(buffer.readLong()), buffer.readInt()));\n }\n this.frameBlocks.put(layer, layerBlocks);\n }\n }\n\n public int getDimension() {\n return dimensionId;\n }\n\n public BlockPos getValvePos() {\n return valvePos;\n }\n\n public TreeMap<Integer, List<LayerBlockPos>> getAirBlocks() {\n return airBlocks;\n }\n\n public TreeMap<Integer, List<LayerBlockPos>> getFrameBlocks() {\n return frameBlocks;\n }\n }\n\n public static class OnTankBreak extends FFSPacket {\n private int dimensionId;\n private BlockPos valvePos;\n\n public OnTankBreak() {\n }\n\n public OnTankBreak(AbstractTankValve valve) {\n this.dimensionId = valve.getWorld().provider.getDimension();\n this.valvePos = valve.getPos();\n }\n\n @Override\n public void encode(ByteBuf buffer) {\n buffer.writeInt(this.dimensionId);\n buffer.writeLong(this.valvePos.toLong());\n }\n\n @Override\n public void decode(ByteBuf buffer) {\n this.dimensionId = buffer.readInt();\n this.valvePos = BlockPos.fromLong(buffer.readLong());\n }\n\n public int getDimension() {\n return dimensionId;\n }\n\n public BlockPos getValvePos() {\n return valvePos;\n }\n }\n }\n\n public static class Server {\n public static class UpdateTileName extends FFSPacket {\n private BlockPos pos;\n private String name;\n\n public UpdateTileName() {\n }\n\n public UpdateTileName(AbstractTankTile tankTile, String name) {\n this.pos = tankTile.getPos();\n this.name = name;\n }\n\n @Override\n public void encode(ByteBuf buffer) {\n buffer.writeLong(this.pos.toLong());\n ByteBufUtils.writeUTF8String(buffer, this.name);\n }\n\n @Override\n public void decode(ByteBuf buffer) {\n this.pos = BlockPos.fromLong(buffer.readLong());\n this.name = ByteBufUtils.readUTF8String(buffer);\n }\n\n public BlockPos getPos() {\n return pos;\n }\n\n public String getName() {\n return name;\n }\n }\n\n public static class UpdateFluidLock extends FFSPacket {\n private BlockPos pos;\n private boolean fluidLock;\n\n public UpdateFluidLock() {\n }\n\n public UpdateFluidLock(AbstractTankValve valve) {\n this.pos = valve.getPos();\n this.fluidLock = valve.getTankConfig().isFluidLocked();\n }\n\n @Override\n public void encode(ByteBuf buffer) {\n buffer.writeLong(this.pos.toLong());\n buffer.writeBoolean(this.fluidLock);\n }\n\n @Override\n public void decode(ByteBuf buffer) {\n this.pos = BlockPos.fromLong(buffer.readLong());\n this.fluidLock = buffer.readBoolean();\n }\n\n public BlockPos getPos() {\n return pos;\n }\n\n public boolean isFluidLock() {\n return fluidLock;\n }\n }\n\n public static class OnTankRequest extends FFSPacket {\n private BlockPos pos;\n\n public OnTankRequest() {\n }\n\n public OnTankRequest(AbstractTankValve valve) {\n this.pos = valve.getPos();\n }\n\n @Override\n public void encode(ByteBuf buffer) {\n buffer.writeLong(this.pos.toLong());\n }\n\n @Override\n public void decode(ByteBuf buffer) {\n this.pos = BlockPos.fromLong(buffer.readLong());\n }\n\n public BlockPos getPos() {\n return pos;\n }\n }\n }\n}", "public class NetworkHandler {\n private static EnumMap<Side, FMLEmbeddedChannel> channels;\n\n public static void registerChannels(Side side) {\n channels = NetworkRegistry.INSTANCE.newChannel(\"ffs\", new PacketCodec());\n\n ChannelPipeline pipeline = channels.get(Side.SERVER).pipeline();\n String targetName = channels.get(Side.SERVER).findChannelHandlerNameForType(PacketCodec.class);\n\n pipeline.addAfter(targetName, \"UpdateTileName_Server\", new UpdateTileName_Server());\n pipeline.addAfter(targetName, \"UpdateFluidLock_Server\", new UpdateFluidLock_Server());\n\n pipeline.addAfter(targetName, \"OnTankRequest\", new OnTankRequest());\n\n if ( side.isClient() ) {\n registerClientHandlers();\n }\n }\n\n @SideOnly(Side.CLIENT)\n private static void registerClientHandlers() {\n ChannelPipeline pipeline = channels.get(Side.CLIENT).pipeline();\n String targetName = channels.get(Side.CLIENT).findChannelHandlerNameForType(PacketCodec.class);\n\n pipeline.addAfter(targetName, \"OnTankBuild\", new OnTankBuild());\n pipeline.addAfter(targetName, \"OnTankBreak\", new OnTankBreak());\n }\n\n public static Packet getProxyPacket(FFSPacket packet) {\n return channels.get(FMLCommonHandler.instance().getEffectiveSide()).generatePacketFrom(packet);\n }\n\n public static void sendPacketToPlayer(FFSPacket packet, EntityPlayer player) {\n FMLEmbeddedChannel channel = channels.get(Side.SERVER);\n channel.attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);\n channel.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);\n channel.writeOutbound(packet);\n }\n\n public static void sendPacketToAllPlayers(FFSPacket packet) {\n FMLEmbeddedChannel channel = channels.get(Side.SERVER);\n channel.attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);\n channel.writeOutbound(packet);\n }\n\n public static void sendPacketToServer(FFSPacket packet) {\n FMLEmbeddedChannel channel = channels.get(Side.CLIENT);\n channel.attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);\n channel.writeOutbound(packet);\n }\n\n public static EntityPlayerMP getPlayer(ChannelHandlerContext ctx) {\n return ((NetHandlerPlayServer) ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()).player;\n }\n}", "public abstract class AbstractTankTile extends TileEntity implements ITickable {\n\n /**\n * Necessary stuff for the interfaces.\n * Current interface list:\n * INameableTile, IFacingTile\n */\n protected EnumFacing tile_facing = null;\n String tile_name = \"\";\n\n private int needsUpdate = 0;\n private BlockPos masterValvePos;\n\n public void setNeedsUpdate() {\n if ( this.needsUpdate == 0 ) {\n this.needsUpdate = 20;\n }\n }\n\n @Override\n public void onLoad() {\n super.onLoad();\n\n setNeedsUpdate();\n }\n\n public boolean isValid() {\n return getMasterValve() != null && getMasterValve().isValid();\n }\n\n @Override\n public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) {\n return oldState.getBlock() != newState.getBlock();\n }\n\n void setValvePos(BlockPos masterValvePos) {\n this.masterValvePos = masterValvePos;\n }\n\n public AbstractTankValve getMasterValve() {\n if ( getWorld() != null && this.masterValvePos != null ) {\n TileEntity tile = getWorld().getTileEntity(this.masterValvePos);\n return tile instanceof AbstractTankValve ? (AbstractTankValve) tile : null;\n }\n\n return null;\n }\n\n @Override\n public void readFromNBT(NBTTagCompound tag) {\n super.readFromNBT(tag);\n\n setValvePos(tag.hasKey(\"valvePos\") ? BlockPos.fromLong(tag.getLong(\"valvePos\")) : null);\n }\n\n @Override\n public NBTTagCompound writeToNBT(NBTTagCompound tag) {\n if ( getMasterValve() != null ) {\n tag.setLong(\"valvePos\", getMasterValve().getPos().toLong());\n }\n\n super.writeToNBT(tag);\n return tag;\n }\n\n @Override\n public NBTTagCompound getUpdateTag() {\n return writeToNBT(new NBTTagCompound());\n }\n\n @Override\n public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {\n super.onDataPacket(net, pkt);\n\n boolean oldIsValid = isValid();\n\n readFromNBT(pkt.getNbtCompound());\n\n if ( getWorld() != null && getWorld().isRemote && oldIsValid != isValid() ) {\n markForUpdateNow();\n }\n }\n\n @Override\n public SPacketUpdateTileEntity getUpdatePacket() {\n NBTTagCompound tag = new NBTTagCompound();\n writeToNBT(tag);\n return new SPacketUpdateTileEntity(getPos(), 0, tag);\n }\n\n public void markForUpdate() {\n if ( getWorld() == null ) {\n setNeedsUpdate();\n return;\n }\n\n if ( --this.needsUpdate == 0 ) {\n IBlockState state = getWorld().getBlockState(getPos());\n getWorld().notifyBlockUpdate(getPos(), state, state, 3);\n markDirty();\n }\n }\n\n public void markForUpdateNow() {\n this.needsUpdate = 1;\n markForUpdate();\n }\n\n public void markForUpdateNow(int when) {\n this.needsUpdate = Math.min(when, 20);\n markForUpdate();\n }\n\n @Override\n public void update() {\n if ( this.needsUpdate > 0 ) {\n markForUpdate();\n }\n }\n\n @Override\n public int hashCode() {\n return getPos().hashCode();\n }\n\n}", "public abstract class AbstractTankValve extends AbstractTankTile implements IFacingTile, INameableTile {\n\n public final WeakHashMap<Integer, TreeMap<Integer, List<LayerBlockPos>>> maps;\n private final List<AbstractTankTile> tankTiles;\n private int initialWaitTick = 20;\n private TankConfig tankConfig;\n private boolean isValid;\n private boolean isMaster;\n private boolean initiated;\n\n // TANK LOGIC\n private int lastComparatorOut = 0;\n // ---------------\n private EntityPlayer buildPlayer;\n\n public AbstractTankValve() {\n tankTiles = new ArrayList<>();\n\n maps = new WeakHashMap<>();\n maps.put(0, new TreeMap<>());\n maps.put(1, new TreeMap<>());\n\n setValid(false);\n setValvePos(null);\n }\n\n @Override\n public void validate() {\n super.validate();\n initiated = true;\n initialWaitTick = 20;\n }\n\n @Override\n public void invalidate() {\n super.invalidate();\n\n breakTank();\n }\n\n @Override\n public void onChunkUnload() {\n super.onChunkUnload();\n\n breakTank();\n }\n\n @Override\n public void update() {\n super.update();\n\n if ( getWorld().isRemote ) {\n return;\n }\n\n if ( initiated ) {\n if ( isMaster() ) {\n//\t\t\t\tif(bottomDiagFrame != null && topDiagFrame != null) { // Potential fix for huge-ass tanks not loading properly on master-valve chunk load.\n//\t\t\t\t\tChunk chunkBottom = getWorld().getChunkFromBlockCoords(bottomDiagFrame);\n//\t\t\t\t\tChunk chunkTop = getWorld().getChunkFromBlockCoords(topDiagFrame);\n//\n//\t\t\t\t\tBlockPos pos_chunkBottom = new BlockPos(chunkBottom.xPosition, 0, chunkBottom.zPosition);\n//\t\t\t\t\tBlockPos pos_chunkTop = new BlockPos(chunkTop.xPosition, 0, chunkTop.zPosition);\n//\n//\t\t\t\t\tBlockPos diff = pos_chunkTop.subtract(pos_chunkBottom);\n//\t\t\t\t\tfor(int x = 0; x <= diff.getX(); x++) {\n//\t\t\t\t\t\tfor(int z = 0; z <= diff.getZ(); z++) {\n//\t\t\t\t\t\t\tForgeChunkManager.forceChunk(GenericUtil.getChunkLoadTicket(getWorld()), new ChunkPos(pos_chunkTop.getX() + x, pos_chunkTop.getZ() + z));\n//\t\t\t\t\t\t}\n//\t\t\t\t\t}\n//\n//\t\t\t\t\tupdateBlockAndNeighbors();\n//\t\t\t\t}\n if ( initialWaitTick-- <= 0 ) {\n initiated = false;\n buildTank(getTileFacing());\n return;\n }\n }\n }\n\n if ( !isValid() )\n return;\n\n if ( !isMaster() && getMasterValve() == null ) {\n setValid(false);\n updateBlockAndNeighbors();\n }\n }\n\n public TreeMap<Integer, List<LayerBlockPos>> getFrameBlocks() {\n return maps.get(0);\n }\n\n public TreeMap<Integer, List<LayerBlockPos>> getAirBlocks() {\n return maps.get(1);\n }\n\n public TankConfig getTankConfig() {\n if ( !isMaster() && getMasterValve() != null && getMasterValve() != this ) {\n return getMasterValve().getTankConfig();\n }\n\n if ( this.tankConfig == null ) {\n this.tankConfig = new TankConfig(this);\n }\n\n return this.tankConfig;\n }\n\n private void setTankConfig(TankConfig tankConfig) {\n this.tankConfig = tankConfig;\n }\n\n public void toggleFluidLock(boolean state) {\n if ( !state ) {\n getTankConfig().unlockFluid();\n } else {\n if ( getTankConfig().getFluidStack() == null ) {\n return;\n }\n\n getTankConfig().lockFluid(getTankConfig().getFluidStack());\n }\n getMasterValve().setNeedsUpdate();\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> List<T> getTankTiles(Class<T> type) {\n List<T> tiles = tankTiles.stream().filter(p -> type.isAssignableFrom(p.getClass())).map(p -> (T) p).collect(Collectors.toList());\n if ( this.getClass().isAssignableFrom(type) ) {\n tiles.add((T) this);\n }\n\n return tiles;\n }\n\n public List<AbstractTankValve> getAllValves(boolean include) {\n if ( !isMaster() && getMasterValve() != null && getMasterValve() != this ) {\n return getMasterValve().getAllValves(include);\n }\n\n List<AbstractTankValve> valves = getTankTiles(AbstractTankValve.class);\n if ( include ) valves.add(this);\n return valves;\n }\n\n /**\n * Let a player build a tank!\n *\n * @param player - The player that tries to build the tank\n * @param inside - The direction of the inside of the tank\n */\n public void buildTank_player(EntityPlayer player, EnumFacing inside) {\n if ( getWorld().isRemote ) {\n return;\n }\n\n buildPlayer = player;\n buildTank(inside);\n }\n\n /**\n * Let's build a tank!\n *\n * @param inside - The direction of the inside of the tank\n */\n private void buildTank(EnumFacing inside) {\n /**\n * Don't build if it's on the client!\n */\n if ( getWorld().isRemote ) {\n return;\n }\n\n /**\n * Let's first set the tank to be invalid,\n * since it should stay like that if the building fails.\n * Also, let's reset variables.\n */\n setValid(false);\n\n getTankConfig().setFluidCapacity(0);\n\n tankTiles.clear();\n\n /**\n * Now, set the inside direction according to the variable.\n */\n if ( inside != null ) {\n setTileFacing(inside);\n }\n\n /**\n * Actually setup the tank here\n */\n if ( !setupTank() ) {\n return;\n }\n\n /**\n * Just in case, set *initiated* to false again.\n * Also, update our neighbor blocks, e.g. pipes or similar.\n */\n initiated = false;\n buildPlayer = null;\n updateBlockAndNeighbors();\n }\n\n private void setTankTileFacing(TreeMap<Integer, List<LayerBlockPos>> airBlocks, TileEntity tankTile) {\n List<BlockPos> possibleAirBlocks = new ArrayList<>();\n for (EnumFacing dr : EnumFacing.VALUES) {\n if ( getWorld().isAirBlock(tankTile.getPos().offset(dr)) ) {\n possibleAirBlocks.add(tankTile.getPos().offset(dr));\n }\n }\n\n BlockPos insideAir = null;\n for (int layer : airBlocks.keySet()) {\n for (BlockPos pos : possibleAirBlocks) {\n if ( airBlocks.get(layer).contains(pos) ) {\n insideAir = pos;\n break;\n }\n }\n }\n\n if ( insideAir == null ) {\n return;\n }\n\n BlockPos dist = insideAir.subtract(tankTile.getPos());\n for (EnumFacing dr : EnumFacing.VALUES) {\n if ( dist.equals(new BlockPos(dr.getXOffset(), dr.getYOffset(), dr.getZOffset())) ) {\n ((IFacingTile) tankTile).setTileFacing(dr);\n break;\n }\n }\n }\n\n private boolean searchAlgorithm() {\n int currentAirBlocks = 1;\n int maxAirBlocks = ModConfig.general.maxAirBlocks;\n BlockPos insidePos = getPos().offset(getTileFacing());\n\n Queue<BlockPos> to_check = new LinkedList<>();\n List<BlockPos> checked_blocks = new ArrayList<>();\n TreeMap<Integer, List<LayerBlockPos>> air_blocks = new TreeMap<>();\n TreeMap<Integer, List<LayerBlockPos>> frame_blocks = new TreeMap<>();\n\n LayerBlockPos pos = new LayerBlockPos(insidePos, 0);\n air_blocks.put(0, Lists.newArrayList(pos));\n\n to_check.add(insidePos);\n\n while ( !to_check.isEmpty() ) {\n BlockPos nextCheck = to_check.remove();\n for (EnumFacing facing : EnumFacing.VALUES) {\n BlockPos offsetPos = nextCheck.offset(facing);\n int layer = offsetPos.getY() - insidePos.getY();\n\n air_blocks.putIfAbsent(layer, Lists.newArrayList());\n frame_blocks.putIfAbsent(layer, Lists.newArrayList());\n\n if ( checked_blocks.contains(offsetPos) ) {\n continue;\n }\n checked_blocks.add(offsetPos);\n\n LayerBlockPos _pos = new LayerBlockPos(offsetPos, offsetPos.getY() - insidePos.getY());\n if ( getWorld().isAirBlock(offsetPos) ) {\n if ( !air_blocks.get(layer).contains(_pos) ) {\n air_blocks.get(layer).add(_pos);\n to_check.add(offsetPos);\n currentAirBlocks++;\n }\n } else {\n if (isBlockBlacklisted(_pos)) {\n return false;\n }\n frame_blocks.get(layer).add(_pos);\n }\n }\n if ( currentAirBlocks > maxAirBlocks ) {\n if ( buildPlayer != null ) {\n GenericUtil.sendMessageToClient(buildPlayer, \"chat.ffs.valve_too_much_air\", false, maxAirBlocks);\n }\n return false;\n }\n }\n\n if ( currentAirBlocks == 0 ) {\n return false;\n }\n\n maps.put(0, frame_blocks);\n maps.put(1, air_blocks);\n return true;\n }\n\n private boolean isBlockBlacklisted(BlockPos pos) {\n if (world.getTileEntity(pos) instanceof AbstractTankTile) return false;\n\n IBlockState state = world.getBlockState(pos);\n int metadata = state.getBlock().getMetaFromState(state);\n\n String registryName = state.getBlock().getRegistryName().toString();\n String registryName_WithMetadata = registryName + \"@\" + metadata;\n\n for (String key : ModConfig.general.blockBlacklist) {\n if (key.equalsIgnoreCase(registryName) || key.equalsIgnoreCase(registryName_WithMetadata)) {\n return !ModConfig.general.blockBlacklistInvert;\n }\n }\n return ModConfig.general.blockBlacklistInvert;\n }\n\n private boolean setupTank() {\n if ( !searchAlgorithm() ) {\n return false;\n }\n\n int size = 0;\n for (int layer : maps.get(1).keySet()) {\n size += maps.get(1).get(layer).size();\n }\n getTankConfig().setFluidCapacity(size * ModConfig.general.mbPerTankBlock);\n\n for (int layer : maps.get(1).keySet()) {\n for (BlockPos pos : maps.get(1).get(layer)) {\n if ( !getWorld().isAirBlock(pos) ) {\n return false;\n }\n }\n }\n\n FluidStack tempNewFluidStack = getTankConfig().getFluidStack();\n\n List<TileEntity> facingTiles = new ArrayList<>();\n for (int layer : maps.get(0).keySet()) {\n for (BlockPos pos : maps.get(0).get(layer)) {\n IBlockState check = getWorld().getBlockState(pos);\n if ( FancyFluidStorage.tankManager.isPartOfTank(getWorld(), pos) ) {\n AbstractTankValve valve = FancyFluidStorage.tankManager.getValveForBlock(getWorld(), pos);\n if ( valve != null && valve != this ) {\n GenericUtil.sendMessageToClient(buildPlayer, \"chat.ffs.valve_other_tank\", false);\n return false;\n }\n continue;\n }\n\n TileEntity tile = getWorld().getTileEntity(pos);\n if ( tile != null ) {\n if ( tile instanceof IFacingTile ) {\n facingTiles.add(tile);\n }\n\n if ( tile instanceof AbstractTankValve ) {\n AbstractTankValve valve = (AbstractTankValve) tile;\n if ( valve == this ) {\n continue;\n }\n\n if ( valve.getTankConfig().getFluidStack() != null ) {\n if ( getTankConfig() != null && getTankConfig().getFluidStack() != null ) {\n FluidStack myFS = getTankConfig().getFluidStack();\n FluidStack otherFS = valve.getTankConfig().getFluidStack();\n\n if ( !myFS.isFluidEqual(otherFS) ) {\n GenericUtil.sendMessageToClient(buildPlayer, \"chat.ffs.valve_different_fluids\", false);\n return false;\n }\n } else {\n tempNewFluidStack = valve.getTankConfig().getFluidStack();\n }\n }\n }\n }\n\n if ( !GenericUtil.areTankBlocksValid(check, getWorld(), pos, GenericUtil.getInsideForTankFrame(getAirBlocks(), pos)) && !GenericUtil.isBlockGlass(check) ) {\n return false;\n }\n }\n }\n\n getTankConfig().setFluidStack(tempNewFluidStack);\n // Make sure we don't overfill a tank. If the new tank is smaller than the old one, excess liquid disappear.\n if ( getTankConfig().getFluidStack() != null ) {\n getTankConfig().getFluidStack().amount = Math.min(getTankConfig().getFluidStack().amount, getTankConfig().getFluidCapacity());\n }\n\n for (TileEntity facingTile : facingTiles) {\n setTankTileFacing(maps.get(1), facingTile);\n }\n isMaster = true;\n\n for (int layer : maps.get(0).keySet()) {\n for (BlockPos pos : maps.get(0).get(layer)) {\n TileEntity tile = getWorld().getTileEntity(pos);\n if ( tile == this ) {\n continue;\n }\n\n if ( tile != null ) {\n if ( tile instanceof AbstractTankValve ) {\n AbstractTankValve valve = (AbstractTankValve) tile;\n\n valve.isMaster = false;\n valve.setValvePos(getPos());\n valve.setTankConfig(getTankConfig());\n tankTiles.add(valve);\n } else if ( tile instanceof AbstractTankTile ) {\n AbstractTankTile tankTile = (AbstractTankTile) tile;\n tankTile.setValvePos(getPos());\n tankTiles.add((AbstractTankTile) tile);\n }\n }\n }\n }\n\n setValid(true);\n\n FancyFluidStorage.tankManager.add(getWorld(), getPos(), getAirBlocks(), getFrameBlocks());\n\n return true;\n }\n\n public void breakTank() {\n if ( getWorld().isRemote ) {\n return;\n }\n\n if ( !isMaster() && getMasterValve() != null && getMasterValve() != this ) {\n getMasterValve().breakTank();\n return;\n }\n\n FancyFluidStorage.tankManager.remove(getWorld().provider.getDimension(), getPos());\n NetworkHandler.sendPacketToAllPlayers(new FFSPacket.Client.OnTankBreak(this));\n\n for (AbstractTankValve valve : getAllValves(false)) {\n if ( valve == this ) {\n continue;\n }\n\n valve.setTankConfig(null);\n valve.setValvePos(null);\n valve.setValid(false);\n valve.updateBlockAndNeighbors(true);\n }\n setValid(false);\n\n tankTiles.removeAll(getTankTiles(AbstractTankValve.class));\n for (AbstractTankTile tankTile : tankTiles) {\n tankTile.setValvePos(null);\n }\n\n tankTiles.clear();\n\n updateBlockAndNeighbors(true);\n }\n\n @Override\n public boolean isValid() {\n if ( getMasterValve() == null || getMasterValve() == this )\n return this.isValid;\n\n return getMasterValve().isValid;\n }\n\n private void setValid(boolean isValid) {\n this.isValid = isValid;\n }\n\n private void updateBlockAndNeighbors() {\n updateBlockAndNeighbors(false);\n }\n\n private void updateBlockAndNeighbors(boolean onlyThis) {\n if ( getWorld().isRemote )\n return;\n\n markForUpdateNow();\n\n if ( !tankTiles.isEmpty() && !onlyThis ) {\n for (AbstractTankTile tile : tankTiles) {\n if ( tile == this ) {\n continue;\n }\n\n tile.markForUpdateNow(2);\n }\n }\n }\n\n private void updateComparatorOutput() {\n if ( this.lastComparatorOut != getComparatorOutput() ) {\n this.lastComparatorOut = getComparatorOutput();\n if ( isMaster() ) {\n for (AbstractTankValve otherValve : getTankTiles(AbstractTankValve.class)) {\n getWorld().updateComparatorOutputLevel(otherValve.getPos(), otherValve.getBlockType());\n }\n }\n getWorld().updateComparatorOutputLevel(getPos(), getBlockType());\n }\n }\n\n @Override\n public void markForUpdate() {\n updateComparatorOutput();\n\n super.markForUpdate();\n }\n\n public boolean isMaster() {\n return isMaster;\n }\n\n @Override\n public AbstractTankValve getMasterValve() {\n return isMaster() ? this : super.getMasterValve();\n }\n\n @Override\n public String getTileName() {\n if ( this.tile_name.isEmpty() ) {\n setTileName(GenericUtil.getUniquePositionName(this));\n }\n\n return this.tile_name;\n }\n\n @Override\n public void setTileName(String name) {\n this.tile_name = name;\n }\n\n @Override\n public EnumFacing getTileFacing() {\n return this.tile_facing;\n }\n\n @Override\n public void setTileFacing(EnumFacing facing) {\n this.tile_facing = facing;\n }\n\n @Override\n public void readFromNBT(NBTTagCompound tag) {\n super.readFromNBT(tag);\n\n isMaster = tag.getBoolean(\"master\");\n if ( isMaster() ) {\n isValid = tag.getBoolean(\"isValid\");\n getTankConfig().readFromNBT(tag);\n\n if ( getWorld() != null && getWorld().isRemote ) {\n if ( isValid() ) {\n if ( !FancyFluidStorage.tankManager.isValveInLists(getWorld(), this) ) {\n NetworkHandler.sendPacketToServer(new FFSPacket.Server.OnTankRequest(this));\n }\n }\n }\n }\n\n//\t\tif(tag.hasKey(\"bottomDiagF\") && tag.hasKey(\"topDiagF\")) {\n//\t\t\tint[] bottomDiagF = tag.getIntArray(\"bottomDiagF\");\n//\t\t\tint[] topDiagF = tag.getIntArray(\"topDiagF\");\n//\t\t\tbottomDiagFrame = new BlockPos(bottomDiagF[0], bottomDiagF[1], bottomDiagF[2]);\n//\t\t\ttopDiagFrame = new BlockPos(topDiagF[0], topDiagF[1], topDiagF[2]);\n//\t\t}\n\n readTileNameFromNBT(tag);\n readTileFacingFromNBT(tag);\n }\n\n @Override\n public NBTTagCompound writeToNBT(NBTTagCompound tag) {\n tag.setBoolean(\"master\", isMaster());\n if ( isMaster() ) {\n tag.setBoolean(\"isValid\", isValid());\n getTankConfig().writeToNBT(tag);\n }\n\n//\t\tif(bottomDiagFrame != null && topDiagFrame != null) {\n//\t\t\ttag.setIntArray(\"bottomDiagF\", new int[]{bottomDiagFrame.getX(), bottomDiagFrame.getY(), bottomDiagFrame.getZ()});\n//\t\t\ttag.setIntArray(\"topDiagF\", new int[]{topDiagFrame.getX(), topDiagFrame.getY(), topDiagFrame.getZ()});\n//\t\t}\n\n saveTileNameToNBT(tag);\n saveTileFacingToNBT(tag);\n\n super.writeToNBT(tag);\n return tag;\n }\n\n @Override\n public boolean hasFastRenderer() {\n return true;\n }\n\n @Override\n public AxisAlignedBB getRenderBoundingBox() {\n return INFINITE_EXTENT_AABB;\n }\n\n public int fillFromContainer(FluidStack resource, boolean doFill) {\n if ( !canFillIncludingContainers(resource) ) {\n return 0;\n }\n\n return getTankConfig().getFluidTank().fill(resource, doFill);\n }\n\n private boolean canFillIncludingContainers(FluidStack fluid) {\n if ( getTankConfig().getFluidStack() != null && !getTankConfig().getFluidStack().isFluidEqual(fluid) ) {\n return false;\n }\n\n return !(getTankConfig().isFluidLocked() && !getTankConfig().getLockedFluid().isFluidEqual(fluid));\n }\n\n public int getComparatorOutput() {\n if ( !isValid() ) {\n return 0;\n }\n\n return MathHelper.floor(((float) this.getTankConfig().getFluidAmount() / this.getTankConfig().getFluidCapacity()) * 14.0F);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof AbstractTankValve && ((AbstractTankValve) obj).getPos().equals(getPos());\n\n }\n}", "public interface INameableTile {\n\n default String getTileName() {\n return \"\";\n }\n\n void setTileName(String name);\n\n default void saveTileNameToNBT(NBTTagCompound tag) {\n if ( !getTileName().isEmpty() ) {\n tag.setString(\"tile_name\", getTileName());\n }\n }\n\n default void readTileNameFromNBT(NBTTagCompound tag) {\n if ( tag.hasKey(\"tile_name\") ) {\n setTileName(tag.getString(\"tile_name\"));\n }\n }\n\n}", "@SideOnly(Side.CLIENT)\npublic class ClientRenderHelper {\n public static final ResourceLocation MC_BLOCK_SHEET = new ResourceLocation(\"textures/atlas/blocks.png\");\n\n public static void setBlockTextureSheet() {\n\n Minecraft.getMinecraft().renderEngine.bindTexture(MC_BLOCK_SHEET);\n }\n\n public static void setGLColorFromInt(int color) {\n\n float red = (float) (color >> 16 & 255) / 255.0F;\n float green = (float) (color >> 8 & 255) / 255.0F;\n float blue = (float) (color & 255) / 255.0F;\n GlStateManager.color(red, green, blue, 1.0F);\n }\n\n public static TextureAtlasSprite getTexture(String location) {\n\n return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location);\n }\n\n public static TextureAtlasSprite getTexture(ResourceLocation location) {\n\n return getTexture(location.toString());\n }\n\n public static void putTexturedQuad(BufferBuilder renderer, TextureAtlasSprite sprite, double x, double y, double z, double w, double h, double d, EnumFacing face, int color, int brightness, boolean flowing) {\n int l1 = brightness >> 0x10 & 0xFFFF;\n int l2 = brightness & 0xFFFF;\n int a = color >> 24 & 0xFF;\n int r = color >> 16 & 0xFF;\n int g = color >> 8 & 0xFF;\n int b = color & 0xFF;\n putTexturedQuad(renderer, sprite, x, y, z, w, h, d, face, r, g, b, a, l1, l2, flowing);\n }\n\n private static void putTexturedQuad(BufferBuilder renderer, TextureAtlasSprite sprite, double x, double y, double z, double w, double h, double d, EnumFacing face, int r, int g, int b, int a, int light1, int light2, boolean flowing) {\n if ( sprite == null ) {\n return;\n }\n double minU;\n double maxU;\n double minV;\n double maxV;\n double size = 16f;\n if ( flowing ) {\n size = 8f;\n }\n double x2 = x + w;\n double y2 = y + h;\n double z2 = z + d;\n double xt1 = x % 1d;\n double xt2 = xt1 + w;\n while ( xt2 > 1f ) xt2 -= 1f;\n double yt1 = y % 1d;\n double yt2 = yt1 + h;\n while ( yt2 > 1f ) yt2 -= 1f;\n double zt1 = z % 1d;\n double zt2 = zt1 + d;\n while ( zt2 > 1f ) zt2 -= 1f;\n\n if ( flowing ) {\n double tmp = 1d - yt1;\n yt1 = 1d - yt2;\n yt2 = tmp;\n }\n\n switch (face) {\n case DOWN:\n case UP:\n minU = sprite.getInterpolatedU(xt1 * size);\n maxU = sprite.getInterpolatedU(xt2 * size);\n minV = sprite.getInterpolatedV(zt1 * size);\n maxV = sprite.getInterpolatedV(zt2 * size);\n break;\n case NORTH:\n case SOUTH:\n minU = sprite.getInterpolatedU(xt2 * size);\n maxU = sprite.getInterpolatedU(xt1 * size);\n minV = sprite.getInterpolatedV(yt1 * size);\n maxV = sprite.getInterpolatedV(yt2 * size);\n break;\n case WEST:\n case EAST:\n minU = sprite.getInterpolatedU(zt2 * size);\n maxU = sprite.getInterpolatedU(zt1 * size);\n minV = sprite.getInterpolatedV(yt1 * size);\n maxV = sprite.getInterpolatedV(yt2 * size);\n break;\n default:\n minU = sprite.getMinU();\n maxU = sprite.getMaxU();\n minV = sprite.getMinV();\n maxV = sprite.getMaxV();\n }\n\n switch (face) {\n case DOWN:\n renderer.pos(x, y, z).color(r, g, b, a).tex(minU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y, z).color(r, g, b, a).tex(maxU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y, z2).color(r, g, b, a).tex(maxU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y, z2).color(r, g, b, a).tex(minU, maxV).lightmap(light1, light2).endVertex();\n break;\n case UP:\n renderer.pos(x, y2, z).color(r, g, b, a).tex(minU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y2, z2).color(r, g, b, a).tex(minU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y2, z2).color(r, g, b, a).tex(maxU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y2, z).color(r, g, b, a).tex(maxU, minV).lightmap(light1, light2).endVertex();\n break;\n case NORTH:\n renderer.pos(x, y, z).color(r, g, b, a).tex(minU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y2, z).color(r, g, b, a).tex(minU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y2, z).color(r, g, b, a).tex(maxU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y, z).color(r, g, b, a).tex(maxU, maxV).lightmap(light1, light2).endVertex();\n break;\n case SOUTH:\n renderer.pos(x, y, z2).color(r, g, b, a).tex(maxU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y, z2).color(r, g, b, a).tex(minU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y2, z2).color(r, g, b, a).tex(minU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y2, z2).color(r, g, b, a).tex(maxU, minV).lightmap(light1, light2).endVertex();\n break;\n case WEST:\n renderer.pos(x, y, z).color(r, g, b, a).tex(maxU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y, z2).color(r, g, b, a).tex(minU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y2, z2).color(r, g, b, a).tex(minU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x, y2, z).color(r, g, b, a).tex(maxU, minV).lightmap(light1, light2).endVertex();\n break;\n case EAST:\n renderer.pos(x2, y, z).color(r, g, b, a).tex(minU, maxV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y2, z).color(r, g, b, a).tex(minU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y2, z2).color(r, g, b, a).tex(maxU, minV).lightmap(light1, light2).endVertex();\n renderer.pos(x2, y, z2).color(r, g, b, a).tex(maxU, maxV).lightmap(light1, light2).endVertex();\n break;\n }\n }\n\n public static int changeAlpha(int origColor, int userInputAlpha) {\n origColor = origColor & 0x00ffffff; //drop the previous alpha value\n return (userInputAlpha << 24) | origColor; //add the one the user inputted\n }\n\n}", "public class GenericUtil {\n private static List<Block> blacklistedBlocks;\n\n private static Map<World, ForgeChunkManager.Ticket> chunkloadTicketMap;\n\n public static void init() {\n blacklistedBlocks = new ArrayList<>();\n\n blacklistedBlocks.add(Blocks.GRASS);\n blacklistedBlocks.add(Blocks.DIRT);\n blacklistedBlocks.add(Blocks.BEDROCK);\n blacklistedBlocks.add(Blocks.SPONGE);\n\n chunkloadTicketMap = new HashMap<>();\n }\n\n public static String getUniquePositionName(AbstractTankValve valve) {\n return \"tile_\" + Long.toHexString(valve.getPos().toLong());\n }\n\n public static boolean isBlockGlass(IBlockState blockState) {\n if ( blockState == null || blockState.getMaterial() == Material.AIR ) {\n return false;\n }\n\n if ( blockState.getBlock() instanceof BlockGlass ) {\n return true;\n }\n\n ItemStack is = new ItemStack(blockState.getBlock(), 1);\n return blockState.getMaterial() == Material.GLASS && !is.getTranslationKey().contains(\"pane\");\n }\n\n public static EnumFacing getInsideForTankFrame(TreeMap<Integer, List<LayerBlockPos>> airBlocks, BlockPos frame) {\n for (EnumFacing facing : EnumFacing.VALUES) {\n for (int layer : airBlocks.keySet()) {\n if ( airBlocks.get(layer).contains(frame.offset(facing)) ) {\n return facing;\n }\n }\n }\n return null;\n }\n\n public static boolean areTankBlocksValid(IBlockState bottomBlock, World world, BlockPos bottomPos, EnumFacing facing) {\n return isValidTankBlock(world, bottomPos, bottomBlock, facing);\n }\n\n public static boolean isValidTankBlock(World world, BlockPos pos, IBlockState state, EnumFacing facing) {\n if ( state == null ) {\n return false;\n }\n\n if ( world.isAirBlock(pos) ) {\n return false;\n }\n\n if ( state.getBlock() instanceof BlockFalling ) {\n return false;\n }\n\n if ( Compatibility.INSTANCE.isCNBLoaded ) {\n if ( CNBAPIAccess.apiInstance.isBlockChiseled(world, pos) ) {\n return facing != null && CNBCompatibility.INSTANCE.isValid(world, pos, facing);\n }\n }\n\n return isBlockGlass(state) || facing == null || world.isSideSolid(pos, facing);\n }\n\n public static boolean isFluidContainer(ItemStack playerItem) {\n return FluidUtil.getFluidHandler(playerItem) != null;\n }\n\n public static boolean fluidContainerHandler(World world, AbstractTankValve valve, EntityPlayer player) {\n if ( world.isRemote ) {\n return true;\n }\n\n ItemStack current = player.getHeldItemMainhand();\n\n if ( current != ItemStack.EMPTY ) {\n if ( !isFluidContainer(current) ) {\n return false;\n }\n\n return FluidUtil.interactWithFluidHandler(player, EnumHand.MAIN_HAND, valve.getTankConfig().getFluidTank());\n }\n return false;\n }\n\n public static String intToFancyNumber(int number) {\n return NumberFormat.getIntegerInstance(Locale.ENGLISH).format(number);\n }\n\n public static void sendMessageToClient(EntityPlayer player, String key, boolean actionBar) {\n if ( player == null ) {\n return;\n }\n\n player.sendStatusMessage(new TextComponentTranslation(key), actionBar);\n }\n\n public static void sendMessageToClient(EntityPlayer player, String key, boolean actionBar, Object... args) {\n if ( player == null ) {\n return;\n }\n\n player.sendStatusMessage(new TextComponentTranslation(key, args), actionBar);\n }\n\n public static void initChunkLoadTicket(World world, ForgeChunkManager.Ticket ticket) {\n chunkloadTicketMap.put(world, ticket);\n }\n\n public static ForgeChunkManager.Ticket getChunkLoadTicket(World world) {\n if ( chunkloadTicketMap.containsKey(world) ) {\n return chunkloadTicketMap.get(world);\n }\n\n ForgeChunkManager.Ticket chunkloadTicket = ForgeChunkManager.requestTicket(FancyFluidStorage.INSTANCE, world, ForgeChunkManager.Type.NORMAL);\n chunkloadTicketMap.put(world, chunkloadTicket);\n return chunkloadTicket;\n }\n\n}" ]
import com.lordmau5.ffs.FancyFluidStorage; import com.lordmau5.ffs.network.FFSPacket; import com.lordmau5.ffs.network.NetworkHandler; import com.lordmau5.ffs.tile.abstracts.AbstractTankTile; import com.lordmau5.ffs.tile.abstracts.AbstractTankValve; import com.lordmau5.ffs.tile.interfaces.INameableTile; import com.lordmau5.ffs.util.ClientRenderHelper; import com.lordmau5.ffs.util.GenericUtil; import com.mojang.realmsclient.gui.ChatFormatting; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; import org.lwjgl.opengl.GL11; import java.awt.*; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package com.lordmau5.ffs.client.gui; /** * Created by Dustin on 05.07.2015. */ public class GuiValve extends GuiScreen { private static final ResourceLocation tex_valve = new ResourceLocation(FancyFluidStorage.MODID + ":textures/gui/gui_tank_valve.png"); private static final ResourceLocation tex_no_valve = new ResourceLocation(FancyFluidStorage.MODID + ":textures/gui/gui_tank_no_valve.png"); private final AbstractTankValve valve; private final AbstractTankValve masterValve; private final int xSize_Valve = 196; private final int ySize_Valve = 128; private final int xSize_NoValve = 96; private final int ySize_NoValve = 128; private GuiButtonLockFluid lockFluidButton; private boolean isNonValve = false; private AbstractTankTile tile; private GuiTextField tileName; private int left = 0, top = 0; private int mouseX, mouseY; public GuiValve(AbstractTankTile tile, boolean isNonValve) { super(); this.isNonValve = isNonValve; if ( !isNonValve ) { this.tile = tile; if ( tile instanceof AbstractTankValve ) { this.valve = (AbstractTankValve) tile; } else { this.valve = tile.getMasterValve(); } this.masterValve = tile.getMasterValve(); } else { this.valve = this.masterValve = tile.getMasterValve(); } } private void initGuiValve() { this.left = (this.width - this.xSize_Valve) / 2; this.top = (this.height - this.ySize_Valve) / 2; if ( this.tile instanceof INameableTile ) { this.tileName = new GuiTextField(0, this.fontRenderer, this.left + 90, this.top + 102, 82, 10); this.tileName.setText(this.valve.getTileName()); this.tileName.setMaxStringLength(32); } this.buttonList.add(this.lockFluidButton = new GuiButtonLockFluid(this.left + 62, this.top + 26, this.masterValve.getTankConfig().isFluidLocked())); } @Override public void initGui() { super.initGui(); if ( isNonValve ) { this.left = (this.width - this.xSize_NoValve) / 2; this.top = (this.height - this.ySize_NoValve) / 2; this.buttonList.add(this.lockFluidButton = new GuiButtonLockFluid(this.left + 66, this.top + 26, this.masterValve.getTankConfig().isFluidLocked())); } else { initGuiValve(); } } @Override public void onGuiClosed() { super.onGuiClosed(); if ( this.tile instanceof INameableTile ) { if ( !this.tileName.getText().isEmpty() ) {
NetworkHandler.sendPacketToServer(new FFSPacket.Server.UpdateTileName(this.tile, this.tileName.getText()));
2
ganeshkamathp/killingspree
core/src/com/sillygames/killingSpree/serverEntities/ServerBomb.java
[ "public interface ExplodingWeaponCategory {\r\n \r\n public void explode();\r\n \r\n public ServerEntity getBomber();\r\n\r\n}\r", "public interface NonExplodingWeaponCategory {\r\n ServerEntity getShooter();\r\n}\r", "public class Utils {\r\n \r\n public static boolean wrapBody(Vector2 position) {\r\n boolean wrap = false;\r\n if (position.x > WorldRenderer.VIEWPORT_WIDTH) {\r\n wrap = true;\r\n position.x -= WorldRenderer.VIEWPORT_WIDTH;\r\n } else if (position.x < 0) {\r\n wrap = true;\r\n position.x += WorldRenderer.VIEWPORT_WIDTH;\r\n }\r\n if (position.y > WorldRenderer.VIEWPORT_HEIGHT) {\r\n wrap = true;\r\n position.y -= WorldRenderer.VIEWPORT_HEIGHT;\r\n } else if (position.y < 0) {\r\n wrap = true;\r\n position.y += WorldRenderer.VIEWPORT_HEIGHT;\r\n }\r\n return wrap;\r\n }\r\n \r\n}\r", "public enum ActorType { ERROR, PLAYER, BLOB, ARROW, BULLET, FLY, FROG, BOMB };\r", "public class WorldBodyUtils {\r\n \r\n public WorldManager worldManager;\r\n public ArrayList<ServerEntity> entities;\r\n private Circle circle;\r\n public AudioMessage audio;\r\n private World world;\r\n private Vector2 tempPlayerPosition;\r\n \r\n public WorldBodyUtils(WorldManager worldManager) {\r\n circle = new Circle();\r\n this.worldManager = worldManager;\r\n entities = new ArrayList<ServerEntity>();\r\n audio = worldManager.audio;\r\n this.world = worldManager.getWorld();\r\n tempPlayerPosition = new Vector2();\r\n }\r\n \r\n public Body addBox(float w, float h, float x, float y, BodyType type){\r\n Body body = new Body(x - w/2, y - h/2, w, h, type);\r\n body.setWorld(world);\r\n world.bodies.add(body);\r\n return body;\r\n }\r\n\r\n public void createWorldObject(MapObject object) {\r\n if (object instanceof RectangleMapObject) {\r\n Rectangle rectangle = ((RectangleMapObject) object).getRectangle();\r\n Body body = new Body(rectangle);\r\n world.bodies.add(body);\r\n \r\n if (rectangle.x < 20) {\r\n rectangle = new Rectangle(rectangle);\r\n rectangle.x += WorldRenderer.VIEWPORT_WIDTH;\r\n body = new Body(rectangle);\r\n world.bodies.add(body);\r\n }\r\n \r\n if (rectangle.x + rectangle.width > WorldRenderer.VIEWPORT_WIDTH - 20) {\r\n rectangle = new Rectangle(rectangle);\r\n rectangle.x -= WorldRenderer.VIEWPORT_WIDTH;\r\n body = new Body(rectangle);\r\n world.bodies.add(body);\r\n }\r\n \r\n if (rectangle.y < 20) {\r\n rectangle = new Rectangle(rectangle);\r\n rectangle.y += WorldRenderer.VIEWPORT_HEIGHT;\r\n body = new Body(rectangle);\r\n world.bodies.add(body);\r\n }\r\n if (rectangle.y > WorldRenderer.VIEWPORT_HEIGHT - 20) {\r\n rectangle = new Rectangle(rectangle);\r\n rectangle.y -= WorldRenderer.VIEWPORT_WIDTH;\r\n body = new Body(rectangle);\r\n world.bodies.add(body);\r\n }\r\n }\r\n }\r\n \r\n public ServerArrow AddArrow(float x, float y) {\r\n ServerArrow arrow = new ServerArrow(worldManager.id++, x, y, this);\r\n arrow.body.setUserData(arrow);\r\n entities.add(arrow);\r\n return arrow;\r\n }\r\n \r\n public ServerBullet AddBullet(float x, float y, ServerPlayer shooter) {\r\n ServerBullet bullet = new ServerBullet(worldManager.id++, x, y, this);\r\n bullet.shooter = shooter;\r\n bullet.body.setUserData(bullet);\r\n entities.add(bullet);\r\n return bullet;\r\n }\r\n \r\n public ServerBomb AddBomb(float x, float y, ServerPlayer bomber) {\r\n for (Body body: world.bodies) {\r\n if (body.rectangle.contains(x, y)) {\r\n return null;\r\n }\r\n }\r\n ServerBomb bomb = new ServerBomb(worldManager.id++, x, y, this);\r\n bomb.bomber = bomber;\r\n bomb.body.setUserData(bomb);\r\n entities.add(bomb);\r\n return bomb;\r\n }\r\n\r\n public void destroyBody(Body body) {\r\n body.toDestroy = true;\r\n }\r\n\r\n public ArrayList<Vector2> getPlayers(Vector2 point, float distance) {\r\n ArrayList<Vector2> playersPosition = new ArrayList<Vector2>();\r\n distance *= distance;\r\n for (ServerPlayer player: worldManager.playerList.values()) {\r\n Vector2 position = player.body.getPosition();\r\n if (point.dst2(position.x, position.y) < distance) {\r\n playersPosition.add(tempPlayerPosition.set(position.x, position.y));\r\n }\r\n else if (point.dst2(position.x + WorldRenderer.VIEWPORT_WIDTH, position.y) < distance) {\r\n playersPosition.add(tempPlayerPosition.set(position.x + WorldRenderer.VIEWPORT_WIDTH, position.y));\r\n }\r\n else if (point.dst2(position.x - WorldRenderer.VIEWPORT_WIDTH, position.y) < distance) {\r\n playersPosition.add(tempPlayerPosition.set(position.x - WorldRenderer.VIEWPORT_WIDTH, position.y));\r\n \r\n }\r\n else if (point.dst2(position.x, position.y + WorldRenderer.VIEWPORT_HEIGHT) < distance) {\r\n playersPosition.add(tempPlayerPosition.set(position.x, position.y + WorldRenderer.VIEWPORT_HEIGHT));\r\n }\r\n else if (point.dst2(position.x, position.y - WorldRenderer.VIEWPORT_HEIGHT) < distance) {\r\n playersPosition.add(tempPlayerPosition.set(position.x, position.y - WorldRenderer.VIEWPORT_HEIGHT));\r\n }\r\n }\r\n return playersPosition;\r\n }\r\n\r\n public void destroyEntities(ServerBomb bomb, float radius, Vector2 position) {\r\n Body body = bomb.body;\r\n circle.set(position, radius);\r\n for (ServerEntity entity: worldManager.entities) {\r\n if (entity.body == body || entity.body.toDestroy) {\r\n continue;\r\n }\r\n if (Intersector.overlaps(circle, entity.body.rectangle)) {\r\n Vector2 step = entity.body.getPosition();\r\n float length = position.dst(step);\r\n step.sub(position);\r\n float max = Math.max(step.x, step.y);\r\n step.scl(4 / max);\r\n Body otherBody = Ray.findBody(world,\r\n body, step, length, true);\r\n if (otherBody == null) {\r\n if (entity instanceof LivingCategory) {\r\n if (((LivingCategory)entity.body.getUserData()).kill()) {\r\n if (bomb.bomber != entity.body.getUserData())\r\n bomb.bomber.addKill();\r\n else {\r\n bomb.bomber.reduceKill();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r", "public class WorldRenderer {\r\n \r\n private static final boolean DEBUG = false;\r\n public static int VIEWPORT_WIDTH = 525;\r\n public static int VIEWPORT_HEIGHT = 375;\r\n private WorldManager worldManager;\r\n private OrthographicCamera camera;\r\n private OrthogonalTiledMapRenderer renderer;\r\n private FitViewport viewport;\r\n private TiledMap map;\r\n private boolean isServer;\r\n private SpriteBatch batch;\r\n private Client client;\r\n private int count;\r\n private ControlsSender controlsSender;\r\n public StateProcessor stateProcessor;\r\n private ConcurrentHashMap<Short, ClientEntity> worldMap;\r\n long previousTime;\r\n private WorldDebugRenderer debugRenderer;\r\n private onScreenControls controls;\r\n private int screenWidth;\r\n private int screenHeight;\r\n private short recentId;\r\n private float screenShakeX;\r\n private float screenShakeY;\r\n private float screenShakeTime;\r\n private KillingSpree game;\r\n public SFXPlayer audioPlayer;\r\n public HUDRenderer hudRenderer;\r\n private byte previousButtonPresses;\r\n \r\n public WorldRenderer(WorldManager worldManager, Client client, KillingSpree game) {\r\n worldMap = new ConcurrentHashMap<Short, ClientEntity>();\r\n this.worldManager = worldManager;\r\n audioPlayer = new SFXPlayer();\r\n stateProcessor = new StateProcessor(client, worldMap, audioPlayer,\r\n game.platformServices);\r\n if (worldManager != null) {\r\n debugRenderer = new WorldDebugRenderer(worldManager.getWorld());\r\n worldManager.setOutgoingEventListener(stateProcessor);\r\n } else {\r\n this.client = client;\r\n }\r\n camera = new OrthographicCamera();\r\n batch = new SpriteBatch();\r\n controlsSender = new ControlsSender();\r\n recentId = -2;\r\n screenShakeX = 0;\r\n screenShakeY = 0;\r\n screenShakeTime = 0;\r\n hudRenderer = new HUDRenderer();\r\n this.game = game;\r\n }\r\n\r\n public void loadLevel(String level, boolean isServer, String name) {\r\n this.isServer = isServer;\r\n map = new TmxMapLoader().load(level);\r\n TiledMapTileLayer layer = (TiledMapTileLayer) map.\r\n getLayers().get(\"terrain\");\r\n VIEWPORT_WIDTH = (int) (layer.getTileWidth() * layer.getWidth());\r\n VIEWPORT_HEIGHT = (int) (layer.getTileHeight() * layer.getHeight());\r\n viewport = new FitViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, camera);\r\n renderer = new OrthogonalTiledMapRenderer(map);\r\n name = name.trim();\r\n if (name.length() == 0)\r\n name = \"noname\";\r\n if (name.length() >= 10){\r\n name = name.substring(0, 10);\r\n }\r\n ClientDetailsMessage clientDetails = new ClientDetailsMessage();\r\n clientDetails.name = name;\r\n clientDetails.protocolVersion = Constants.PROTOCOL_VERSION;\r\n if (isServer) {\r\n MapLayer collision = map.\r\n getLayers().get(\"collision\");\r\n for(MapObject object: collision.getObjects()) {\r\n worldManager.createWorldObject(object);\r\n }\r\n worldManager.addIncomingEvent(MessageObjectPool.instance.\r\n eventPool.obtain().set(State.RECEIVED, clientDetails));\r\n } else {\r\n client.sendTCP(clientDetails);\r\n }\r\n controls = new onScreenControls();\r\n \r\n }\r\n\r\n @SuppressWarnings(\"unused\")\r\n public void render(float delta) {\r\n// screenShakeTime = 0.1f;\r\n if (screenShakeTime > 0) {\r\n screenShakeTime += delta;\r\n screenShakeX += MathUtils.random(-7, 7);\r\n screenShakeY += MathUtils.random(-7, 7);\r\n if (Math.abs(screenShakeX) > 10) {\r\n screenShakeX = Math.signum(screenShakeX) * 10;\r\n }\r\n if (Math.abs(screenShakeY) > 5) {\r\n screenShakeY = Math.signum(screenShakeY) * 5;\r\n }\r\n if (screenShakeTime > 0.2f) {\r\n screenShakeTime = 0;\r\n screenShakeX = 0;\r\n screenShakeY = 0;\r\n }\r\n }\r\n camera.setToOrtho(false, VIEWPORT_WIDTH + screenShakeX,\r\n VIEWPORT_HEIGHT + screenShakeY);\r\n // Temp experiment to check GC\r\n count++;\r\n if(count % 60 == 0) {\r\n// System.gc();\r\n }\r\n viewport.apply();\r\n renderer.setView(camera);\r\n renderer.render();\r\n batch.setProjectionMatrix(camera.combined);\r\n// if(DEBUG && Gdx.input.isTouched()) {\r\n// Gdx.app.log(\"Touched at\",\r\n// viewport.unproject(new Vector2(Gdx.input.getX(),\r\n// Gdx.input.getY())).toString());\r\n// }\r\n batch.begin();\r\n renderObjects(delta);\r\n batch.end();\r\n if (isServer && DEBUG) {\r\n debugRenderer.render(camera.combined);\r\n }\r\n processControls();\r\n Gdx.gl.glViewport(0, 0, screenWidth, screenHeight);\r\n if (!InputController.instance.controllerEnabled()) {\r\n controls.render();\r\n }\r\n }\r\n\r\n private void renderObjects(float delta) {\r\n long currentTime = TimeUtils.nanoTime();\r\n float alpha = 0;\r\n GameStateMessage nextStateMessage;\r\n if (isServer) {\r\n alpha = 1;\r\n nextStateMessage = stateProcessor.stateQueue.get(stateProcessor.stateQueue.size() - 1);\r\n } else {\r\n stateProcessor.processStateQueue(currentTime);\r\n nextStateMessage = stateProcessor.getNextState();\r\n long nextTime = nextStateMessage.time;\r\n currentTime += stateProcessor.timeOffset;\r\n if (nextTime != previousTime)\r\n alpha = (float)(currentTime - previousTime) / (float)(nextTime - previousTime);\r\n if (currentTime > nextTime) {\r\n alpha = 1;\r\n }\r\n }\r\n \r\n for (EntityState state: nextStateMessage.states) {\r\n short id = recentId;\r\n if (!worldMap.containsKey(state.id) && state.id > recentId) {\r\n ClientEntity entity = null;\r\n if (EntityUtils.ByteToActorType(state.type) == ActorType.PLAYER) {\r\n entity = new ClientPlayer(state.id, state.x, state.y, this);\r\n } else if (EntityUtils.ByteToActorType(state.type) == ActorType.BLOB) {\r\n entity = new ClientBlob(state.id, state.x, state.y, this);\r\n } else if (EntityUtils.ByteToActorType(state.type) == ActorType.ARROW) {\r\n entity = new ClientArrow(state.id, state.x, state.y, this);\r\n } else if (EntityUtils.ByteToActorType(state.type) == ActorType.BULLET) {\r\n entity = new ClientBullet(state.id, state.x, state.y, this);\r\n } else if (EntityUtils.ByteToActorType(state.type) == ActorType.FLY) {\r\n entity = new ClientFly(state.id, state.x, state.y, this);\r\n } else if (EntityUtils.ByteToActorType(state.type) == ActorType.FROG) {\r\n entity = new ClientFrog(state.id, state.x, state.y, this);\r\n } else if (EntityUtils.ByteToActorType(state.type) == ActorType.BOMB) {\r\n entity = new ClientBomb(state.id, state.x, state.y, this);\r\n } else {\r\n Gdx.app.log(\"Error\", \"Couldnt decode actor type\");\r\n Gdx.app.exit();\r\n }\r\n worldMap.put(state.id, entity);\r\n id = (short) Math.max(id, state.id);\r\n }\r\n recentId = id;\r\n }\r\n\r\n for (EntityState state: nextStateMessage.states) {\r\n if (worldMap.get(state.id) != null) {\r\n worldMap.get(state.id).processState(state, alpha);\r\n }\r\n }\r\n for (ClientEntity entity: worldMap.values()) {\r\n if (entity.destroy && entity instanceof ClientBomb)\r\n shakeScreen();\r\n if (entity.remove) {\r\n worldMap.remove(entity.id);\r\n continue;\r\n }\r\n entity.render(delta, batch);\r\n }\r\n// Gdx.app.log(\"alpha \", Float.toString(alpha));\r\n previousTime = currentTime;\r\n \r\n }\r\n\r\n private void processControls() {\r\n \r\n ControlsMessage message = controlsSender.sendControls(controls);\r\n \r\n if (previousButtonPresses != message.buttonPresses) {\r\n if(isServer) {\r\n worldManager.addIncomingEvent(MessageObjectPool.instance.\r\n eventPool.obtain().set(State.RECEIVED, message));\r\n } else {\r\n client.sendUDP(message);\r\n }\r\n previousButtonPresses = message.buttonPresses;\r\n }\r\n \r\n if (controls.closeButton()) {\r\n game.setScreen(new MainMenuScreen(game));\r\n }\r\n }\r\n\r\n public void resize(int width, int height) {\r\n screenWidth = width;\r\n screenHeight = height;\r\n viewport.update(width, height);\r\n camera.update();\r\n }\r\n \r\n public void shakeScreen() {\r\n screenShakeTime = 0.01f;\r\n }\r\n\r\n public void dispose() {\r\n if (client != null) {\r\n client.stop();\r\n }\r\n batch.dispose();\r\n hudRenderer.dispose();\r\n audioPlayer.dispose();\r\n map.dispose();\r\n renderer.dispose();\r\n }\r\n \r\n}\r", "public enum BodyType { StaticBody, DynamicBody }\r", "public class EntityState implements Poolable{\r\n \r\n public short id;\r\n public byte type;\r\n public float x, y;\r\n public float angle;\r\n public short extra;\r\n public float vX, vY;\r\n \r\n @Override\r\n public void reset() {\r\n id = 0;\r\n type = 0;\r\n x = 0;\r\n y = 0;\r\n angle = 0;\r\n extra = 0;\r\n vX = 0;\r\n vY = 0;\r\n }\r\n\r\n}\r" ]
import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.sillygames.killingSpree.categories.ExplodingWeaponCategory; import com.sillygames.killingSpree.categories.NonExplodingWeaponCategory; import com.sillygames.killingSpree.helpers.Utils; import com.sillygames.killingSpree.helpers.EntityUtils.ActorType; import com.sillygames.killingSpree.managers.WorldBodyUtils; import com.sillygames.killingSpree.managers.WorldRenderer; import com.sillygames.killingSpree.managers.physics.Body.BodyType; import com.sillygames.killingSpree.networking.messages.EntityState;
package com.sillygames.killingSpree.serverEntities; public class ServerBomb extends ServerEntity implements ExplodingWeaponCategory { public static final float RADIUS = 10f; public ServerEntity bomber; public float destroyTime; private float velocity; public ServerBomb(short id, float x, float y, WorldBodyUtils world) { super(id, x, y, world); actorType = ActorType.BOMB; body = world.addBox(RADIUS, RADIUS, position.x, position.y, BodyType.DynamicBody); body.setLinearVelocity(velocity, 0); body.setUserData(this); body.restitutionX = 0.5f; body.restitutionY = 0.5f; destroyTime = 1.5f; body.setGravityScale(0.75f); body.xDamping = 0.02f; } @Override public void update(float delta) { destroyTime -= delta; position.set(body.getPosition()); if (Utils.wrapBody(position)) { body.setTransform(position, 0); } if (destroyTime < 0) { explode(); } } @Override public void dispose() { world.destroyBody(body); } @Override
public void updateState(EntityState state) {
7
rodolfodpk/myeslib
inventory-aggregate-root/src/test/java/org/myeslib/example/SampleDomainGsonFactoryTest.java
[ "public interface Command extends Serializable {\n\t\n UUID getCommandId();\n\tLong getTargetVersion();\n\t\n}", "public interface Event extends Serializable {\n\t\n}", "@SuppressWarnings(\"serial\")\n@Data\npublic class AggregateRootHistory implements Serializable {\n\n\tprivate final List<UnitOfWork> unitsOfWork;\n\tprivate final Set<UnitOfWork> persisted;\n\n\tpublic AggregateRootHistory() {\n\t\tthis.unitsOfWork = new LinkedList<>();\n\t\tthis.persisted = new LinkedHashSet<>();\n\t}\n\n\tpublic List<Event> getAllEvents() {\n return getEventsAfterUntil(0, Long.MAX_VALUE);\n\t}\n\n\tpublic List<Event> getEventsAfterUntil(long afterVersion, long untilVersion){\n\t\tList<Event> events = new LinkedList<>();\n\t\tfor (UnitOfWork t : unitsOfWork) {\n\t\t\tif (t.getVersion() > afterVersion && t.getVersion() <= untilVersion){\n\t\t\t\tfor (Event event : t.getEvents()) {\n\t\t\t\t\tevents.add(event);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn events;\n\t}\n\t\n\tpublic List<Event> getEventsUntil(long version){\n\t\tList<Event> events = new LinkedList<>();\n\t\tfor (UnitOfWork t : unitsOfWork) {\n\t\t\tif (t.getVersion() <= version){\n\t\t\t\tfor (Event event : t.getEvents()) {\n\t\t\t\t\tevents.add(event);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn events;\n\t}\n\t\n\tpublic Long getLastVersion() {\n\t\treturn unitsOfWork.size()==0 ? 0 : unitsOfWork.get(unitsOfWork.size()-1).getVersion();\n\t}\n\n\tpublic void add(final UnitOfWork transaction) {\n\t\tcheckNotNull(transaction);\n\t\tunitsOfWork.add(transaction);\n\t}\n\n\tpublic UnitOfWork getLastUnitOfWork() {\n\t\treturn unitsOfWork.get(unitsOfWork.size()-1);\n\t}\n\n public List<UnitOfWork> getPendingOfPersistence() {\n return Lists.newLinkedList(Sets.difference(Sets.newLinkedHashSet(unitsOfWork), persisted));\n }\n\n public void markAsPersisted(UnitOfWork uow) {\n checkArgument(unitsOfWork.contains(uow), \"unitOfWork must be part of this AggregateRootHistory in order to be marked as persisted\");\n persisted.add(uow);\n }\n\n}", "@SuppressWarnings(\"serial\")\n@Value\npublic class Snapshot<A extends AggregateRoot> implements Serializable {\n\t\n\tprivate A aggregateInstance;\n\tprivate Long version;\n\n}", "@SuppressWarnings(\"serial\")\n@Value\npublic class UnitOfWork implements Comparable<UnitOfWork>, Serializable {\n\n final UUID id;\n\tfinal Command command;\n\tfinal List<? extends Event> events;\n\tfinal long version;\n\t\n\tpublic UnitOfWork(UUID id, Command command, Long version, List<? extends Event> events) {\n\t checkNotNull(id, \"id cannot be null\");\n\t checkNotNull(command, \"command cannot be null\");\n\t\tcheckArgument(command.getTargetVersion()>=0, \"target version must be >= 0\");\n\t\tcheckArgument(version>0, \"invalid version\");\n\t\tcheckNotNull(events, \"events cannot be null\");\n\t\tfor (Event e: events){\n\t\t\tcheckNotNull(e, \"event within events list cannot be null\");\n\t\t}\n\t\tthis.id = id;\n\t\tthis.command = command;\n\t\tthis.version = version;\n\t\tthis.events = events;\n\t}\n\t\n\tpublic static UnitOfWork create(UUID id, Command command, List<? extends Event> newEvents) {\n\t\tcheckNotNull(command.getTargetVersion(), \"target version cannot be null\");\n\t\tcheckArgument(command.getTargetVersion()>=0, \"target version must be >= 0\");\n\t\treturn new UnitOfWork(id, command, command.getTargetVersion()+1, newEvents);\n\t}\n\t\n\tpublic List<Event> getEvents(){\n\t\tList<Event> result = new LinkedList<>();\n\t\tfor (Event event : events) {\n\t\t\tresult.add(event);\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic int compareTo(UnitOfWork other) {\n\t\tif (version < other.version) {\n\t\t\treturn -1;\n\t\t} else if (version > other.version) {\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tpublic Long getTargetVersion() {\n\t\treturn command.getTargetVersion();\n\t}\n}", "@Value\npublic static class IncreaseInventory implements Command {\n @NonNull\n UUID commandId;\n @NonNull\n UUID id;\n @NonNull\n Integer howMany;\n Long targetVersion;\n}", "@Value\npublic static class InventoryIncreased implements Event {\n @NonNull\n UUID id;\n @NonNull\n Integer howMany;\n}", "@Data\npublic static class InventoryItemAggregateRoot implements AggregateRoot {\n\n UUID id;\n String description;\n Integer available = 0;\n\n public void on(InventoryItemCreated event) {\n this.id = event.id;\n this.description = event.description;\n this.available = 0;\n }\n\n public void on(InventoryIncreased event) {\n this.available = this.available + event.howMany;\n }\n\n public void on(InventoryDecreased event) {\n this.available = this.available - event.howMany;\n }\n \n public boolean isAvailable(int howMany) {\n return getAvailable() - howMany >= 0;\n }\n\n}" ]
import static org.junit.Assert.assertEquals; import java.lang.reflect.Type; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.AggregateRootHistory; import org.myeslib.core.data.Snapshot; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.example.SampleDomain.InventoryItemAggregateRoot; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;
package org.myeslib.example; public class SampleDomainGsonFactoryTest { final Gson gson = new SampleDomainGsonFactory().create(); @Test public void aggregateRootHistory() { UUID id = UUID.randomUUID(); UUID uowId1 = UUID.randomUUID(); UUID uowId2 = UUID.randomUUID(); Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0L); Event event11 = new InventoryIncreased(id, 1); Event event12 = new InventoryIncreased(id, 1); UnitOfWork uow1 = UnitOfWork.create(uowId1, command1, Arrays.asList(event11, event12)); Command command2 = new IncreaseInventory(UUID.randomUUID(), id, 10, 0L); Event event21 = new InventoryIncreased(id, 1); Event event22 = new InventoryIncreased(id, 1); UnitOfWork uow2 = UnitOfWork.create(uowId2, command2, Arrays.asList(event21, event22));
AggregateRootHistory arh = new AggregateRootHistory();
2
bafomdad/realfilingcabinet
com/bafomdad/realfilingcabinet/crafting/FolderStorageRecipe.java
[ "@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 interface IEmptyFolder {\n\n}", "public interface IFilingCabinet extends ITileEntityProvider {\n\n\tpublic void leftClick(TileEntity tile, EntityPlayer player);\n\t\n\tpublic void rightClick(TileEntity tile, EntityPlayer player, EnumFacing side, float hitX, float hity, float hitZ);\n}", "public interface IFolder {\n\t\n\tpublic ItemStack isFolderEmpty(ItemStack stack);\n}", "public class RFCBlocks {\n\n\tpublic static BlockRFC blockRFC;\n\tpublic static BlockAC blockAC;\n\t\n\tpublic static void init() {\n\t\t\n\t\tblockRFC = new BlockRFC();\n\t\tif (RealFilingCabinet.tcLoaded && ConfigRFC.tcIntegration)\n\t\t\tblockAC = new BlockAC();\n\t}\n\t\n\t@SideOnly(Side.CLIENT)\n\tpublic static void initModels() {\n\n\t\tClientRegistry.bindTileEntitySpecialRenderer(TileEntityRFC.class, new RenderFilingCabinet());\n\t\tif (RealFilingCabinet.botaniaLoaded && ConfigRFC.botaniaIntegration)\n\t\t\tClientRegistry.bindTileEntitySpecialRenderer(TileManaCabinet.class, new RenderManaCabinet());\n\t\tif (RealFilingCabinet.tcLoaded && ConfigRFC.tcIntegration)\n\t\t\tClientRegistry.bindTileEntitySpecialRenderer(TileEntityAC.class, new RenderAspectCabinet());\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 ItemDyedFolder extends Item implements IFolder {\n\t\n\tpublic ItemDyedFolder() {\n\t\t\n\t\tsetRegistryName(\"dyedfolder\");\n\t\tsetTranslationKey(RealFilingCabinet.MOD_ID + \".dyedfolder\");\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() + \".\" + EnumDyeColor.values()[stack.getItemDamage()].getName().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))\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).addTooltips(player, list, whatisthis);\n\t\tlist.add(\"Limit: \" + ConfigRFC.folderSizeLimit);\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\tItemFolder.remove(copy, extract);\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 int add(ItemStack stack, long count) {\n\t\t\n\t\tif (!(stack.getItem() instanceof ItemDyedFolder)) {\n\t\t\tItemFolder.add(stack, count);\n\t\t\treturn Integer.MAX_VALUE;\n\t\t}\n\t\tlong current = ItemFolder.getFileSize(stack);\n\t\tlong newCount = Math.min(count + current, ConfigRFC.folderSizeLimit);\n\t\tlong remainder = ConfigRFC.folderSizeLimit - ItemFolder.getFileSize(stack);\n\t\tItemFolder.setFileSize(stack, newCount);\n\t\t\n\t\treturn (int)remainder;\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 (ItemFolder.getObject(stack) != null) {\n\t\t\tif (((ItemStack)ItemFolder.getObject(stack)).getItem() instanceof ItemBlock) {\t\n\t\t\t\tlong count = ItemFolder.getFileSize(stack);\n\t\t\t\t\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tItemStack stackToPlace = new ItemStack(((ItemStack)ItemFolder.getObject(stack)).getItem(), 1, ((ItemStack)ItemFolder.getObject(stack)).getItemDamage());\n\t\t\t\t\tItemStack savedfolder = player.getHeldItem(hand);\n\t\t\t\t\t\n\t\t\t\t\tplayer.setHeldItem(hand, stackToPlace);\n\t\t\t\t\tEnumActionResult ear = stackToPlace.onItemUse(player, world, pos, hand, side, hitX, hitY, hitZ);\n\t\t\t\t\tplayer.setHeldItem(hand, savedfolder);\n\t\t\t\t\t\n\t\t\t\t\tif (ear == EnumActionResult.SUCCESS) {\n\t\t\t\t\t\tif (!player.capabilities.isCreativeMode) {\n\t\t\t\t\t\t\tItemFolder.remove(stack, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn EnumActionResult.SUCCESS;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn EnumActionResult.PASS;\n\t}\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\n\t@Override\n\tpublic ItemStack isFolderEmpty(ItemStack stack) {\n\n\t\treturn new ItemStack(RFCItems.emptyDyedFolder, 1, stack.getItemDamage());\n\t}\n}", "public enum FolderType {\n\tNORMAL,\n\tDURA,\n\tMOB,\n\tFLUID,\n\tNBT;\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}" ]
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapelessRecipes; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import com.bafomdad.realfilingcabinet.RealFilingCabinet; import com.bafomdad.realfilingcabinet.api.IEmptyFolder; import com.bafomdad.realfilingcabinet.api.IFilingCabinet; import com.bafomdad.realfilingcabinet.api.IFolder; import com.bafomdad.realfilingcabinet.init.RFCBlocks; import com.bafomdad.realfilingcabinet.init.RFCItems; import com.bafomdad.realfilingcabinet.items.ItemDyedFolder; import com.bafomdad.realfilingcabinet.items.ItemEmptyFolder.FolderType; import com.bafomdad.realfilingcabinet.items.ItemFolder;
package com.bafomdad.realfilingcabinet.crafting; public class FolderStorageRecipe extends net.minecraftforge.registries.IForgeRegistryEntry.Impl<IRecipe> implements IRecipe { private ItemStack output; final String name; private ItemStack input; public FolderStorageRecipe(String name, ItemStack output, ItemStack input) { this.output = output; this.input = input; this.name = name; this.setRegistryName(new ResourceLocation(RealFilingCabinet.MOD_ID, name)); } @Override public boolean matches(InventoryCrafting ic, World world) { List<ItemStack> list = new ArrayList(); list.add(input); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { ItemStack stack = ic.getStackInRowAndColumn(j, i); if (!stack.isEmpty()) { if (allowableIngredient(stack)) list.add(stack); boolean flag = false; Iterator iter = list.iterator(); while (iter.hasNext()) { ItemStack stack1 = (ItemStack)iter.next(); if (stack.getItem() == stack1.getItem() && (stack1.getItemDamage() == 32767 || stack.getItemDamage() == stack1.getItemDamage())) { flag = true; list.remove(stack1); break; } } if (!flag) { return false; } } } } return list.isEmpty(); } @Override public ItemStack getCraftingResult(InventoryCrafting ic) { int emptyFolder = -1; int recipestack = -1; for (int i = 0; i < ic.getSizeInventory(); i++) { ItemStack stack = ic.getStackInSlot(i); if (!stack.isEmpty()) { if (stack.getItem() instanceof IEmptyFolder || stack.getItem() == RFCItems.autoFolder) emptyFolder = i; else recipestack = i; } } if (emptyFolder >= 0 && recipestack >= 0) { ItemStack stack1 = ic.getStackInSlot(recipestack); ItemStack folder = ic.getStackInSlot(emptyFolder); if (folder.getItem() == RFCItems.emptyDyedFolder) { ItemStack newFolder = new ItemStack(RFCItems.dyedFolder, 1, folder.getItemDamage());
ItemFolder.setObject(newFolder, stack1);
8
mkovatsc/iot-semantics
semantic-ide/src/main/java/ch/ethz/inf/vs/semantics/ide/rest/QueryResource.java
[ "public class N3Linter {\n\n\tpublic static ArrayList<SemanticsErrors> lint(String input) {\n\t\tArrayList<SemanticsErrors> errors = new ArrayList<SemanticsErrors>();\n\t\tN3Lexer nl = new N3Lexer(new ANTLRInputStream(input));\n\t\tCommonTokenStream ts = new CommonTokenStream(nl);\n\t\tN3Parser np = new N3Parser(ts);\n\t\tnp.addErrorListener(new ANTLRErrorListener() {\n\t\t\t@Override\n\t\t\tpublic void syntaxError(@NotNull Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, @NotNull String msg, RecognitionException e) {\n\t\t\t\terrors.add(new SemanticsErrors(line, charPositionInLine, msg));\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reportAmbiguity(@NotNull Parser recognizer, @NotNull DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, @NotNull ATNConfigSet configs) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reportAttemptingFullContext(@NotNull Parser recognizer, @NotNull DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, @NotNull ATNConfigSet configs) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reportContextSensitivity(@NotNull Parser recognizer, @NotNull DFA dfa, int startIndex, int stopIndex, int prediction, @NotNull ATNConfigSet configs) {\n\n\t\t\t}\n\t\t});\n\t\tnp.n3Doc();\n\t\treturn errors;\n\t}\n\n}", "public class Query {\n\tprivate int id;\n\tprivate boolean watch;\n\tprivate String name;\n\tprivate String input;\n\tprivate String query;\n\n\tpublic String getInput() {\n\t\treturn input;\n\t}\n\n\tpublic void setInput(String input) {\n\t\tthis.input = input;\n\t}\n\n\tpublic String getQuery() {\n\t\treturn query;\n\t}\n\n\tpublic void setQuery(String query) {\n\t\tthis.query = query;\n\t}\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 boolean isWatch() {\n\t\treturn watch;\n\t}\n\n\tpublic void setWatch(boolean watch) {\n\t\tthis.watch = watch;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n}", "public class QueryResult {\n\n\tprivate String result;\n\tprivate ArrayList<SemanticsErrors> errquery;\n\tprivate ArrayList<SemanticsErrors> errinput;\n\n\tpublic QueryResult() {\n\n\t}\n\n\tpublic QueryResult(String result, ArrayList<SemanticsErrors> errquery, ArrayList<SemanticsErrors> errinput) {\n\n\t\tthis.setResult(result);\n\t\tthis.setErrquery(errquery);\n\t\tthis.setErrinput(errinput);\n\t}\n\n\tpublic String getResult() {\n\t\treturn result;\n\t}\n\n\tpublic void setResult(String result) {\n\t\tthis.result = result;\n\t}\n\n\tpublic ArrayList<SemanticsErrors> getErrquery() {\n\t\treturn errquery;\n\t}\n\n\tpublic void setErrquery(ArrayList<SemanticsErrors> errquery) {\n\t\tthis.errquery = errquery;\n\t}\n\n\tpublic ArrayList<SemanticsErrors> getErrinput() {\n\t\treturn errinput;\n\t}\n\n\tpublic void setErrinput(ArrayList<SemanticsErrors> errinput) {\n\t\tthis.errinput = errinput;\n\t}\n}", "public class SemanticsErrors {\n\n\tprivate int line;\n\tprivate int charPositionInLine;\n\tprivate String msg;\n\n\tpublic SemanticsErrors() {\n\n\t}\n\n\tpublic SemanticsErrors(int line, int charPositionInLine, String msg) {\n\n\t\tthis.setLine(line);\n\t\tthis.setCharPositionInLine(charPositionInLine);\n\t\tthis.setMsg(msg);\n\t}\n\n\tpublic int getLine() {\n\t\treturn line;\n\t}\n\n\tpublic void setLine(int line) {\n\t\tthis.line = line;\n\t}\n\n\tpublic int getCharPositionInLine() {\n\t\treturn charPositionInLine;\n\t}\n\n\tpublic void setCharPositionInLine(int charPositionInLine) {\n\t\tthis.charPositionInLine = charPositionInLine;\n\t}\n\n\tpublic String getMsg() {\n\t\treturn msg;\n\t}\n\n\tpublic void setMsg(String msg) {\n\t\tthis.msg = msg;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"line \" + line + \":\" + charPositionInLine + \" \" + msg;\n\t}\n}", "public abstract class Workspace {\n\n\tprotected int id;\n\n\tHashMap<Integer, Query> queries = new HashMap<>();\n\n\tpublic abstract Device deleteDevice(int id);\n\n\tpublic abstract Device addDevice(Device msg);\n\n\tpublic abstract Collection<Device> getDevices();\n\n\tpublic abstract Device getDevice(int id);\n\n\tpublic abstract Device updateDevice(int id, Device msg);\n\n\tpublic abstract String executeQuery(String goal, String input, boolean raw) throws Exception;\n\n\tpublic abstract void clearAnswers();\n\n\tpublic Query addQuery(Query msg) {\n\n\t\tmsg.setId(queries.keySet().stream().reduce(0, Integer::max) + 1);\n\t\tqueries.put(msg.getId(), msg);\n\t\treturn msg;\n\t}\n\n\tpublic Collection<Query> getQueries() {\n\t\treturn queries.values();\n\t}\n\n\tpublic Query getQuery(int id) {\n\t\treturn queries.get(id);\n\t}\n\n\tpublic Query deleteQuery(int id) {\n\t\treturn queries.remove(id);\n\t}\n\n\tpublic Query updateQuery(int id, Query msg) {\n\n\t\tQuery d = queries.get(id);\n\t\td.setName(msg.getName());\n\t\td.setWatch(msg.isWatch());\n\t\td.setInput(msg.getInput());\n\t\td.setQuery(msg.getQuery());\n\t\treturn d;\n\t}\n\n\tpublic abstract Collection<String> getHints();\n\n\tpublic abstract String planMashup(String query, String input) throws Exception;\n\n\tpublic abstract void addAnswer(String n3Document);\n\n\tpublic abstract Backup loadBackup(Backup backup);\n\n\tpublic Backup getBackup() {\n\n\t\tBackup backup = new Backup();\n\t\tbackup.setDevices(getDevices());\n\t\tbackup.setQueries(getQueries());\n\t\treturn backup;\n\t}\n\n\tpublic abstract WorkspaceInfo getWorkspaceInfo();\n\n\tpublic abstract void setName(String name);\n\n\tpublic abstract void save();\n\n\tpublic void remove() {\n\t\ttry {\n\t\t\tgetFile().delete();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic File getFile() throws IOException {\n\t\tFile file = new File(WorkspaceManager.getFolder(), \"workspace\"+id+\".json\");\n\t\tif (!file.exists()) {\n\t\t\tfile.createNewFile();\n\t\t}\n\t\treturn file;\n\t}\n}", "public class WorkspaceManager {\n\tprivate static volatile WorkspaceManager instance = null;\n\tprivate static File persistenceFolder;\n\tprivate static Object lock = new Object();\n\tprivate Map<Integer, Workspace> workspaces;\n\tprivate int ID;\n\n\tprivate WorkspaceManager() {\n\t\tworkspaces = new HashMap<>();\n\t\tID = 1;\n\t\tfor (File ws : getFolder().listFiles()) {\n\t\t\tObjectMapper mapper = new ObjectMapper(); // can reuse, share globally\n\t\t\ttry {\n\t\t\t\tWorkspaceInfo workspaceinfo = mapper.readValue(ws, WorkspaceInfo.class);\n\t\t\t\tcreateWorkspace(workspaceinfo);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static WorkspaceManager getInstance() {\n\t\tif (instance == null) {\n\t\t\tsynchronized (WorkspaceManager.class) {\n\t\t\t\tif (instance == null) {\n\t\t\t\t\tinstance = new WorkspaceManager();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic static File getFolder() {\n\t\tif (persistenceFolder==null) {\n\t\t\tsynchronized (lock) {\n\t\t\t\tif (persistenceFolder==null) {\n\t\t\t\t\tpersistenceFolder = new File(\"workspaces\");\n\t\t\t\t\tif (!persistenceFolder.exists()) {\n\t\t\t\t\t\tpersistenceFolder.mkdir();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn persistenceFolder;\n\t}\n\n\tpublic Workspace getWorkspace(int id) {\n\t\treturn workspaces.get(id);\n\t}\n\n\tpublic static Workspace get(int workspace) {\n\t\treturn getInstance().getWorkspace(workspace);\n\t}\n\n\tpublic static Collection<WorkspaceInfo> getWorkspaces() {\n\t\tArrayList<WorkspaceInfo> workspaces = new ArrayList<>();\n\t\tfor (Workspace w : getInstance().workspaces.values()) {\n\t\t\tworkspaces.add(w.getWorkspaceInfo());\n\t\t}\n\t\treturn workspaces;\n\t}\n\n\tpublic WorkspaceInfo deleteWorkspace(int id) {\n\t\tWorkspace workspace = get(id);\n\t\tWorkspaceInfo ws = workspace.getWorkspaceInfo();\n\t\tworkspaces.remove(id);\n\t\tworkspace.remove();\n\t\treturn ws;\n\t}\n\n\tpublic WorkspaceInfo createWorkspace(WorkspaceInfo ws) {\n\t\tsynchronized (this) {\n\t\t\tint id;\n\t\t\tif (!workspaces.containsKey(ws.getId()) && ws.getId()!=0) {\n\t\t\t\tid = ws.getId();\n\t\t\t\tID = Math.max(ID, id + 1);\n\t\t\t} else {\n\t\t\t\tid = ID;\n\t\t\t\tID++;\n\t\t\t}\n\t\t\tWorkspace workspace;\n\t\t\tif (\"remote\".equals(ws.getType())) {\n\n\t\t\t\tworkspace = new RemoteWorkspace(id, ws.getName(), ws.getUrl());\n\t\t\t} else {\n\n\t\t\t\tworkspace = new VirtualWorkspace(id, ws.getName());\n\t\t\t}\n\t\t\tworkspaces.put(id, workspace);\n\t\t\tif (ws.getBackup()!=null) {\n\t\t\t\tworkspace.loadBackup(ws.getBackup());\n\t\t\t}\n\t\t\tworkspace.save();\n\t\t\treturn workspace.getWorkspaceInfo();\n\t\t}\n\t}\n}" ]
import ch.ethz.inf.vs.semantics.ide.domain.N3Linter; import ch.ethz.inf.vs.semantics.ide.domain.Query; import ch.ethz.inf.vs.semantics.ide.domain.QueryResult; import ch.ethz.inf.vs.semantics.ide.domain.SemanticsErrors; import ch.ethz.inf.vs.semantics.ide.workspace.Workspace; import ch.ethz.inf.vs.semantics.ide.workspace.WorkspaceManager; import restx.annotations.*; import restx.factory.Component; import restx.security.PermitAll; import java.util.ArrayList; import java.util.Collection;
package ch.ethz.inf.vs.semantics.ide.rest; @Component @RestxResource public class QueryResource { @POST("/{workspace}/queries") @PermitAll public static Query postQuery(int workspace, Query msg) { Workspace ws = WorkspaceManager.get(workspace); Query query = ws.addQuery(msg); ws.save(); return query; } @GET("/{workspace}/queries") @PermitAll public Collection<Query> queries(int workspace) { return WorkspaceManager.get(workspace).getQueries(); } @GET("/{workspace}/queries/{id}") @PermitAll public Query getQuery(int workspace, int id) { return WorkspaceManager.get(workspace).getQuery(id); } @DELETE("/{workspace}/queries/{id}") @PermitAll public Query deleteQuery(int workspace, int id) { Workspace ws = WorkspaceManager.get(workspace); Query query = ws.deleteQuery(id); ws.save(); return query; } @PUT("/{workspace}/queries/{id}") @PermitAll public Query putQuery(int workspace, int id, Query msg ) { Workspace ws = WorkspaceManager.get(workspace); Query query = ws.updateQuery(id, msg); ws.save(); return query; } @GET("/{workspace}/hints") @PermitAll public Collection<String> hints(int workspace) { return WorkspaceManager.get(workspace).getHints(); } @POST("/{workspace}/query/{raw}") @PermitAll
public QueryResult query(int workspace, Query query, boolean raw) {
2
ZonCon/Ecommerce-Retronight-Android
app/src/main/java/com/megotechnologies/ecommerce_retronight/push/NotificationService.java
[ "public class MainActivity extends Activity implements ZCActivityLifecycle, ZCRunnable {\n\n\tpublic static Boolean LOG = true;\n\n\t// Project\n\t\n\tpublic static String PID = \"14\";\n\t\n\t// API\n\t\n\tpublic static String API = \"http://www.zoncon.com/v6_1/index.php/projects/\";\n\tpublic static String API_STREAMS = API + \"get_public_streams\";\n\tpublic static String API_INDI_STREAMS = API + \"get_public_individual_stream\";\n\tpublic static String API_NOTIFICATIONS = API + \"get_public_notification\";\n\tpublic static String API_COUNTRIES = API + \"get_public_countries\";\n\tpublic static String API_STATES = API + \"get_public_states\";\n\tpublic static String API_CITIES = API + \"get_public_cities\";\n\tpublic static String API_CART = API + \"get_public_cart\";\n\tpublic static String API_USER_APPS = API + \"get_public_user_apps\";\n\tpublic static String API_CREATE_ACCOUNT = API + \"add_public_consumer\";\n\tpublic static String API_RESET_PASSWORD = API + \"public_consumer_password_reset\";\n\tpublic static String API_FORGOT_CHANGE_PASSWORD = API + \"public_consumer_forgot_change_password\";\n\tpublic static String API_LOGIN = API + \"public_consumer_login\";\n\tpublic static String API_ORDER_NEW = API + \"public_new_order\";\n\tpublic static String API_ORDER_CONFIRM = API + \"public_confirm_order_payment\";\n\tpublic static String API_ORDER_CANCEL = API + \"public_cancel_order_payment\";\n\tpublic static String API_VALIDATE_LOC = API + \"public_validate_location\";\n\tpublic static String API_VERIFY_LOGIN = API + \"public_verify_login\";\n\tpublic static String API_ORDERS_LIST = API + \"public_orders_get\";\n\tpublic static String API_COUPON_VALIDATE = API + \"public_coupon_validate\";\n\tpublic static String API_ORDERS_SINGLE = API + \"public_orders_get_single\";\n\tpublic static String UPLOADS = \"http://www.zoncon.com/v6_1/uploads\";\n\tpublic static String PG_IFRAME_URL = \"\";\n\tpublic static String PG_REDIRECT_URL = \"\";\n\tpublic static String PG_MERCHANT_ID = \"\";\n\n\t// Fonts\n\n\n\tpublic static char FONT_CHAR_URL = 0xe70a;\n\tpublic static char FONT_CHAR_CONTACT = 0xe708;\n\tpublic static char FONT_CHAR_LOCATION = 0xe706;\n\tpublic static char FONT_CHAR_ATTACHMENT = 0xe70b;\n\tpublic static char FONT_CHAR_CLOSE = 0xe701;\n\tpublic static char FONT_CHAR_SHARE = 0xe713;\n\tpublic static char FONT_CHAR_LIKED = 0xe71c;\n\n\t// Payment Gateway\n\t\n\tpublic static String PG_ACCESS_CODE = \"AVUO02BI71CK19OUKC\";\n\tpublic static String PG_CURRENCY = \"INR\";\n\n\t// Maps\n\n\tpublic static String MAPS_PREFIX = \"http://maps.google.com/?q=\";\n\n\t// External Storage\n\n\tpublic static String STORAGE_PATH = \"\";\n\n\t// Screen\n\n\tpublic static int SCREEN_WIDTH;\n\tpublic static int SCREEN_HEIGHT;\n\tpublic static int SPACING = 20;\n\n\t// Pictures\n\n\tpublic static int IMG_TH_MAX_SIZE = 200;\n\tpublic static int IMG_DETAIL_MAX_SIZE = 800;\n\n\t// Symbols\n\t\n\tpublic static String SYMBOL_RUPEE = \"INR\";\n\t\n\t// Text size\n\t\n\tpublic static char TEXT_SIZE_TILE = 12;\n\tpublic static char TEXT_SIZE_BUTTON = 17;\n\tpublic static char TEXT_SIZE_TITLE = 16;\n\t\n\t// DB\n\t\n\tpublic static String DB_TABLE = \"records\";\n\tpublic static String DB_NAME = \"zoncon_ecommerce_retronight.db\";\n\tpublic static int DB_VERSION = 5;\n\t\n\t// DB Columns\n\t\n\tpublic static String DB_COL_ID = \"_id\";\n\tpublic static String DB_COL_SRV_ID = \"server_id\";\n\tpublic static String DB_COL_TYPE = \"type\";\n\tpublic static String DB_COL_TITLE = \"title\";\n\tpublic static String DB_COL_SUB = \"subtitle\";\n\tpublic static String DB_COL_CONTENT = \"content\";\n\tpublic static String DB_COL_TIMESTAMP = \"timestamp\";\n\tpublic static String DB_COL_STOCK = \"stock\";\n\tpublic static String DB_COL_PRICE = \"price\";\n\tpublic static String DB_COL_EXTRA_1 = \"extra1\";\n\tpublic static String DB_COL_EXTRA_2 = \"extra2\";\n\tpublic static String DB_COL_EXTRA_3 = \"extra3\";\n\tpublic static String DB_COL_EXTRA_4 = \"extra4\";\n\tpublic static String DB_COL_EXTRA_5 = \"extra5\";\n\tpublic static String DB_COL_EXTRA_6 = \"extra6\";\n\tpublic static String DB_COL_EXTRA_7 = \"extra7\";\n\tpublic static String DB_COL_EXTRA_8 = \"extra8\";\n\tpublic static String DB_COL_EXTRA_9 = \"extra9\";\n\tpublic static String DB_COL_EXTRA_10 = \"extra10\";\n\tpublic static String DB_COL_BOOKING = \"bookingPrice\";\n\tpublic static String DB_COL_DISCOUNT = \"discount\";\n\tpublic static String DB_COL_SKU = \"sku\";\n\tpublic static String DB_COL_SIZE = \"size\";\n\tpublic static String DB_COL_WEIGHT = \"weight\";\n\tpublic static String DB_COL_NAME = \"name\";\n\tpublic static String DB_COL_CAPTION = \"caption\";\n\tpublic static String DB_COL_URL = \"url\";\n\tpublic static String DB_COL_LOCATION = \"location\";\n\tpublic static String DB_COL_EMAIL = \"email\";\n\tpublic static String DB_COL_PHONE = \"phone\";\n\tpublic static String DB_COL_PATH_ORIG = \"path_original\";\n\tpublic static String DB_COL_PATH_PROC = \"path_processed\";\n\tpublic static String DB_COL_PATH_TH = \"path_thumbnail\";\n\tpublic static String DB_COL_CART_ITEM_STREAM_SRV_ID = \"cart_item_stream_server_id\";\n\tpublic static String DB_COL_CART_ITEM_SRV_ID = \"cart_item_server_id\";\n\tpublic static String DB_COL_CART_ITEM_QUANTITY = \"cart_item_quantity\";\n\tpublic static String DB_COL_CART_COUPON_CODE = \"cart_coupon_code\";\n\tpublic static String DB_COL_CART_CART_ISOPEN = \"cart_isopen\";\n\tpublic static String DB_COL_FOREIGN_KEY = \"foreign_key\";\n\tpublic static String[] DB_ALL_COL = {DB_COL_ID, DB_COL_SRV_ID, DB_COL_TYPE, DB_COL_TITLE, DB_COL_SUB, DB_COL_CONTENT, DB_COL_TIMESTAMP, DB_COL_STOCK, DB_COL_PRICE, DB_COL_EXTRA_1, DB_COL_EXTRA_2, DB_COL_EXTRA_3, DB_COL_EXTRA_4, DB_COL_EXTRA_5, DB_COL_EXTRA_6, DB_COL_EXTRA_7, DB_COL_EXTRA_8, DB_COL_EXTRA_9, DB_COL_EXTRA_10, DB_COL_BOOKING, DB_COL_DISCOUNT, DB_COL_SKU, DB_COL_SIZE, DB_COL_WEIGHT, DB_COL_NAME, DB_COL_CAPTION, DB_COL_URL, DB_COL_LOCATION, DB_COL_EMAIL, DB_COL_PHONE, DB_COL_PATH_ORIG, DB_COL_PATH_PROC, DB_COL_PATH_TH, DB_COL_CART_ITEM_STREAM_SRV_ID, DB_COL_CART_ITEM_SRV_ID, DB_COL_CART_ITEM_QUANTITY, DB_COL_CART_COUPON_CODE, DB_COL_CART_CART_ISOPEN, DB_COL_FOREIGN_KEY};\n\t\n\t// DB Record Types\n\t\n\tpublic static String DB_RECORD_TYPE_STREAM = \"RECORD_STREAM\";\n\tpublic static String DB_RECORD_TYPE_ITEM = \"RECORD_ITEM\";\n\tpublic static String DB_RECORD_TYPE_PICTURE = \"RECORD_PICTURE\";\n\tpublic static String DB_RECORD_TYPE_ATTACHMENT = \"RECORD_ATTACHMENT\";\n\tpublic static String DB_RECORD_TYPE_URL = \"RECORD_URL\";\n\tpublic static String DB_RECORD_TYPE_LOCATION = \"RECORD_LOCATION\";\n\tpublic static String DB_RECORD_TYPE_CONTACT = \"RECORD_CONTACT\";\n\tpublic static String DB_RECORD_TYPE_CART = \"RECORD_CART\";\n\tpublic static String DB_RECORD_TYPE_CART_ITEM = \"RECORD_CART_ITEM\";\n\tpublic static String DB_RECORD_TYPE_MY_COUNTRY = \"RECORD_MY_COUNTRY\";\n\tpublic static String DB_RECORD_TYPE_MY_STATE = \"RECORD_MY_STATE\";\n\tpublic static String DB_RECORD_TYPE_MY_CITY = \"RECORD_MY_CITY\";\n\tpublic static String DB_RECORD_TYPE_MY_PHONE = \"RECORD_MY_PHONE\";\n\tpublic static String DB_RECORD_TYPE_MY_NAME = \"RECORD_MY_NAME\";\n\tpublic static String DB_RECORD_TYPE_MY_ADDRESS = \"RECORD_MY_ADDRESS\";\n\tpublic static String DB_RECORD_TYPE_MY_PINCODE = \"RECORD_MY_PINCODE\";\n\tpublic static String DB_RECORD_TYPE_NOTIF = \"RECORD_NOTIF\";\n\tpublic static String DB_RECORD_TYPE_DISCOUNT = \"RECORD_DISCOUNT\";\n\tpublic static String DB_RECORD_TYPE_COUPON = \"RECORD_COUPON\";\n\tpublic static String DB_RECORD_TYPE_TAX_1 = \"RECORD_TAX_1\";\n\tpublic static String DB_RECORD_TYPE_TAX_2 = \"RECORD_TAX_2\";\n\tpublic static String DB_RECORD_TYPE_MESSAGESTREAM_PUSH = \"MESSAGE_PUSH\";\n\tpublic static String DB_RECORD_VALUE_CART_OPEN = \"yes\";\n\tpublic static String DB_RECORD_VALUE_CART_CLOSED = \"no\";\n\tpublic static String DB_DISCOUNT_TYPE_FLAT = \"FLAT\";\n\tpublic static String DB_DISCOUNT_TYPE_PERCENTAGE = \"PERCENTAGE\";\n\t\n\n\t// Threads\n\t\n\tpublic static String TH_NAME_LOCATIONS_COUNTRIES = \"countries\";\n\tpublic static String TH_NAME_LOCATIONS_STATES = \"states\";\n\tpublic static String TH_NAME_LOCATIONS_CITIES = \"cities\";\n\tpublic static String TH_NAME_CART = \"cart\";\n\tpublic static String TH_NAME_ORDER = \"order\";\n\tpublic static String TH_NAME_ACCOUNT_CREATE = \"account\";\n\tpublic static String TH_NAME_APPS_USING = \"appsusing\";\n\tpublic static String TH_NAME_PASSWORD_RESET = \"password_reset\";\n\tpublic static String TH_NAME_PASSWORD_CHANGE = \"password_change\";\n\tpublic static String TH_NAME_LOGIN = \"login\";\n\tpublic static String TH_NAME_CONFIRM_ORDER = \"confirmorder\";\n\tpublic static String TH_NAME_CANCEL_ORDER = \"cancelorder\";\n\tpublic static String TH_NAME_VERIFY_LOGIN = \"verify_login\";\n\tpublic static String TH_NAME_ORDERS_GET = \"get_orders\";\n\tpublic static String TH_NAME_LOAD_MORE = \"load_more\";\n\tpublic static String TH_NAME_LOAD_MORE_CHECKER = \"load_more_checker\";\n\tpublic static String TH_NAME_VALIDATE_COUPON = \"validate_coupon\";\n\t\n\t// Thread Constants\n\t\n\tpublic static String TH_STATE_TERM = \"TERMINATED\";\n\tpublic static int TH_CHECKER_DURATION = 200;\n\tpublic static int TH_SPLASH_MIN_DURATION = 3000;\n\t\n\t// Messages\n\n\tpublic static String MSG_ORDERS_NOITEMS = \"You haven't completed any orders yet!\";\n\tpublic static String MSG_ORDERS_END = \"No more orders!\";\n\tpublic static String MSG_CART_NOITEMS = \"Cart is empty!\";\n\tpublic static String MSG_CART_CONFIRM_REMOVE = \"Are you sure you want to remove this item from the cart?\";\n\tpublic static String MSG_CART_EXPIRED = \"Cart has expired!\";\n\tpublic static String MSG_CART_ITEM_LIMIT = \"Maximum quantity limit for this item has been reached!\";\n\tpublic static String MSG_CART_DISCONNECTED = \"Cart cannot be accessed offline. Please check your Internet connection!\";\n\tpublic static String MSG_COUPON_INVALID_LOCATION = \"This coupon is not available at your location!\";\n\tpublic static String MSG_COUPON_INVALID = \"Coupon is invalid!\";\n\tpublic static String MSG_COUPON_BOOKING_INVALID = \"Coupon cannot be applied for items with booking amounts!\";\n\tpublic static String MSG_COUPON_DOUBLE_NOT_ALLOWED = \"This coupon can only be applied to non-discounted items!\";\n\tpublic static String MSG_COUPON_MIN_PURCHASE_LIMIT = \"This coupon is applicable for purchases above INR \";\n\tpublic static String MSG_DISCONNECTED = \"Cannot be accessed offline. Please check your Internet connection!\";\n\tpublic static String MSG_ORDERS_DISCONNECTED = \"Orders cannot be accessed offline. Please check your Internet connection!\";\n\tpublic static String MSG_LOCATIONS_DISCONNECTED = \"Locations cannot be accessed offline. Please check your Internet connection!\";\n\tpublic static String MSG_BLANK_FIELDS = \"No fields can be left blank!\";\n\tpublic static String MSG_CONFIRM = \"Are you sure?\";\n\tpublic static String MSG_PHONE_INVALID = \"Please provide a valid phone number!\";\n\tpublic static String MSG_PINCODE_INVALID = \"Please provide a valid pincode number!\";\n\tpublic static String MSG_PASSWORDS_NOT_MATCHING = \"Passwords are not matching!\";\n\tpublic static String MSG_PASSWORDS_CHANGE_SUCCESS = \"Password has been changed successfully!\";\n\tpublic static String MSG_PASSWORDS_CHANGE_FAILURE = \"Password could not be changed! Please verify credentials..\";\n\tpublic static String MSG_PASSWORDS_INVALID = \"New password is invalid!\";\n\tpublic static String MSG_ZONCON_PASSWORD_RESET_SUCCESS = \"Password has been reset successfully! Please login again\";\n\tpublic static String MSG_ZONCON_PASSWORD_RESET_ERROR = \"Either the code has expired or you have entered an incorrect email address!\";\n\tpublic static String MSG_ZONCON_ACCOUNT_NOT_EXISTS = \"Account for the given email does not exist!\";\n\tpublic static String MSG_ZONCON_ACCOUNT_SUCCESS = \"Account created successfully! Now please login with the same credentials.\";\n\tpublic static String MSG_ZONCON_ACCOUNT_DUPLICATE = \"Account already exists for this email address!\";\n\tpublic static String MSG_INVALID_EMAIL = \"Invalid Email Address!\";\n\tpublic static String MSG_INVALID_EMAIL_PASSWORD = \"Invalid Email Address or Password! Password should be minimum 8 characters\";\n\tpublic static String MSG_LOGIN_FAIL = \"Email Address or Password is incorrect!\";\n\tpublic static String MSG_ORDER_SUCCESS = \"Your order has been placed successfully! Thank you for shopping with us.\";\n\tpublic static String MSG_ORDER_FAILURE = \"Your order could not be placed! Please try again.\";\n\tpublic static String MSG_VERSION_UPDATE = \"Please update your app to the latest version from the Play Store! If you haven't yet received a software update, please wait for a few hours until it becomes available.\";\n\tpublic static String MSG_YES = \"Yes\";\n\tpublic static String MSG_NO = \"No\";\n\tpublic static String MSG_OK = \"OK\";\n\tpublic static String MSG_PRODUCT_NOT_AVAILABLE = \"This product is not available at your location!\";\n\n\t// Order Status\n\n\tpublic static String ORDER_PROCESSING = \"PROCESSING\";\n\tpublic static String ORDER_CANCELLED = \"CANCELLED\";\n\tpublic static String ORDER_COMPLETE = \"COMPLETE\";\n\n\t// Splash\n\n\tpublic static int SPLASH_DURATION = 3000;\n\n\t// Loading\n\n\tpublic static int LOADING_PIC_COUNT = 3;\n\n\n\t// Values\n\n\tpublic static int MAX_CART_QUANTITY = 100;\n\tpublic static String[] ITEMS_LIST = new String[]{\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"};\n\n\t// Cart\n\n\tpublic static long TIMEOUT_CART_CLEAR = 86400000;\n\n\t// Market\n\n\tpublic static String MARKET_URL_PREFIX_1 = \"market://details?id=\";\n\tpublic static String MARKET_URL_PREFIX_2 = \"http://play.google.com/store/apps/details?id=\";\n\n\t// Market\n\n\tpublic static String SHARE_SUBJECT = \"ZonCon ECommerce App\";\n\tpublic static String SHARE_CONTENT = \"Thank you for downoading the ZonCon Ecommerce mobile app!\";\n\n\t// Notifications\n\n\tpublic static int NOTIF_SLEEP_TIME = 300000;\n\n\t// Load More\n\n\tpublic static String LOAD_MORE_CAPTION = \"LOAD MORE\";\n\tpublic static String LOAD_MORE_CAPTION_LOADING = \"Loading...\";\n\tpublic static String LOAD_MORE_CAPTION_END = \"REACHED THE END\";\n\n\t// Body\n\n\tpublic static int BODY_TOP_MARGIN_DP = 70;\n\tpublic static int BODY_BOTTOM_MARGIN_DP = 0;\n\n\n\tpublic static String SHARE_ITEM_POSTFIX = \"Brought to you by ZonCon Ecommerce!\";\n\n\tpublic static String SCREEN_SHOP_CATEGORIES = \"ShopCategories\";\n\tpublic static String SCREEN_SHOP_ITEM_LIST = \"ShopItemList\";\n\tpublic static String SCREEN_SHOP_ITEM_DETAILS = \"ShopItemDetails\";\n\tpublic static String SCREEN_ABOUT_ITEM_LIST = \"AboutItemList\";\n\tpublic static String SCREEN_ABOUT_ITEM_DETAILS = \"AboutItemDetails\";\n\tpublic static String SCREEN_ALERT_ITEM_LIST = \"AlertItemList\";\n\tpublic static String SCREEN_ALERT_ITEM_DETAILS = \"AlertItemDetails\";\n\tpublic static String SCREEN_POLICY_ITEM_LIST = \"PolicyItemList\";\n\tpublic static String SCREEN_POLICY_ITEM_DETAILS = \"PolicyItemDetails\";\n\tpublic static String SCREEN_LOADING = \"Splash\";\n\tpublic static String SCREEN_LOCATION = \"Location\";\n\tpublic static String SCREEN_STREAMS = \"Stream\";\n\tpublic static String SCREEN_ACCOUNT = \"Account\";\n\tpublic static String SCREEN_CART = \"Cart\";\n\tpublic static String SCREEN_CREATE_ACCOUNT = \"CreateAccount\";\n\tpublic static String SCREEN_LOGIN_ACCOUNT = \"LoginAccount\";\n\tpublic static String SCREEN_FORGOT = \"Forgot\";\n\tpublic static String SCREEN_RESET = \"Reset\";\n\tpublic static String SCREEN_SHIPPING = \"Shipping\";\n\tpublic static String SCREEN_CHECKOUT = \"Checkout\";\n\tpublic static String SCREEN_CONFIRM = \"Confirm\";\n\tpublic static String SCREEN_PAYMENT = \"Payment\";\n\tpublic static String SCREEN_ORDER_LIST = \"Orderlist\";\n\tpublic static String SCREEN_ORDER_DETAILS = \"Orderdetails\";\n\n\tpublic static String STREAM_NAME_VERSIONS = \"Versions\";\n\n\tpublic static String TOKEN_KEY = \"token\";\n\tpublic static String EMAIL_KEY = \"email\";\n\tpublic static String MUSIC_KEY = \"music\";\n\n\tpublic static String DEEP_LINK = \"deeplink\";\n\tpublic static String DEEP_LINK_VALUE_CART = \"cart\";\n\tpublic static String DEEP_LINK_VALUE_ALERTS = \"alerts\";\n\tpublic static String DEEP_LINK_VALUE_ACCOUNT = \"account\";\n\tpublic static String DEEP_LINK_VALUE_PRODUCT_LIST = \"productlist\";\n\tpublic static String DEEP_LINK_VALUE_POLICIES = \"policies\";\n\tpublic static String DEEP_LINK_VALUE_DEV = \"dev\";\n\n\tpublic static String DEEP_LINK_PARAM = \"deeplinkparam\";\t\n\n\tpublic static int SOCKET_TIMEOUT = 20000;\n\tpublic static int HTTP_TIMEOUT = 20000;\n\n\n\tpublic static int NUM_INIT_STREAMS = 6;\n\n\tpublic static int MIN_PURCHASE_LIMIT = 500;\n\tpublic static int MAX_PURCHASE_LIMIT = 500000;\n\tpublic static String MIN_PURCHASE_LIMIT_ERROR = \"Minimum purchase limit is \" + MainActivity.SYMBOL_RUPEE + \" \" + MIN_PURCHASE_LIMIT;\n\tpublic static String MAX_PURCHASE_LIMIT_ERROR = \"Maximum purchase limit is \" + MainActivity.SYMBOL_RUPEE + \" \" + MAX_PURCHASE_LIMIT;\n\n\tpublic Boolean IS_CONNECTED = false;\n\n\tpublic static final String MyPREFERENCES = \"MyPrefs\" ;\n\n\tpublic ZonConApplication app;\n\n\tpublic static ProgressDialog pageLoad;\n\n\tpublic Context context;\n\tpublic SharedPreferences sharedPreferences;\n\tpublic DbConnection dbC;\n\tpublic FragmentManager fragMgr;\n\n\tprotected LinearLayout llHead;\n\tprotected ImageView ivHeadTitle, ivHeadMenu, ivHeadCart;\n\tprotected TextView tvCartNotif;\n\tprotected FrameLayout flBody;\n\n\tpublic Typeface tf;\n\n\tprotected Boolean RUN_FLAG = false;\n\tpublic Boolean IS_CLICKED = false;\n\tpublic Boolean IS_CLICKABLE_FRAME = true;\n\tpublic Boolean IS_CLICKABLE_FRAGMENT = true;\n\tpublic int CART_NOTIF_DURATION = 10000;\n\tpublic String myCountry = null, myState = null, myCity = null;\n\tpublic String myCountryId = null, myStateId = null, myCityId = null;\n\tpublic String lastCreatedActivity = null;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\trequestWindowFeature(Window.FEATURE_NO_TITLE); \n\t\tthis.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);\n\t\tsetContentView(R.layout.activity_main);\n\n\t\tsharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);\n\n\t\tDisplay display = getWindowManager().getDefaultDisplay();\n\t\tPoint size = new Point();\n\t\tif (android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {\n\t\t\t// call something for API Level 11+\n\n\t\t\ttry {\n\n\t\t\t\tdisplay.getSize(size);\n\t\t\t\tSCREEN_WIDTH = size.x;\n\t\t\t\tSCREEN_HEIGHT = size.y;\n\n\t\t\t} catch (java.lang.NoSuchMethodError ignore) { // Older device\n\t\t\t\tSCREEN_WIDTH = display.getWidth();\n\t\t\t\tSCREEN_HEIGHT = display.getHeight();\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tSCREEN_WIDTH = display.getWidth();\n\t\t\tSCREEN_HEIGHT = display.getHeight();\n\n\t\t}\n\n\t\tString packName = getApplicationContext().getPackageName();\n\t\tSTORAGE_PATH = Environment.getExternalStorageDirectory() + \"/\" + packName;\n\t\tFile dir = new File(STORAGE_PATH);\n\t\tif (!dir.exists()) {\n\t\t\tdir.mkdir();\n\t\t}\n\n\t\tstoreContext();\n\t\tstoreClassVariables();\n\t\tinitUIHandles();\n\t\tformatUI();\n\t\tinitUIListeners();\n\n\t\tapp.context = MainActivity.this;\n\n\t\tif(getIntent().getExtras() != null) {\n\n\t\t\tMLog.log(\"Extras not null\");\n\n\t\t\tString deepLink = getIntent().getExtras().getString(MainActivity.DEEP_LINK);\n\n\t\t\tif(deepLink != null) {\n\n\t\t\t\tif(deepLink.length() > 0) {\n\n\t\t\t\t\tif(deepLink.contains(MainActivity.DEEP_LINK_VALUE_PRODUCT_LIST)) {\n\n\t\t\t\t\t\tfragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\t\t\t\tString _idStream = getIntent().getExtras().getString(MainActivity.DEEP_LINK_PARAM);\n\t\t\t\t\t\tFragmentShopItemsList frag = new FragmentShopItemsList();\n\t\t\t\t\t\tfrag.idStream = Integer.parseInt(_idStream);\n\t\t\t\t\t\tfragMgr.beginTransaction()\n\t\t\t\t\t\t.add(R.id.ll_body, frag)\n\t\t\t\t\t\t.addToBackStack(null)\n\t\t\t\t\t\t.commit();\n\n\t\t\t\t\t} else if(deepLink.contains(MainActivity.DEEP_LINK_VALUE_CART)) {\n\n\t\t\t\t\t\tloadCart();\n\n\t\t\t\t\t} else if(deepLink.contains(MainActivity.DEEP_LINK_VALUE_ALERTS)) {\n\n\t\t\t\t\t\tloadAlerts();\n\n\t\t\t\t\t} else if(deepLink.contains(MainActivity.DEEP_LINK_VALUE_ACCOUNT)) {\n\n\t\t\t\t\t\tloadMenu();\n\n\t\t\t\t\t} else if(deepLink.contains(MainActivity.DEEP_LINK_VALUE_POLICIES)) {\n\n\t\t\t\t\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\t\t\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM);\n\t\t\t\t\t\tArrayList<HashMap<String, String>> records = null;\n\t\t\t\t\t\tif(dbC.isOpen()) {\n\t\t\t\t\t\t\tdbC.isAvailale();\n\t\t\t\t\t\t\trecords = dbC.retrieveRecords(map);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(records.size() >= 2) {\n\n\t\t\t\t\t\t\tmap = records.get(1);\n\n\t\t\t\t\t\t\tFragmentShopItemsList fragment = new FragmentShopItemsList();\n\t\t\t\t\t\t\tfragment.idStream = Integer.parseInt(map.get(MainActivity.DB_COL_SRV_ID));\n\t\t\t\t\t\t\tfragMgr.beginTransaction()\n\t\t\t\t\t\t\t.add(R.id.ll_body, fragment)\n\t\t\t\t\t\t\t.addToBackStack(null)\n\t\t\t\t\t\t\t.commit();\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else if(deepLink.contains(MainActivity.DEEP_LINK_VALUE_DEV)) {\n\n\t\t\t\t\t\tFragmentDev fragment = new FragmentDev();\t\n\t\t\t\t\t\tfragMgr.beginTransaction()\n\t\t\t\t\t\t.add(R.id.ll_body, fragment)\n\t\t\t\t\t\t.addToBackStack(null)\n\t\t\t\t\t\t.commit();\n\n\t\t\t\t\t} \n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\t\t\tpopulateLocation();\n\t\t}\n\n\t}\n\n\t@Override\n\tprotected void onStart() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onStart();\n\t\t\n\t}\n\t\n\t@Override\n\tprotected void onStop() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onStop();\n\t\t\n\t}\n\t\n\t@Override\n\tprotected void onPause() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onPause();\n\t\tGoogleAnalytics.getInstance(MainActivity.this).reportActivityStop(this);\n\t}\n\t\n\t\n\t@Override\n\tprotected void onResume() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onResume();\n\t\t//GoogleAnalytics.getInstance(this).getLogger().setLogLevel(LogLevel.VERBOSE);\n\t\tGoogleAnalytics.getInstance(MainActivity.this).reportActivityStart(this);\n\t\t\n\t\tMLog.log(\"Resuming...\" + app.stateOfLifeCycle);\n\t\tMLog.log(\"Resuming...\" + app.wasInBackground + \"\");\n\t\tMLog.log(\"Resuming...\" + app.ENABLE_SYNC + \"\");\n\n\t\tif(!app.PREVENT_CLOSE_AND_SYNC && !app.ISGOINGOUTOFAPP) {\n\n\t\t\tloadSplash();\n\n\t\t} else {\n\n\t\t\t// Do Nothing\n\n\t\t}\n\n\t\tif(app.ISGOINGOUTOFAPP) {\n\n\t\t\tapp.ISGOINGOUTOFAPP = false;\n\n\t\t}\n\n\t\t/*\n\t\tif(app.wasInBackground) {\n\n\t\t\tif(app.ENABLE_SYNC) {\n\n\t\t\t\tloadSplash();\n\n\t\t\t} else {\n\n\t\t\t\t// Do Nothing\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tif(getIntent().getExtras() == null) {\n\t\t\t\tif(app.ENABLE_SYNC) {\n\t\t\t\t\tloadSplash();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgetIntent().removeExtra(MainActivity.DEEP_LINK);\n\t\t\t\tgetIntent().removeExtra(MainActivity.DEEP_LINK_PARAM);\n\t\t\t}\n\n\t\t}*/\n\n\t}\n\n\tpublic void clearToken() {\n\n\t\tEditor editor = sharedPreferences.edit();\n\t\teditor.remove(TOKEN_KEY);\n\t\teditor.commit();\n\n\t}\n\n\tpublic void clearEmail() {\n\n\t\tEditor editor = sharedPreferences.edit();\n\t\teditor.remove(EMAIL_KEY);\n\t\teditor.commit();\n\t}\n\n\tpublic void updateEmail(String email) {\n\n\t\tEditor editor = sharedPreferences.edit();\n\t\teditor.remove(EMAIL_KEY);\n\t\teditor.putString(EMAIL_KEY, email);\n\t\teditor.commit();\n\n\t}\n\n\tpublic void updateToken(String token) {\n\n\t\tEditor editor = sharedPreferences.edit();\n\t\teditor.remove(TOKEN_KEY);\n\t\teditor.putString(TOKEN_KEY, token);\n\t\teditor.commit();\n\n\t}\n\n\tpublic String getEmail() {\n\n\t\treturn sharedPreferences.getString(EMAIL_KEY, \"\");\n\n\t}\n\n\tpublic String getToken() {\n\n\t\treturn sharedPreferences.getString(TOKEN_KEY, \"\");\n\n\t}\n\n\tpublic String getGold22Rate(int index) {\n\n\t\treturn null;\n\n\t}\n\n\tpublic void populateLocation() {\n\n\t\tHashMap<String, String> mapCountry = new HashMap<String, String>();\n\t\tmapCountry.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_MY_COUNTRY);\n\n\t\tHashMap<String, String> mapState = new HashMap<String, String>();\n\t\tmapState.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_MY_STATE);\n\n\t\tHashMap<String, String> mapCity = new HashMap<String, String>();\n\t\tmapCity.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_MY_CITY);\n\n\t\tArrayList<HashMap<String, String>> recordsCountry = null, recordsState = null, recordsCity = null;\n\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecordsCountry = dbC.retrieveRecords(mapCountry);\n\t\t\trecordsState = dbC.retrieveRecords(mapState);\n\t\t\trecordsCity = dbC.retrieveRecords(mapCity);\n\t\t}\n\n\t\tif(recordsCountry != null && recordsState != null && recordsCity != null) {\n\n\t\t\tif(recordsCountry.size() > 0 && recordsState.size() > 0 && recordsCity.size() > 0) {\n\n\t\t\t\tmapCountry = recordsCountry.get(0);\n\t\t\t\tmapState = recordsState.get(0);\n\t\t\t\tmapCity = recordsCity.get(0);\n\n\t\t\t\tmyCountry = mapCountry.get(MainActivity.DB_COL_NAME);\n\t\t\t\tmyCountryId = mapCountry.get(MainActivity.DB_COL_SRV_ID);\n\t\t\t\tmyState = mapState.get(MainActivity.DB_COL_NAME);\n\t\t\t\tmyStateId = mapState.get(MainActivity.DB_COL_SRV_ID);\n\t\t\t\tmyCity = mapCity.get(MainActivity.DB_COL_NAME);\n\t\t\t\tmyCityId = mapCity.get(MainActivity.DB_COL_SRV_ID);\n\n\t\t\t\tMLog.log(\"My Country \" + myCountry + \" \" + myCountryId);\n\t\t\t\tMLog.log(\"My State \" + myState + \" \" + myStateId);\n\t\t\t\tMLog.log(\"My Cityy \" + myCity + \" \" + myCityId);\n\n\t\t\t} else {\n\n\t\t\t\tmyCity = null;\n\t\t\t\tmyCityId = null;\n\t\t\t\tmyCountry = null;\n\t\t\t\tmyCountryId = null;\n\t\t\t\tmyState = null;\n\t\t\t\tmyStateId = null;\n\n\t\t\t}\n\t\t} else {\n\n\t\t\tmyCity = null;\n\t\t\tmyCityId = null;\n\t\t\tmyCountry = null;\n\t\t\tmyCountryId = null;\n\t\t\tmyState = null;\n\t\t\tmyStateId = null;\n\n\t\t}\n\t}\n\n\tpublic void loadSplash() {\n\n\t\ttry {\n\n\t\t\tapp.ENABLE_SYNC = true;\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = false;\n\n\t\t\tpopulateLocation();\n\t\t\tfragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\tFragmentTransaction fragmentTransaction;\n\n\t\t\tif(myCity == null) {\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentShippingLocation fragmentLoc = new FragmentShippingLocation();\n\t\t\t\tfragmentLoc.isBegin = true;\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_LOCATION)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_LOCATION)\n\t\t\t\t.commit();\n\n\t\t\t} else {\n\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentLoading fragmentLoc = new FragmentLoading();\n\t\t\t\tfragmentLoc.isBegin = true;\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_LOADING)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_LOADING)\n\t\t\t\t.commit();\n\n\n\t\t\t}\n\n\t\t} catch (IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void loadShop() {\n\n\t\ttry {\n\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = false;\n\n\t\t\tpopulateLocation();\n\t\t\tfragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\tFragmentTransaction fragmentTransaction;\n\n\t\t\tif(myCity == null) {\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentShippingLocation fragmentLoc = new FragmentShippingLocation();\n\t\t\t\tfragmentLoc.isBegin = true;\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_LOCATION)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_LOCATION)\n\t\t\t\t.commit();\n\n\t\t\t} else {\n\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentShopCategories fragmentLoc = new FragmentShopCategories();\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_SHOP_CATEGORIES)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_SHOP_CATEGORIES)\n\t\t\t\t.commit();\n\n\t\t\t}\n\n\t\t}catch(IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void loadCart() {\n\n\t\ttry {\n\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = true;\n\n\t\t\tpopulateLocation();\n\t\t\tfragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\tFragmentTransaction fragmentTransaction;\n\n\t\t\tif(myCity == null) {\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentShippingLocation fragmentLoc = new FragmentShippingLocation();\n\t\t\t\tfragmentLoc.isBegin = true;\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_LOCATION)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_LOCATION)\n\t\t\t\t.commit();\n\n\t\t\t} else {\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentPaymentCart fragmentLoc = new FragmentPaymentCart();\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_CART)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_CART)\n\t\t\t\t.commit();\n\n\t\t\t}\n\n\t\t} catch (IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\n\tpublic void loadAlerts() {\n\n\t\ttry {\n\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = false;\n\n\t\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM);\n\t\t\tArrayList<HashMap<String, String>> records = null;\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\trecords = dbC.retrieveRecords(map);\n\t\t\t}\n\n\t\t\tif(records.size() > MainActivity.NUM_INIT_STREAMS) {\n\n\t\t\t\tfor(int i = 0; i < records.size(); i++) {\n\n\t\t\t\t\tmap = records.get(i);\n\t\t\t\t\tString name = map.get(MainActivity.DB_COL_NAME);\n\n\t\t\t\t\tif(name.toLowerCase().contains(\"alert\")) {\n\n\t\t\t\t\t\t//fragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\t\t\t\tFragmentAlertItemsList fragment = new FragmentAlertItemsList();\n\t\t\t\t\t\tfragment.idStream = Integer.parseInt(map.get(MainActivity.DB_COL_SRV_ID));\n\t\t\t\t\t\tfragMgr.beginTransaction()\n\t\t\t\t\t\t\t\t.add(R.id.ll_body, fragment, MainActivity.SCREEN_ALERT_ITEM_LIST)\n\t\t\t\t\t\t\t\t.addToBackStack(MainActivity.SCREEN_ALERT_ITEM_LIST)\n\t\t\t\t\t\t\t\t.commit();\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} catch (IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void loadPolicy() {\n\n\t\ttry {\n\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = false;\n\n\t\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM);\n\t\t\tArrayList<HashMap<String, String>> records = null;\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\trecords = dbC.retrieveRecords(map);\n\t\t\t}\n\n\t\t\tif(records.size() > MainActivity.NUM_INIT_STREAMS) {\n\n\t\t\t\tfor(int i = 0; i < records.size(); i++) {\n\n\t\t\t\t\tmap = records.get(i);\n\t\t\t\t\tString name = map.get(MainActivity.DB_COL_NAME);\n\n\t\t\t\t\tif(name.toLowerCase().contains(\"terms\")) {\n\n\t\t\t\t\t\t//fragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\t\t\t\tFragmentPolicyItemsList fragment = new FragmentPolicyItemsList();\n\t\t\t\t\t\tfragment.idStream = Integer.parseInt(map.get(MainActivity.DB_COL_SRV_ID));\n\t\t\t\t\t\tfragMgr.beginTransaction()\n\t\t\t\t\t\t\t\t.add(R.id.ll_body, fragment, MainActivity.SCREEN_POLICY_ITEM_LIST)\n\t\t\t\t\t\t\t\t.addToBackStack(MainActivity.SCREEN_POLICY_ITEM_LIST)\n\t\t\t\t\t\t\t\t.commit();\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} catch (IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void loadAbout() {\n\n\t\ttry {\n\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = false;\n\n\t\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM);\n\t\t\tArrayList<HashMap<String, String>> records = null;\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\trecords = dbC.retrieveRecords(map);\n\t\t\t}\n\n\t\t\tif(records.size() > MainActivity.NUM_INIT_STREAMS) {\n\n\t\t\t\tfor(int i = 0; i < records.size(); i++) {\n\n\t\t\t\t\tmap = records.get(i);\n\t\t\t\t\tString name = map.get(MainActivity.DB_COL_NAME);\n\n\t\t\t\t\tif(name.toLowerCase().contains(\"about\")) {\n\n\n\t\t\t\t\t\t//fragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\t\t\t\tFragmentAboutItemsList fragment = new FragmentAboutItemsList();\n\t\t\t\t\t\tfragment.idStream = Integer.parseInt(map.get(MainActivity.DB_COL_SRV_ID));\n\t\t\t\t\t\tfragMgr.beginTransaction()\n\t\t\t\t\t\t\t\t.add(R.id.ll_body, fragment, MainActivity.SCREEN_ABOUT_ITEM_LIST)\n\t\t\t\t\t\t\t\t.addToBackStack(MainActivity.SCREEN_ABOUT_ITEM_LIST)\n\t\t\t\t\t\t\t\t.commit();\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} catch (IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\tpublic void loadMenu() {\n\n\t\ttry {\n\n\t\t\tapp.PREVENT_CLOSE_AND_SYNC = true;\n\n\t\t\tpopulateLocation();\n\t\t\tfragMgr.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t\tFragmentTransaction fragmentTransaction;\n\n\t\t\tif(myCity == null) {\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentShippingLocation fragmentLoc = new FragmentShippingLocation();\n\t\t\t\tfragmentLoc.isBegin = true;\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_LOCATION)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_LOCATION)\n\t\t\t\t.commit();\n\n\t\t\t} else {\n\n\t\t\t\tfragmentTransaction = fragMgr.beginTransaction();\n\t\t\t\tFragmentMenu fragmentLoc = new FragmentMenu();\n\t\t\t\tfragmentTransaction.add(R.id.ll_body, fragmentLoc, MainActivity.SCREEN_ACCOUNT)\n\t\t\t\t.addToBackStack(MainActivity.SCREEN_ACCOUNT)\n\t\t\t\t.commit();\n\n\t\t\t}\n\n\t\t} catch (IllegalStateException e) {\n\n\t\t}\n\n\t}\n\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\t// TODO Auto-generated method stub\n\t\tint backStackEntryCount = fragMgr.getBackStackEntryCount();\n\t\tMLog.log(\"Back Pressed = \" + lastCreatedActivity);\n\t\tMLog.log(\"Back Stack Entry = \" + backStackEntryCount);\n\n\t\tif(app.APP_EXIT_ON_BACK) {\n\t\t\tsuper.onBackPressed();\n\t\t\tfinish();\n\t\t} else {\n\n\t\t\tif(backStackEntryCount == 1){\n\n\t\t\t\tString fragmentTag = fragMgr.getBackStackEntryAt(fragMgr.getBackStackEntryCount() - 1).getName();\n\t\t\t\tMLog.log(\"Back Fragment found \" + fragmentTag);\n\t\t\t\tif(fragmentTag.equals(MainActivity.SCREEN_SHOP_CATEGORIES)) {\n\t\t\t\t\tsuper.onBackPressed();\n\t\t\t\t\tfinish();\n\t\t\t\t} else {\n\t\t\t\t\tloadShop();\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\tMLog.log(\"Pressing Back\");\n\t\t\t\tsuper.onBackPressed();\n\n\t\t\t}\n\n\t\t}\n\t\tIS_CLICKABLE_FRAGMENT = true;\n\n\t}\n\n\tHandler cartNotifHandler = new Handler() {\n\n\t\tpublic void handleMessage(Message msg) {\n\n\t\t\tif(msg.what == 0) {\n\n\t\t\t\ttvCartNotif.setVisibility(RelativeLayout.GONE);\n\n\t\t\t} else {\n\n\t\t\t\ttvCartNotif.setText(msg.what + \"\");\n\t\t\t\ttvCartNotif.setVisibility(RelativeLayout.VISIBLE);\n\n\t\t\t}\n\n\t\t};\n\n\t};\n\n\tHandler alertNotifHandler = new Handler() {\n\n\t\tpublic void handleMessage(Message msg) {\n\n\t\t\tif(msg.what == 0) {\n\n\t\t\t} else {\n\n\t\t\t}\n\n\t\t};\n\n\t};\n\n\tpublic void clearAlertNotification() {\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_NOTIF);\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\tArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();\n\t\t\tlist = dbC.retrieveRecords(map);\n\t\t\tif(list.isEmpty()) {\n\t\t\t} else {\n\n\t\t\t\tif(list.size() > 1) {\n\n\t\t\t\t\tdbC.deleteRecord(map);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tHashMap<String, String> mapR = list.get(0);\n\t\t\t\t\tint isOpen = Integer.parseInt(mapR.get(MainActivity.DB_COL_CART_CART_ISOPEN));\n\t\t\t\t\tif(isOpen == 0) {\n\t\t\t\t\t\tmapR.put(MainActivity.DB_COL_CART_CART_ISOPEN, \"1\");\n\t\t\t\t\t\tdbC.updateRecord(mapR, map);\n\t\t\t\t\t\talertNotifHandler.sendEmptyMessage(0);\n\t\t\t\t\t} \n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void showAlertNotification() {\n\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_NOTIF);\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\tArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();\n\t\t\tlist = dbC.retrieveRecords(map);\n\t\t\tif(list.isEmpty()) {\n\t\t\t\tMessage msg = new Message();\n\t\t\t\talertNotifHandler.sendEmptyMessage(0);\n\t\t\t\t//show notification\n\t\t\t} else {\n\n\t\t\t\tif(list.size() > 1) {\n\n\t\t\t\t\tdbC.deleteRecord(map);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tHashMap<String, String> mapR = list.get(0);\n\t\t\t\t\tint isOpen = Integer.parseInt(mapR.get(MainActivity.DB_COL_CART_CART_ISOPEN));\n\t\t\t\t\tif(isOpen == 0) {\n\t\t\t\t\t\talertNotifHandler.sendEmptyMessage(1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\talertNotifHandler.sendEmptyMessage(0);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void showCartNotification() {\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART);\n\t\tmap.put(MainActivity.DB_COL_CART_CART_ISOPEN, MainActivity.DB_RECORD_VALUE_CART_OPEN);\n\t\tString _idOpenCart = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\t_idOpenCart = dbC.retrieveId(map);\n\t\t}\n\n\t\t// If open cart exists proceed else show message no item present\n\n\t\tif(_idOpenCart != null && _idOpenCart.length() > 0) {\n\n\t\t\tmap = new HashMap<String, String>();\n\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART_ITEM);\n\t\t\tmap.put(MainActivity.DB_COL_FOREIGN_KEY, _idOpenCart);\n\t\t\tArrayList<HashMap<String, String>> recordsItems = null;\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\trecordsItems = dbC.retrieveRecords(map);\n\t\t\t}\n\n\t\t\tMLog.log(\"Checking cart items \" + recordsItems.size());\n\n\t\t\tif(recordsItems.size() > 0) {\n\n\t\t\t\t//cartNotifHandler.sendEmptyMessage(1);\n\t\t\t\tcartNotifHandler.sendEmptyMessage(recordsItems.size());\n\n\t\t\t} else {\n\n\t\t\t\tcartNotifHandler.sendEmptyMessage(0);\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tcartNotifHandler.sendEmptyMessage(0);\n\n\t\t}\n\n\t}\n\n\n\n\tint pixelsToDp(int pixels) {\n\n\t\tDisplayMetrics metrics = MainActivity.this.getResources().getDisplayMetrics();\n\t\tfloat dp = pixels;\n\t\tfloat fpixels = metrics.density * dp;\n\t\treturn pixels = (int) (fpixels + 0.5f);\n\n\t}\n\n\tpublic int dpToPixels(int dp) {\n\t\tfloat density = getApplicationContext().getResources().getDisplayMetrics().density;\n\t\treturn Math.round((float) dp * density);\n\t}\n\n\tfloat pixelsToSp(Context context, float px) {\n\t\tfloat scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;\n\t\t//Log.d(TAG, \"Scaled Density \" + scaledDensity + \"\");\n\t\treturn px/scaledDensity;\n\t}\n\n\tfloat spToPixels(Context context, float px) {\n\t\tfloat scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;\n\t\t//Log.d(TAG, \"Scaled Density \" + scaledDensity + \"\");\n\t\treturn px*scaledDensity;\n\t}\n\n\tpublic Boolean checkIfExistsInExternalStorage(String fileName) {\n\n\t\tString filePath = STORAGE_PATH + \"/\" + fileName;\n\t\tFile file = new File(filePath);\n\t\tif(file.exists()) {\n\n\t\t\tif(file.length() > 0) {\n\t\t\t\treturn file.exists();\n\t\t\t} else {\n\n\t\t\t\tfile.delete();\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn file.exists();\n\n\t}\n\n\t@Override\n\tpublic void storeContext() {\n\t\t// TODO Auto-generated method stub\n\t\tcontext = MainActivity.this;\n\t\tapp = (ZonConApplication)getApplicationContext();\n\t}\n\n\t@Override\n\tpublic void initUIListeners() {\n\t\t// TODO Auto-generated method stub\n\n\t\tivHeadMenu.setOnClickListener(new View.OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\t// TODO Auto-generated method stub\n\n\t\t\t\tif (!IS_CLICKED) {\n\n\t\t\t\t\tIS_CLICKED = true;\n\t\t\t\t\tloadMenu();\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\n\t\tivHeadCart.setOnClickListener(new View.OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\t// TODO Auto-generated method stub\n\n\t\t\t\tif(!IS_CLICKED) {\n\n\t\t\t\t\tIS_CLICKED = true;\n\t\t\t\t\tloadCart();\n\n\t\t\t\t} \n\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic void initUIHandles() {\n\t\t// TODO Auto-generated method stub\n\t\tllHead = (LinearLayout)findViewById(R.id.ll_head);\n\t\tivHeadTitle = (ImageView)findViewById(R.id.iv_head_title);\n\t\tivHeadCart = (ImageView)findViewById(R.id.iv_head_cart);\n\t\tivHeadMenu = (ImageView)findViewById(R.id.iv_head_menu);\n\n\t\ttvCartNotif = (TextView)findViewById(R.id.tv_cart_notif);\n\n\t\tflBody = (FrameLayout)findViewById(R.id.ll_body);\n\n\t\ttf = Typeface.createFromAsset(getAssets(), \"icomoon.ttf\");\n\n\t}\n\n\t@Override\n\tpublic void formatUI() {\n\t\t// TODO Auto-generated method stub\n\n\t\tif(isTablet(getApplicationContext())) {\n\n\t\t\tTEXT_SIZE_TILE = (char)(18);\n\t\t\tTEXT_SIZE_TITLE = (char)(22);\n\n\t\t}\n\n\t}\n\n\tpublic void highlightFooter(int index) {\n\n\n\t}\n\n\tpublic void showConnected(Boolean value) {\n\n\t}\n\n\t@Override\n\tpublic void storeClassVariables() {\n\t\t// TODO Auto-generated method stub\n\t\tdbC = app.conn;\n\t\tfragMgr = getFragmentManager();\n\n\t}\n\n\tpublic Handler handlerLoading = new Handler() {\n\n\t\tpublic void handleMessage(android.os.Message msg) {\n\n\t\t\tif(msg.what == 0) {\n\n\t\t\t\thideLoading();\n\n\t\t\t} else {\n\n\t\t\t\tshowLoading();\n\n\t\t\t}\n\n\t\t};\n\n\t};\n\n\tpublic void hideHeaderFooter() {\n\n\t\tllHead.setVisibility(RelativeLayout.GONE);\n\t\tRelativeLayout.LayoutParams rParams = (RelativeLayout.LayoutParams) flBody.getLayoutParams();\n\t\trParams.setMargins(0, 0, 0, 0);\n\n\n\t}\n\n\tpublic void showHeaderFooter() {\n\n\t\tllHead.setVisibility(RelativeLayout.VISIBLE);\n\t\tRelativeLayout.LayoutParams rParams = (RelativeLayout.LayoutParams) flBody.getLayoutParams();\n\t\trParams.setMargins(0, dpToPixels(MainActivity.BODY_TOP_MARGIN_DP), 0, dpToPixels(MainActivity.BODY_BOTTOM_MARGIN_DP));\n\n\n\t}\n\n\tpublic void showLoading() {\n\n\t\tpageLoad = new ProgressDialog(MainActivity.this);\n\t\tpageLoad.setTitle(\"Loading...\");\n\t\tpageLoad.setMessage(\"Please wait\");\n\t\tpageLoad.setCanceledOnTouchOutside(false);\n\t\tpageLoad.show();\n\n\t}\n\n\tpublic void hideLoading() {\n\n\t\tpageLoad.dismiss();\n\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void setRunFlag(Boolean value) {\n\t\t// TODO Auto-generated method stub\n\t\tRUN_FLAG = value;\n\t}\n\n\tprotected Handler threadHandler = new Handler() {\n\n\t\tpublic void handleMessage(android.os.Message msg) {\n\n\n\n\n\t\t}\n\n\t};\n\n\tpublic boolean isTablet(Context context) {\n\t\tboolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);\n\t\tboolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);\n\t\tMLog.log(\"IS TABLET = \" + (xlarge || large));\n\t\treturn (xlarge || large);\n\t}\n\n\n\tpublic Boolean applyCouponToCart(String code, Boolean containsDiscount, String purchasePrice, String discountDifference) {\n\n\t\tMLog.log(\"Current Coupon = \" + code);\n\n\t\tCouponRecord cr = getCouponRecordFromCode(code);\n\n\t\tif(cr != null) {\n\n\t\t\tMLog.log(\"Code \" + cr.code);\n\t\t\tMLog.log(\"Double \" + cr.allowDoubleDiscouting);\n\n\t\t\tMLog.log(\"Purchase=\" + purchasePrice);\n\t\t\tMLog.log(\"Min Purchase=\" + cr.minPurchase);\n\n\t\t\tif(cr.minPurchase != null) {\n\n\t\t\t\tif(cr.minPurchase.length() > 0) {\n\n\t\t\t\t\tif(Double.parseDouble(purchasePrice) < Double.parseDouble(cr.minPurchase)) {\n\n\t\t\t\t\t\tAlertDialog.Builder alert = new AlertDialog.Builder(context);\n\t\t\t\t\t\talert.setMessage(MainActivity.MSG_COUPON_MIN_PURCHASE_LIMIT + cr.minPurchase);\n\t\t\t\t\t\talert.setTitle(\"Alert\");\n\t\t\t\t\t\talert.setPositiveButton(MainActivity.MSG_OK, new DialogInterface.OnClickListener() {\n\t\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\t\t//dismiss the dialog\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\talert.create().show();\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(!cr.allowDoubleDiscouting.equals(\"1\") && containsDiscount) {\n\n\t\t\t\tAlertDialog.Builder alert = new AlertDialog.Builder(context);\n\t\t\t\talert.setMessage(MainActivity.MSG_COUPON_DOUBLE_NOT_ALLOWED);\n\t\t\t\talert.setTitle(\"Error\");\n\t\t\t\talert.setPositiveButton(MainActivity.MSG_OK, new DialogInterface.OnClickListener() {\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t//dismiss the dialog\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\talert.create().show();\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART);\n\t\t\tArrayList<HashMap<String, String>> recordsCart = null;\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\trecordsCart = dbC.retrieveRecords(map);\n\t\t\t}\n\n\t\t\tif(recordsCart.size() > 0) {\n\n\t\t\t\tHashMap<String, String> mapExisting = recordsCart.get(0);\n\t\t\t\tmapExisting.put(MainActivity.DB_COL_DISCOUNT, cr.id);\n\t\t\t\tif(dbC.isOpen()) {\n\t\t\t\t\tdbC.isAvailale();\n\t\t\t\t\tdbC.updateRecord(mapExisting, map);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tAlertDialog.Builder alert = new AlertDialog.Builder(context);\n\t\talert.setMessage(MainActivity.MSG_COUPON_INVALID_LOCATION);\n\t\talert.setTitle(\"Alert\");\n\t\talert.setPositiveButton(MainActivity.MSG_OK, new DialogInterface.OnClickListener() {\n\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t//dismiss the dialog\n\t\t\t}\n\t\t});\n\t\talert.create().show();\n\n\t\treturn false;\n\t}\n\n\tpublic void removeAppliedCouponToCart() {\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART);\n\t\tArrayList<HashMap<String, String>> recordsCart = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecordsCart = dbC.retrieveRecords(map);\n\t\t}\n\n\t\tif(recordsCart.size() > 0) {\n\n\t\t\tHashMap<String, String> mapExisting = recordsCart.get(0);\n\t\t\tmapExisting.put(MainActivity.DB_COL_DISCOUNT, \"\");\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\tdbC.updateRecord(mapExisting, map);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\tpublic CouponRecord getCouponAppliedToCart() {\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART);\n\t\tArrayList<HashMap<String, String>> recordsCart = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecordsCart = dbC.retrieveRecords(map);\n\t\t}\n\n\t\tif(recordsCart.size() > 0) {\n\n\t\t\tHashMap<String, String> mapExisting = recordsCart.get(0);\n\t\t\tString idCoupon = mapExisting.get(MainActivity.DB_COL_DISCOUNT);\n\n\t\t\tif(idCoupon != null) {\n\n\t\t\t\tif(idCoupon.length() > 0) {\n\n\t\t\t\t\treturn getCouponRecordFromId(idCoupon);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic CouponRecord getCouponRecordFromCode(String code) {\n\n\t\tCouponRecord dr = null;\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON);\n\t\tArrayList<HashMap<String, String>> recordsCoupons = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecordsCoupons = dbC.retrieveRecords(map);\n\t\t}\n\n\t\tfor(int j = 0; j < recordsCoupons.size(); j++) {\n\n\t\t\tmap = recordsCoupons.get(j);\n\n\t\t\tString discountCode = map.get(MainActivity.DB_COL_NAME);\n\t\t\tString discountType = map.get(MainActivity.DB_COL_TITLE);\n\t\t\tString discountValue = map.get(MainActivity.DB_COL_PRICE);\n\t\t\tString idDiscount = map.get(MainActivity.DB_COL_SRV_ID);\n\t\t\tString allowDouble = map.get(MainActivity.DB_COL_CAPTION);\n\t\t\tString maxVal = map.get(MainActivity.DB_COL_EXTRA_1);\n\t\t\tString minPurchase = map.get(MainActivity.DB_COL_EXTRA_2);\n\n\t\t\tif(code.equals(discountCode)) {\n\n\t\t\t\tMLog.log(\"Coupon Found\");\n\t\t\t\tdr = new CouponRecord();\n\t\t\t\tdr.code = discountCode;\n\t\t\t\tdr.type = discountType;\n\t\t\t\tdr.value = discountValue;\n\t\t\t\tdr.id = idDiscount;\n\t\t\t\tdr.allowDoubleDiscouting = allowDouble;\n\t\t\t\tdr.maxVal = maxVal;\n\t\t\t\tdr.minPurchase = minPurchase;\n\n\t\t\t\tMLog.log(\"Coupon Found \" + dr.code + \" \" + dr.type + \" \" + dr.value + \" \" + dr.id);\n\n\t\t\t\treturn dr;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn dr;\n\n\t}\n\n\tpublic CouponRecord getCouponRecordFromId(String discountId) {\n\n\t\tCouponRecord dr = null;\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON);\n\t\tArrayList<HashMap<String, String>> recordsCoupons = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecordsCoupons = dbC.retrieveRecords(map);\n\t\t}\n\n\t\tfor(int j = 0; j < recordsCoupons.size(); j++) {\n\n\t\t\tHashMap<String, String> map1 = null;\n\n\t\t\tmap1 = recordsCoupons.get(j);\n\n\t\t\tString discountCode = map1.get(MainActivity.DB_COL_NAME);\n\t\t\tString discountType = map1.get(MainActivity.DB_COL_TITLE);\n\t\t\tString discountValue = map1.get(MainActivity.DB_COL_PRICE);\n\t\t\tString idDiscount = map1.get(MainActivity.DB_COL_SRV_ID);\n\t\t\tString allowDouble = map1.get(MainActivity.DB_COL_CAPTION);\n\t\t\tString maxVal = map1.get(MainActivity.DB_COL_EXTRA_1);\n\t\t\tString minPurchase = map1.get(MainActivity.DB_COL_EXTRA_2);\n\n\t\t\tif(idDiscount.equals(discountId)) {\n\n\t\t\t\tMLog.log(\"Coupon Found\");\n\t\t\t\tdr = new CouponRecord();\n\t\t\t\tdr.code = discountCode;\n\t\t\t\tdr.type = discountType;\n\t\t\t\tdr.value = discountValue;\n\t\t\t\tdr.allowDoubleDiscouting = allowDouble;\n\t\t\t\tdr.id = discountId;\n\t\t\t\tdr.maxVal = maxVal;\n\t\t\t\tdr.minPurchase = minPurchase;\n\n\t\t\t\tMLog.log(\"Coupon Found \" + dr.code + \" \" + dr.type + \" \" + dr.value + \" \" + dr.id + \" \" + minPurchase + \" \" + maxVal);\n\n\t\t\t\treturn dr;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn dr;\n\n\t}\n\n\n\tpublic DiscountRecord getDiscountRecordFromId(String discountId) {\n\n\t\tDiscountRecord dr = null;\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_DISCOUNT);\n\t\tArrayList<HashMap<String, String>> recordsDiscounts = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecordsDiscounts = dbC.retrieveRecords(map);\n\t\t}\n\n\t\tfor(int j = 0; j < recordsDiscounts.size(); j++) {\n\n\t\t\tmap = recordsDiscounts.get(j);\n\n\t\t\tString discountCode = map.get(MainActivity.DB_COL_NAME);\n\t\t\tString discountType = map.get(MainActivity.DB_COL_TITLE);\n\t\t\tString discountValue = map.get(MainActivity.DB_COL_PRICE);\n\t\t\tString idDiscount = map.get(MainActivity.DB_COL_SRV_ID);\n\n\t\t\tif(idDiscount.equals(discountId)) {\n\n\t\t\t\tMLog.log(\"Discount Found\");\n\t\t\t\tdr = new DiscountRecord();\n\t\t\t\tdr.code = discountCode;\n\t\t\t\tdr.type = discountType;\n\t\t\t\tdr.value = discountValue;\n\t\t\t\tdr.id = discountId;\n\t\t\t\tMLog.log(\"Discount Found \" + dr.code + \" \" + dr.type + \" \" + dr.value + \" \" + dr.id);\n\t\t\t\treturn dr;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn dr;\n\n\t}\n\n\tpublic Boolean checkVersionCompat() {\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM);\n\t\tmap.put(MainActivity.DB_COL_NAME, MainActivity.STREAM_NAME_VERSIONS);\n\n\t\tArrayList<HashMap<String, String>> records = null;\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\trecords = dbC.retrieveRecords(map);\n\t\t}\n\n\t\tMLog.log(\"Version Records=\" + records.size());\n\n\t\tif(records.size() > 0) {\n\n\t\t\tmap = records.get(0);\n\t\t\tString streamKey = map.get(MainActivity.DB_COL_ID);\n\n\t\t\tMLog.log(\"Version Records key =\" + streamKey);\n\n\t\t\tmap = new HashMap<String, String>();\n\t\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_ITEM);\n\t\t\tmap.put(MainActivity.DB_COL_FOREIGN_KEY, streamKey);\n\t\t\tif(dbC.isOpen()) {\n\t\t\t\tdbC.isAvailale();\n\t\t\t\trecords = dbC.retrieveRecords(map);\n\t\t\t}\n\n\t\t\tMLog.log(\"Version Records Items key =\" + records.size());\n\n\t\t\tif(records.size() > 0) {\n\n\t\t\t\tmap = records.get(0);\n\t\t\t\tString versionWeb = map.get(MainActivity.DB_COL_TITLE);\n\t\t\t\tMLog.log(\"Web Version = \" + versionWeb);\n\t\t\t\ttry {\n\n\t\t\t\t\tString version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;\n\t\t\t\t\tDouble dVersionWeb = Double.valueOf(versionWeb);\n\t\t\t\t\tDouble dVersion = Double.valueOf(version);\n\t\t\t\t\tif(dVersion >= dVersionWeb) {\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t}\n\n\t\t\t\t} catch (NameNotFoundException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\n\t\t\t} \n\t\t}\n\n\n\t\treturn false;\n\n\t\t//activity.getFragmentManager().beginTransaction().remove(FragmentLoading.this).commit();\n\n\t}\n\n\tpublic void addNewCoupon(CouponRecord cr, String timestamp) {\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON);\n\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\tdbC.deleteRecord(map);\n\t\t}\n\n\t\tmap = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_COUPON);\n\t\tmap.put(MainActivity.DB_COL_NAME, cr.code);\n\t\tmap.put(MainActivity.DB_COL_TITLE, cr.type);\n\t\tmap.put(MainActivity.DB_COL_TIMESTAMP, timestamp);\n\t\tmap.put(MainActivity.DB_COL_PRICE, cr.value);\n\t\tmap.put(MainActivity.DB_COL_CAPTION, cr.allowDoubleDiscouting);\n\t\tmap.put(MainActivity.DB_COL_SRV_ID, cr.id);\n\t\tmap.put(MainActivity.DB_COL_EXTRA_1, cr.maxVal);\n\t\tmap.put(MainActivity.DB_COL_EXTRA_2, cr.minPurchase);\n\t\tdbC.insertRecord(map);\n\n\t}\n\n\tpublic TaxRecord getTax1() {\n\n\t\tTaxRecord taxRecord = null;\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_TAX_1);\n\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\tArrayList<HashMap<String, String>> list = dbC.retrieveRecords(map);\n\t\t\tif(list.size() > 0) {\n\t\t\t\tmap = list.get(0);\n\t\t\t\ttaxRecord = new TaxRecord();\n\t\t\t\ttaxRecord.label = map.get(MainActivity.DB_COL_TITLE);\n\t\t\t\ttaxRecord.value = map.get(MainActivity.DB_COL_SUB);\n\t\t\t}\n\t\t}\n\n\t\treturn taxRecord;\n\n\t}\n\n\tpublic TaxRecord getTax2() {\n\n\t\tTaxRecord taxRecord = null;\n\n\t\tHashMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_TAX_2);\n\n\t\tif(dbC.isOpen()) {\n\t\t\tdbC.isAvailale();\n\t\t\tArrayList<HashMap<String, String>> list = dbC.retrieveRecords(map);\n\t\t\tif(list.size() > 0) {\n\t\t\t\tmap = list.get(0);\n\t\t\t\ttaxRecord = new TaxRecord();\n\t\t\t\ttaxRecord.label = map.get(MainActivity.DB_COL_TITLE);\n\t\t\t\ttaxRecord.value = map.get(MainActivity.DB_COL_SUB);\n\t\t\t}\n\t\t}\n\n\t\treturn taxRecord;\n\n\t}\n\n}", "public final class R {\n public static final class anim {\n public static final int abc_fade_in=0x7f040000;\n public static final int abc_fade_out=0x7f040001;\n public static final int abc_grow_fade_in_from_bottom=0x7f040002;\n public static final int abc_popup_enter=0x7f040003;\n public static final int abc_popup_exit=0x7f040004;\n public static final int abc_shrink_fade_out_from_bottom=0x7f040005;\n public static final int abc_slide_in_bottom=0x7f040006;\n public static final int abc_slide_in_top=0x7f040007;\n public static final int abc_slide_out_bottom=0x7f040008;\n public static final int abc_slide_out_top=0x7f040009;\n public static final int pestle_in=0x7f04000a;\n public static final int picture_rotate=0x7f04000b;\n public static final int pop_in=0x7f04000c;\n }\n public static final class attr {\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarDivider=0x7f010086;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarItemBackground=0x7f010087;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarPopupTheme=0x7f010080;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>wrap_content</code></td><td>0</td><td></td></tr>\n</table>\n */\n public static final int actionBarSize=0x7f010085;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarSplitStyle=0x7f010082;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarStyle=0x7f010081;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarTabBarStyle=0x7f01007c;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarTabStyle=0x7f01007b;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarTabTextStyle=0x7f01007d;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarTheme=0x7f010083;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionBarWidgetTheme=0x7f010084;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionButtonStyle=0x7f0100a0;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionDropDownStyle=0x7f01009c;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionLayout=0x7f010054;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionMenuTextAppearance=0x7f010088;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int actionMenuTextColor=0x7f010089;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeBackground=0x7f01008c;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeCloseButtonStyle=0x7f01008b;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeCloseDrawable=0x7f01008e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeCopyDrawable=0x7f010090;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeCutDrawable=0x7f01008f;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeFindDrawable=0x7f010094;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModePasteDrawable=0x7f010091;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModePopupWindowStyle=0x7f010096;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeSelectAllDrawable=0x7f010092;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeShareDrawable=0x7f010093;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeSplitBackground=0x7f01008d;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeStyle=0x7f01008a;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionModeWebSearchDrawable=0x7f010095;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionOverflowButtonStyle=0x7f01007e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int actionOverflowMenuStyle=0x7f01007f;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int actionProviderClass=0x7f010056;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int actionViewClass=0x7f010055;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int activityChooserViewStyle=0x7f0100a8;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int adSize=0x7f010027;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int adSizes=0x7f010028;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int adUnitId=0x7f010029;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int alertDialogButtonGroupStyle=0x7f0100ca;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int alertDialogCenterButtons=0x7f0100cb;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int alertDialogStyle=0x7f0100c9;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int alertDialogTheme=0x7f0100cc;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int ambientEnabled=0x7f010051;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>holo_dark</code></td><td>0</td><td></td></tr>\n<tr><td><code>holo_light</code></td><td>1</td><td></td></tr>\n</table>\n */\n public static final int appTheme=0x7f0100ef;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int arrowHeadLength=0x7f010037;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int arrowShaftLength=0x7f010038;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int autoCompleteTextViewStyle=0x7f0100d1;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int background=0x7f010014;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int backgroundSplit=0x7f010016;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int backgroundStacked=0x7f010015;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int backgroundTint=0x7f0100ed;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>src_over</code></td><td>3</td><td></td></tr>\n<tr><td><code>src_in</code></td><td>5</td><td></td></tr>\n<tr><td><code>src_atop</code></td><td>9</td><td></td></tr>\n<tr><td><code>multiply</code></td><td>14</td><td></td></tr>\n<tr><td><code>screen</code></td><td>15</td><td></td></tr>\n</table>\n */\n public static final int backgroundTintMode=0x7f0100ee;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int barLength=0x7f010039;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int borderlessButtonStyle=0x7f0100a5;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonBarButtonStyle=0x7f0100a2;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonBarNegativeButtonStyle=0x7f0100cf;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonBarNeutralButtonStyle=0x7f0100d0;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonBarPositiveButtonStyle=0x7f0100ce;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonBarStyle=0x7f0100a1;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonPanelSideLayout=0x7f01002a;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>standard</code></td><td>0</td><td></td></tr>\n<tr><td><code>wide</code></td><td>1</td><td></td></tr>\n<tr><td><code>icon_only</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int buttonSize=0x7f010067;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonStyle=0x7f0100d2;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int buttonStyleSmall=0x7f0100d3;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int buttonTint=0x7f010030;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>src_over</code></td><td>3</td><td></td></tr>\n<tr><td><code>src_in</code></td><td>5</td><td></td></tr>\n<tr><td><code>src_atop</code></td><td>9</td><td></td></tr>\n<tr><td><code>multiply</code></td><td>14</td><td></td></tr>\n<tr><td><code>screen</code></td><td>15</td><td></td></tr>\n</table>\n */\n public static final int buttonTintMode=0x7f010031;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>google_wallet_classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>google_wallet_grayscale</code></td><td>2</td><td></td></tr>\n<tr><td><code>google_wallet_monochrome</code></td><td>3</td><td></td></tr>\n<tr><td><code>android_pay_dark</code></td><td>4</td><td></td></tr>\n<tr><td><code>android_pay_light</code></td><td>5</td><td></td></tr>\n<tr><td><code>android_pay_light_with_border</code></td><td>6</td><td></td></tr>\n<tr><td><code>classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>grayscale</code></td><td>2</td><td></td></tr>\n<tr><td><code>monochrome</code></td><td>3</td><td></td></tr>\n</table>\n */\n public static final int buyButtonAppearance=0x7f0100f6;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>match_parent</code></td><td>-1</td><td></td></tr>\n<tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr>\n</table>\n */\n public static final int buyButtonHeight=0x7f0100f3;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>buy_with</code></td><td>5</td><td></td></tr>\n<tr><td><code>logo_only</code></td><td>6</td><td></td></tr>\n<tr><td><code>donate_with</code></td><td>7</td><td></td></tr>\n<tr><td><code>buy_with_google</code></td><td>1</td><td></td></tr>\n<tr><td><code>buy_now</code></td><td>2</td><td></td></tr>\n<tr><td><code>book_now</code></td><td>3</td><td></td></tr>\n<tr><td><code>donate_with_google</code></td><td>4</td><td></td></tr>\n</table>\n */\n public static final int buyButtonText=0x7f0100f5;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>match_parent</code></td><td>-1</td><td></td></tr>\n<tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr>\n</table>\n */\n public static final int buyButtonWidth=0x7f0100f4;\n /** <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int cameraBearing=0x7f010042;\n /** <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int cameraTargetLat=0x7f010043;\n /** <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int cameraTargetLng=0x7f010044;\n /** <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int cameraTilt=0x7f010045;\n /** <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int cameraZoom=0x7f010046;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int checkboxStyle=0x7f0100d4;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int checkedTextViewStyle=0x7f0100d5;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int circleCrop=0x7f010040;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int closeIcon=0x7f01005e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int closeItemLayout=0x7f010024;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int collapseContentDescription=0x7f0100e4;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int collapseIcon=0x7f0100e3;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int color=0x7f010033;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorAccent=0x7f0100c2;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorButtonNormal=0x7f0100c6;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorControlActivated=0x7f0100c4;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorControlHighlight=0x7f0100c5;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorControlNormal=0x7f0100c3;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorPrimary=0x7f0100c0;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorPrimaryDark=0x7f0100c1;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>dark</code></td><td>0</td><td></td></tr>\n<tr><td><code>light</code></td><td>1</td><td></td></tr>\n<tr><td><code>auto</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int colorScheme=0x7f010068;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int colorSwitchThumbNormal=0x7f0100c7;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int commitIcon=0x7f010063;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int contentInsetEnd=0x7f01001f;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int contentInsetLeft=0x7f010020;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int contentInsetRight=0x7f010021;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int contentInsetStart=0x7f01001e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int controlBackground=0x7f0100c8;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int customNavigationLayout=0x7f010017;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int defaultQueryHint=0x7f01005d;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int dialogPreferredPadding=0x7f01009a;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int dialogTheme=0x7f010099;\n /** <p>Must be one or more (separated by '|') of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>useLogo</code></td><td>0x1</td><td></td></tr>\n<tr><td><code>showHome</code></td><td>0x2</td><td></td></tr>\n<tr><td><code>homeAsUp</code></td><td>0x4</td><td></td></tr>\n<tr><td><code>showTitle</code></td><td>0x8</td><td></td></tr>\n<tr><td><code>showCustom</code></td><td>0x10</td><td></td></tr>\n<tr><td><code>disableHome</code></td><td>0x20</td><td></td></tr>\n</table>\n */\n public static final int displayOptions=0x7f01000d;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int divider=0x7f010013;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int dividerHorizontal=0x7f0100a7;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int dividerPadding=0x7f01003d;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int dividerVertical=0x7f0100a6;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int drawableSize=0x7f010035;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int drawerArrowStyle=0x7f010000;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int dropDownListViewStyle=0x7f0100b8;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int dropdownListPreferredItemHeight=0x7f01009d;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int editTextBackground=0x7f0100ae;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int editTextColor=0x7f0100ad;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int editTextStyle=0x7f0100d6;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int elevation=0x7f010022;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>production</code></td><td>1</td><td></td></tr>\n<tr><td><code>test</code></td><td>3</td><td></td></tr>\n<tr><td><code>sandbox</code></td><td>0</td><td></td></tr>\n<tr><td><code>strict_sandbox</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int environment=0x7f0100f0;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int expandActivityOverflowButtonDrawable=0x7f010026;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int externalRouteEnabledDrawable=0x7f010052;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>buyButton</code></td><td>1</td><td></td></tr>\n<tr><td><code>selectionDetails</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int fragmentMode=0x7f0100f2;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int fragmentStyle=0x7f0100f1;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int gapBetweenBars=0x7f010036;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int goIcon=0x7f01005f;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int height=0x7f010001;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int hideOnContentScroll=0x7f01001d;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int homeAsUpIndicator=0x7f01009f;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int homeLayout=0x7f010018;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int icon=0x7f010011;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int iconifiedByDefault=0x7f01005b;\n /** <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int imageAspectRatio=0x7f01003f;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>adjust_width</code></td><td>1</td><td></td></tr>\n<tr><td><code>adjust_height</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int imageAspectRatioAdjust=0x7f01003e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int indeterminateProgressStyle=0x7f01001a;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int initialActivityCount=0x7f010025;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int isLightTheme=0x7f010002;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int itemPadding=0x7f01001c;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int layout=0x7f01005a;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int listChoiceBackgroundIndicator=0x7f0100bf;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int listDividerAlertDialog=0x7f01009b;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int listItemLayout=0x7f01002e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int listLayout=0x7f01002b;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int listPopupWindowStyle=0x7f0100b9;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int listPreferredItemHeight=0x7f0100b3;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int listPreferredItemHeightLarge=0x7f0100b5;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int listPreferredItemHeightSmall=0x7f0100b4;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int listPreferredItemPaddingLeft=0x7f0100b6;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int listPreferredItemPaddingRight=0x7f0100b7;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int liteMode=0x7f010047;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int logo=0x7f010012;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int logoDescription=0x7f0100e7;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>normal</code></td><td>1</td><td></td></tr>\n<tr><td><code>satellite</code></td><td>2</td><td></td></tr>\n<tr><td><code>terrain</code></td><td>3</td><td></td></tr>\n<tr><td><code>hybrid</code></td><td>4</td><td></td></tr>\n</table>\n */\n public static final int mapType=0x7f010041;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int maskedWalletDetailsBackground=0x7f0100f9;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int maskedWalletDetailsButtonBackground=0x7f0100fb;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int maskedWalletDetailsButtonTextAppearance=0x7f0100fa;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int maskedWalletDetailsHeaderTextAppearance=0x7f0100f8;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>google_wallet_classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>google_wallet_monochrome</code></td><td>2</td><td></td></tr>\n<tr><td><code>android_pay</code></td><td>3</td><td></td></tr>\n<tr><td><code>classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>monochrome</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int maskedWalletDetailsLogoImageType=0x7f0100fd;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int maskedWalletDetailsLogoTextColor=0x7f0100fc;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int maskedWalletDetailsTextAppearance=0x7f0100f7;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int maxButtonHeight=0x7f0100e2;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int measureWithLargestChild=0x7f01003b;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRouteButtonStyle=0x7f010003;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRouteCastDrawable=0x7f010004;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRouteConnectingDrawable=0x7f010005;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRouteOffDrawable=0x7f010006;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRouteOnDrawable=0x7f010007;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRoutePauseDrawable=0x7f010008;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRoutePlayDrawable=0x7f010009;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int mediaRouteSettingsDrawable=0x7f01000a;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int multiChoiceItemLayout=0x7f01002c;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int navigationContentDescription=0x7f0100e6;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int navigationIcon=0x7f0100e5;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>normal</code></td><td>0</td><td></td></tr>\n<tr><td><code>listMode</code></td><td>1</td><td></td></tr>\n<tr><td><code>tabMode</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int navigationMode=0x7f01000c;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int overlapAnchor=0x7f010058;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int paddingEnd=0x7f0100eb;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int paddingStart=0x7f0100ea;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int panelBackground=0x7f0100bc;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int panelMenuListTheme=0x7f0100be;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int panelMenuListWidth=0x7f0100bd;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int popupMenuStyle=0x7f0100ab;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int popupTheme=0x7f010023;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int popupWindowStyle=0x7f0100ac;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int preserveIconSpacing=0x7f010057;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int progressBarPadding=0x7f01001b;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int progressBarStyle=0x7f010019;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int queryBackground=0x7f010065;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int queryHint=0x7f01005c;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int radioButtonStyle=0x7f0100d7;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int ratingBarStyle=0x7f0100d8;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n */\n public static final int scopeUris=0x7f010069;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int searchHintIcon=0x7f010061;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int searchIcon=0x7f010060;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int searchViewStyle=0x7f0100b2;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int selectableItemBackground=0x7f0100a3;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int selectableItemBackgroundBorderless=0x7f0100a4;\n /** <p>Must be one or more (separated by '|') of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>never</code></td><td>0</td><td></td></tr>\n<tr><td><code>ifRoom</code></td><td>1</td><td></td></tr>\n<tr><td><code>always</code></td><td>2</td><td></td></tr>\n<tr><td><code>withText</code></td><td>4</td><td></td></tr>\n<tr><td><code>collapseActionView</code></td><td>8</td><td></td></tr>\n</table>\n */\n public static final int showAsAction=0x7f010053;\n /** <p>Must be one or more (separated by '|') of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>beginning</code></td><td>1</td><td></td></tr>\n<tr><td><code>middle</code></td><td>2</td><td></td></tr>\n<tr><td><code>end</code></td><td>4</td><td></td></tr>\n</table>\n */\n public static final int showDividers=0x7f01003c;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int showText=0x7f010070;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int singleChoiceItemLayout=0x7f01002d;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int spinBars=0x7f010034;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int spinnerDropDownItemStyle=0x7f01009e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int spinnerStyle=0x7f0100d9;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int splitTrack=0x7f01006f;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int state_above_anchor=0x7f010059;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int submitBackground=0x7f010066;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int subtitle=0x7f01000e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int subtitleTextAppearance=0x7f0100dc;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int subtitleTextColor=0x7f0100e9;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int subtitleTextStyle=0x7f010010;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int suggestionRowLayout=0x7f010064;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int switchMinWidth=0x7f01006d;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int switchPadding=0x7f01006e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int switchStyle=0x7f0100da;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int switchTextAppearance=0x7f01006c;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n */\n public static final int textAllCaps=0x7f01002f;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int textAppearanceLargePopupMenu=0x7f010097;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int textAppearanceListItem=0x7f0100ba;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int textAppearanceListItemSmall=0x7f0100bb;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int textAppearanceSearchResultSubtitle=0x7f0100b0;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int textAppearanceSearchResultTitle=0x7f0100af;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int textAppearanceSmallPopupMenu=0x7f010098;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int textColorAlertDialogListItem=0x7f0100cd;\n /** <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n */\n public static final int textColorSearchUrl=0x7f0100b1;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int theme=0x7f0100ec;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int thickness=0x7f01003a;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int thumbTextPadding=0x7f01006b;\n /** <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int title=0x7f01000b;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int titleMarginBottom=0x7f0100e1;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int titleMarginEnd=0x7f0100df;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int titleMarginStart=0x7f0100de;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int titleMarginTop=0x7f0100e0;\n /** <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int titleMargins=0x7f0100dd;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int titleTextAppearance=0x7f0100db;\n /** <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int titleTextColor=0x7f0100e8;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int titleTextStyle=0x7f01000f;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int toolbarNavigationButtonStyle=0x7f0100aa;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int toolbarStyle=0x7f0100a9;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int track=0x7f01006a;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiCompass=0x7f010048;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiMapToolbar=0x7f010050;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiRotateGestures=0x7f010049;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiScrollGestures=0x7f01004a;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiTiltGestures=0x7f01004b;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiZoomControls=0x7f01004c;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int uiZoomGestures=0x7f01004d;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int useViewLifecycle=0x7f01004e;\n /** <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n */\n public static final int voiceIcon=0x7f010062;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowActionBar=0x7f010071;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowActionBarOverlay=0x7f010073;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowActionModeOverlay=0x7f010074;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowFixedHeightMajor=0x7f010078;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowFixedHeightMinor=0x7f010076;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowFixedWidthMajor=0x7f010075;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowFixedWidthMinor=0x7f010077;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowMinWidthMajor=0x7f010079;\n /** <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowMinWidthMinor=0x7f01007a;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int windowNoTitle=0x7f010072;\n /** <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>slide</code></td><td>1</td><td></td></tr>\n<tr><td><code>none</code></td><td>2</td><td></td></tr>\n</table>\n */\n public static final int windowTransitionStyle=0x7f010032;\n /** <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n */\n public static final int zOrderOnTop=0x7f01004f;\n }\n public static final class bool {\n public static final int abc_action_bar_embed_tabs=0x7f090002;\n public static final int abc_action_bar_embed_tabs_pre_jb=0x7f090000;\n public static final int abc_action_bar_expanded_action_views_exclusive=0x7f090003;\n public static final int abc_config_actionMenuItemAllCaps=0x7f090004;\n public static final int abc_config_allowActionMenuItemTextWithIcon=0x7f090001;\n public static final int abc_config_closeDialogWhenTouchOutside=0x7f090005;\n public static final int abc_config_showMenuShortcutsWhenKeyboardPresent=0x7f090006;\n }\n public static final class color {\n public static final int abc_background_cache_hint_selector_material_dark=0x7f0b0070;\n public static final int abc_background_cache_hint_selector_material_light=0x7f0b0071;\n public static final int abc_color_highlight_material=0x7f0b0072;\n public static final int abc_input_method_navigation_guard=0x7f0b0000;\n public static final int abc_primary_text_disable_only_material_dark=0x7f0b0073;\n public static final int abc_primary_text_disable_only_material_light=0x7f0b0074;\n public static final int abc_primary_text_material_dark=0x7f0b0075;\n public static final int abc_primary_text_material_light=0x7f0b0076;\n public static final int abc_search_url_text=0x7f0b0077;\n public static final int abc_search_url_text_normal=0x7f0b0001;\n public static final int abc_search_url_text_pressed=0x7f0b0002;\n public static final int abc_search_url_text_selected=0x7f0b0003;\n public static final int abc_secondary_text_material_dark=0x7f0b0078;\n public static final int abc_secondary_text_material_light=0x7f0b0079;\n public static final int accent_material_dark=0x7f0b0004;\n public static final int accent_material_light=0x7f0b0005;\n public static final int background_floating_material_dark=0x7f0b0006;\n public static final int background_floating_material_light=0x7f0b0007;\n public static final int background_material_dark=0x7f0b0008;\n public static final int background_material_light=0x7f0b0009;\n public static final int black=0x7f0b000a;\n public static final int blue_png=0x7f0b000b;\n public static final int bright_foreground_disabled_material_dark=0x7f0b000c;\n public static final int bright_foreground_disabled_material_light=0x7f0b000d;\n public static final int bright_foreground_inverse_material_dark=0x7f0b000e;\n public static final int bright_foreground_inverse_material_light=0x7f0b000f;\n public static final int bright_foreground_material_dark=0x7f0b0010;\n public static final int bright_foreground_material_light=0x7f0b0011;\n public static final int button_material_dark=0x7f0b0012;\n public static final int button_material_light=0x7f0b0013;\n public static final int color_green=0x7f0b0014;\n public static final int common_action_bar_splitter=0x7f0b0015;\n public static final int common_google_signin_btn_text_dark=0x7f0b007a;\n public static final int common_google_signin_btn_text_dark_default=0x7f0b0016;\n public static final int common_google_signin_btn_text_dark_disabled=0x7f0b0017;\n public static final int common_google_signin_btn_text_dark_focused=0x7f0b0018;\n public static final int common_google_signin_btn_text_dark_pressed=0x7f0b0019;\n public static final int common_google_signin_btn_text_light=0x7f0b007b;\n public static final int common_google_signin_btn_text_light_default=0x7f0b001a;\n public static final int common_google_signin_btn_text_light_disabled=0x7f0b001b;\n public static final int common_google_signin_btn_text_light_focused=0x7f0b001c;\n public static final int common_google_signin_btn_text_light_pressed=0x7f0b001d;\n public static final int common_plus_signin_btn_text_dark=0x7f0b007c;\n public static final int common_plus_signin_btn_text_dark_default=0x7f0b001e;\n public static final int common_plus_signin_btn_text_dark_disabled=0x7f0b001f;\n public static final int common_plus_signin_btn_text_dark_focused=0x7f0b0020;\n public static final int common_plus_signin_btn_text_dark_pressed=0x7f0b0021;\n public static final int common_plus_signin_btn_text_light=0x7f0b007d;\n public static final int common_plus_signin_btn_text_light_default=0x7f0b0022;\n public static final int common_plus_signin_btn_text_light_disabled=0x7f0b0023;\n public static final int common_plus_signin_btn_text_light_focused=0x7f0b0024;\n public static final int common_plus_signin_btn_text_light_pressed=0x7f0b0025;\n public static final int dark_brown=0x7f0b0026;\n public static final int dark_gray=0x7f0b0027;\n public static final int dark_mask=0x7f0b0028;\n public static final int dim_foreground_disabled_material_dark=0x7f0b0029;\n public static final int dim_foreground_disabled_material_light=0x7f0b002a;\n public static final int dim_foreground_material_dark=0x7f0b002b;\n public static final int dim_foreground_material_light=0x7f0b002c;\n public static final int foreground_material_dark=0x7f0b002d;\n public static final int foreground_material_light=0x7f0b002e;\n public static final int gray=0x7f0b002f;\n public static final int gray_png=0x7f0b0030;\n public static final int gray_verydark=0x7f0b0031;\n public static final int highlighted_text_material_dark=0x7f0b0032;\n public static final int highlighted_text_material_light=0x7f0b0033;\n public static final int hint_foreground_material_dark=0x7f0b0034;\n public static final int hint_foreground_material_light=0x7f0b0035;\n public static final int light_blue=0x7f0b0036;\n public static final int light_gray=0x7f0b0037;\n public static final int line_separator=0x7f0b0038;\n public static final int material_blue_grey_800=0x7f0b0039;\n public static final int material_blue_grey_900=0x7f0b003a;\n public static final int material_blue_grey_950=0x7f0b003b;\n public static final int material_deep_teal_200=0x7f0b003c;\n public static final int material_deep_teal_500=0x7f0b003d;\n public static final int material_grey_100=0x7f0b003e;\n public static final int material_grey_300=0x7f0b003f;\n public static final int material_grey_50=0x7f0b0040;\n public static final int material_grey_600=0x7f0b0041;\n public static final int material_grey_800=0x7f0b0042;\n public static final int material_grey_850=0x7f0b0043;\n public static final int material_grey_900=0x7f0b0044;\n public static final int place_autocomplete_prediction_primary_text=0x7f0b0045;\n public static final int place_autocomplete_prediction_primary_text_highlight=0x7f0b0046;\n public static final int place_autocomplete_prediction_secondary_text=0x7f0b0047;\n public static final int place_autocomplete_search_hint=0x7f0b0048;\n public static final int place_autocomplete_search_text=0x7f0b0049;\n public static final int place_autocomplete_separator=0x7f0b004a;\n public static final int primary_dark_material_dark=0x7f0b004b;\n public static final int primary_dark_material_light=0x7f0b004c;\n public static final int primary_material_dark=0x7f0b004d;\n public static final int primary_material_light=0x7f0b004e;\n public static final int primary_text_default_material_dark=0x7f0b004f;\n public static final int primary_text_default_material_light=0x7f0b0050;\n public static final int primary_text_disabled_material_dark=0x7f0b0051;\n public static final int primary_text_disabled_material_light=0x7f0b0052;\n public static final int purple=0x7f0b0053;\n public static final int red=0x7f0b0054;\n public static final int ripple_material_dark=0x7f0b0055;\n public static final int ripple_material_light=0x7f0b0056;\n public static final int secondary_text_default_material_dark=0x7f0b0057;\n public static final int secondary_text_default_material_light=0x7f0b0058;\n public static final int secondary_text_disabled_material_dark=0x7f0b0059;\n public static final int secondary_text_disabled_material_light=0x7f0b005a;\n public static final int switch_thumb_disabled_material_dark=0x7f0b005b;\n public static final int switch_thumb_disabled_material_light=0x7f0b005c;\n public static final int switch_thumb_material_dark=0x7f0b007e;\n public static final int switch_thumb_material_light=0x7f0b007f;\n public static final int switch_thumb_normal_material_dark=0x7f0b005d;\n public static final int switch_thumb_normal_material_light=0x7f0b005e;\n public static final int text_color=0x7f0b005f;\n public static final int wallet_bright_foreground_disabled_holo_light=0x7f0b0060;\n public static final int wallet_bright_foreground_holo_dark=0x7f0b0061;\n public static final int wallet_bright_foreground_holo_light=0x7f0b0062;\n public static final int wallet_dim_foreground_disabled_holo_dark=0x7f0b0063;\n public static final int wallet_dim_foreground_holo_dark=0x7f0b0064;\n public static final int wallet_dim_foreground_inverse_disabled_holo_dark=0x7f0b0065;\n public static final int wallet_dim_foreground_inverse_holo_dark=0x7f0b0066;\n public static final int wallet_highlighted_text_holo_dark=0x7f0b0067;\n public static final int wallet_highlighted_text_holo_light=0x7f0b0068;\n public static final int wallet_hint_foreground_holo_dark=0x7f0b0069;\n public static final int wallet_hint_foreground_holo_light=0x7f0b006a;\n public static final int wallet_holo_blue_light=0x7f0b006b;\n public static final int wallet_link_text_light=0x7f0b006c;\n public static final int wallet_primary_text_holo_light=0x7f0b0080;\n public static final int wallet_secondary_text_holo_dark=0x7f0b0081;\n public static final int white=0x7f0b006d;\n public static final int wood_brown=0x7f0b006e;\n public static final int yellow=0x7f0b006f;\n }\n public static final class dimen {\n public static final int abc_action_bar_content_inset_material=0x7f07000b;\n public static final int abc_action_bar_default_height_material=0x7f070001;\n public static final int abc_action_bar_default_padding_end_material=0x7f07000c;\n public static final int abc_action_bar_default_padding_start_material=0x7f07000d;\n public static final int abc_action_bar_icon_vertical_padding_material=0x7f070010;\n public static final int abc_action_bar_overflow_padding_end_material=0x7f070011;\n public static final int abc_action_bar_overflow_padding_start_material=0x7f070012;\n public static final int abc_action_bar_progress_bar_size=0x7f070002;\n public static final int abc_action_bar_stacked_max_height=0x7f070013;\n public static final int abc_action_bar_stacked_tab_max_width=0x7f070014;\n public static final int abc_action_bar_subtitle_bottom_margin_material=0x7f070015;\n public static final int abc_action_bar_subtitle_top_margin_material=0x7f070016;\n public static final int abc_action_button_min_height_material=0x7f070017;\n public static final int abc_action_button_min_width_material=0x7f070018;\n public static final int abc_action_button_min_width_overflow_material=0x7f070019;\n public static final int abc_alert_dialog_button_bar_height=0x7f070000;\n public static final int abc_button_inset_horizontal_material=0x7f07001a;\n public static final int abc_button_inset_vertical_material=0x7f07001b;\n public static final int abc_button_padding_horizontal_material=0x7f07001c;\n public static final int abc_button_padding_vertical_material=0x7f07001d;\n public static final int abc_config_prefDialogWidth=0x7f070005;\n public static final int abc_control_corner_material=0x7f07001e;\n public static final int abc_control_inset_material=0x7f07001f;\n public static final int abc_control_padding_material=0x7f070020;\n public static final int abc_dialog_list_padding_vertical_material=0x7f070021;\n public static final int abc_dialog_min_width_major=0x7f070022;\n public static final int abc_dialog_min_width_minor=0x7f070023;\n public static final int abc_dialog_padding_material=0x7f070024;\n public static final int abc_dialog_padding_top_material=0x7f070025;\n public static final int abc_disabled_alpha_material_dark=0x7f070026;\n public static final int abc_disabled_alpha_material_light=0x7f070027;\n public static final int abc_dropdownitem_icon_width=0x7f070028;\n public static final int abc_dropdownitem_text_padding_left=0x7f070029;\n public static final int abc_dropdownitem_text_padding_right=0x7f07002a;\n public static final int abc_edit_text_inset_bottom_material=0x7f07002b;\n public static final int abc_edit_text_inset_horizontal_material=0x7f07002c;\n public static final int abc_edit_text_inset_top_material=0x7f07002d;\n public static final int abc_floating_window_z=0x7f07002e;\n public static final int abc_list_item_padding_horizontal_material=0x7f07002f;\n public static final int abc_panel_menu_list_width=0x7f070030;\n public static final int abc_search_view_preferred_width=0x7f070031;\n public static final int abc_search_view_text_min_width=0x7f070006;\n public static final int abc_switch_padding=0x7f07000f;\n public static final int abc_text_size_body_1_material=0x7f070032;\n public static final int abc_text_size_body_2_material=0x7f070033;\n public static final int abc_text_size_button_material=0x7f070034;\n public static final int abc_text_size_caption_material=0x7f070035;\n public static final int abc_text_size_display_1_material=0x7f070036;\n public static final int abc_text_size_display_2_material=0x7f070037;\n public static final int abc_text_size_display_3_material=0x7f070038;\n public static final int abc_text_size_display_4_material=0x7f070039;\n public static final int abc_text_size_headline_material=0x7f07003a;\n public static final int abc_text_size_large_material=0x7f07003b;\n public static final int abc_text_size_medium_material=0x7f07003c;\n public static final int abc_text_size_menu_material=0x7f07003d;\n public static final int abc_text_size_small_material=0x7f07003e;\n public static final int abc_text_size_subhead_material=0x7f07003f;\n public static final int abc_text_size_subtitle_material_toolbar=0x7f070003;\n public static final int abc_text_size_title_material=0x7f070040;\n public static final int abc_text_size_title_material_toolbar=0x7f070004;\n public static final int dialog_fixed_height_major=0x7f070007;\n public static final int dialog_fixed_height_minor=0x7f070008;\n public static final int dialog_fixed_width_major=0x7f070009;\n public static final int dialog_fixed_width_minor=0x7f07000a;\n public static final int disabled_alpha_material_dark=0x7f070041;\n public static final int disabled_alpha_material_light=0x7f070042;\n public static final int highlight_alpha_material_colored=0x7f070043;\n public static final int highlight_alpha_material_dark=0x7f070044;\n public static final int highlight_alpha_material_light=0x7f070045;\n public static final int mr_media_route_controller_art_max_height=0x7f07000e;\n public static final int notification_large_icon_height=0x7f070046;\n public static final int notification_large_icon_width=0x7f070047;\n public static final int notification_subtext_size=0x7f070048;\n public static final int place_autocomplete_button_padding=0x7f070049;\n public static final int place_autocomplete_powered_by_google_height=0x7f07004a;\n public static final int place_autocomplete_powered_by_google_start=0x7f07004b;\n public static final int place_autocomplete_prediction_height=0x7f07004c;\n public static final int place_autocomplete_prediction_horizontal_margin=0x7f07004d;\n public static final int place_autocomplete_prediction_primary_text=0x7f07004e;\n public static final int place_autocomplete_prediction_secondary_text=0x7f07004f;\n public static final int place_autocomplete_progress_horizontal_margin=0x7f070050;\n public static final int place_autocomplete_progress_size=0x7f070051;\n public static final int place_autocomplete_separator_start=0x7f070052;\n }\n public static final class drawable {\n public static final int abc_ab_share_pack_mtrl_alpha=0x7f020000;\n public static final int abc_action_bar_item_background_material=0x7f020001;\n public static final int abc_btn_borderless_material=0x7f020002;\n public static final int abc_btn_check_material=0x7f020003;\n public static final int abc_btn_check_to_on_mtrl_000=0x7f020004;\n public static final int abc_btn_check_to_on_mtrl_015=0x7f020005;\n public static final int abc_btn_colored_material=0x7f020006;\n public static final int abc_btn_default_mtrl_shape=0x7f020007;\n public static final int abc_btn_radio_material=0x7f020008;\n public static final int abc_btn_radio_to_on_mtrl_000=0x7f020009;\n public static final int abc_btn_radio_to_on_mtrl_015=0x7f02000a;\n public static final int abc_btn_rating_star_off_mtrl_alpha=0x7f02000b;\n public static final int abc_btn_rating_star_on_mtrl_alpha=0x7f02000c;\n public static final int abc_btn_switch_to_on_mtrl_00001=0x7f02000d;\n public static final int abc_btn_switch_to_on_mtrl_00012=0x7f02000e;\n public static final int abc_cab_background_internal_bg=0x7f02000f;\n public static final int abc_cab_background_top_material=0x7f020010;\n public static final int abc_cab_background_top_mtrl_alpha=0x7f020011;\n public static final int abc_control_background_material=0x7f020012;\n public static final int abc_dialog_material_background_dark=0x7f020013;\n public static final int abc_dialog_material_background_light=0x7f020014;\n public static final int abc_edit_text_material=0x7f020015;\n public static final int abc_ic_ab_back_mtrl_am_alpha=0x7f020016;\n public static final int abc_ic_clear_mtrl_alpha=0x7f020017;\n public static final int abc_ic_commit_search_api_mtrl_alpha=0x7f020018;\n public static final int abc_ic_go_search_api_mtrl_alpha=0x7f020019;\n public static final int abc_ic_menu_copy_mtrl_am_alpha=0x7f02001a;\n public static final int abc_ic_menu_cut_mtrl_alpha=0x7f02001b;\n public static final int abc_ic_menu_moreoverflow_mtrl_alpha=0x7f02001c;\n public static final int abc_ic_menu_paste_mtrl_am_alpha=0x7f02001d;\n public static final int abc_ic_menu_selectall_mtrl_alpha=0x7f02001e;\n public static final int abc_ic_menu_share_mtrl_alpha=0x7f02001f;\n public static final int abc_ic_search_api_mtrl_alpha=0x7f020020;\n public static final int abc_ic_voice_search_api_mtrl_alpha=0x7f020021;\n public static final int abc_item_background_holo_dark=0x7f020022;\n public static final int abc_item_background_holo_light=0x7f020023;\n public static final int abc_list_divider_mtrl_alpha=0x7f020024;\n public static final int abc_list_focused_holo=0x7f020025;\n public static final int abc_list_longpressed_holo=0x7f020026;\n public static final int abc_list_pressed_holo_dark=0x7f020027;\n public static final int abc_list_pressed_holo_light=0x7f020028;\n public static final int abc_list_selector_background_transition_holo_dark=0x7f020029;\n public static final int abc_list_selector_background_transition_holo_light=0x7f02002a;\n public static final int abc_list_selector_disabled_holo_dark=0x7f02002b;\n public static final int abc_list_selector_disabled_holo_light=0x7f02002c;\n public static final int abc_list_selector_holo_dark=0x7f02002d;\n public static final int abc_list_selector_holo_light=0x7f02002e;\n public static final int abc_menu_hardkey_panel_mtrl_mult=0x7f02002f;\n public static final int abc_popup_background_mtrl_mult=0x7f020030;\n public static final int abc_ratingbar_full_material=0x7f020031;\n public static final int abc_spinner_mtrl_am_alpha=0x7f020032;\n public static final int abc_spinner_textfield_background_material=0x7f020033;\n public static final int abc_switch_thumb_material=0x7f020034;\n public static final int abc_switch_track_mtrl_alpha=0x7f020035;\n public static final int abc_tab_indicator_material=0x7f020036;\n public static final int abc_tab_indicator_mtrl_alpha=0x7f020037;\n public static final int abc_text_cursor_material=0x7f020038;\n public static final int abc_textfield_activated_mtrl_alpha=0x7f020039;\n public static final int abc_textfield_default_mtrl_alpha=0x7f02003a;\n public static final int abc_textfield_search_activated_mtrl_alpha=0x7f02003b;\n public static final int abc_textfield_search_default_mtrl_alpha=0x7f02003c;\n public static final int abc_textfield_search_material=0x7f02003d;\n public static final int bg=0x7f02003e;\n public static final int brown_shadow_background=0x7f02003f;\n public static final int camera=0x7f020040;\n public static final int cart=0x7f020041;\n public static final int cast_ic_notification_0=0x7f020042;\n public static final int cast_ic_notification_1=0x7f020043;\n public static final int cast_ic_notification_2=0x7f020044;\n public static final int cast_ic_notification_connecting=0x7f020045;\n public static final int cast_ic_notification_on=0x7f020046;\n public static final int circle_background=0x7f020047;\n public static final int circle_red_background=0x7f020048;\n public static final int circle_translucent_background=0x7f020049;\n public static final int circle_yellow_background=0x7f02004a;\n public static final int common_full_open_on_phone=0x7f02004b;\n public static final int common_google_signin_btn_icon_dark=0x7f02004c;\n public static final int common_google_signin_btn_icon_dark_disabled=0x7f02004d;\n public static final int common_google_signin_btn_icon_dark_focused=0x7f02004e;\n public static final int common_google_signin_btn_icon_dark_normal=0x7f02004f;\n public static final int common_google_signin_btn_icon_dark_pressed=0x7f020050;\n public static final int common_google_signin_btn_icon_light=0x7f020051;\n public static final int common_google_signin_btn_icon_light_disabled=0x7f020052;\n public static final int common_google_signin_btn_icon_light_focused=0x7f020053;\n public static final int common_google_signin_btn_icon_light_normal=0x7f020054;\n public static final int common_google_signin_btn_icon_light_pressed=0x7f020055;\n public static final int common_google_signin_btn_text_dark=0x7f020056;\n public static final int common_google_signin_btn_text_dark_disabled=0x7f020057;\n public static final int common_google_signin_btn_text_dark_focused=0x7f020058;\n public static final int common_google_signin_btn_text_dark_normal=0x7f020059;\n public static final int common_google_signin_btn_text_dark_pressed=0x7f02005a;\n public static final int common_google_signin_btn_text_light=0x7f02005b;\n public static final int common_google_signin_btn_text_light_disabled=0x7f02005c;\n public static final int common_google_signin_btn_text_light_focused=0x7f02005d;\n public static final int common_google_signin_btn_text_light_normal=0x7f02005e;\n public static final int common_google_signin_btn_text_light_pressed=0x7f02005f;\n public static final int common_ic_googleplayservices=0x7f020060;\n public static final int common_plus_signin_btn_icon_dark=0x7f020061;\n public static final int common_plus_signin_btn_icon_dark_disabled=0x7f020062;\n public static final int common_plus_signin_btn_icon_dark_focused=0x7f020063;\n public static final int common_plus_signin_btn_icon_dark_normal=0x7f020064;\n public static final int common_plus_signin_btn_icon_dark_pressed=0x7f020065;\n public static final int common_plus_signin_btn_icon_light=0x7f020066;\n public static final int common_plus_signin_btn_icon_light_disabled=0x7f020067;\n public static final int common_plus_signin_btn_icon_light_focused=0x7f020068;\n public static final int common_plus_signin_btn_icon_light_normal=0x7f020069;\n public static final int common_plus_signin_btn_icon_light_pressed=0x7f02006a;\n public static final int common_plus_signin_btn_text_dark=0x7f02006b;\n public static final int common_plus_signin_btn_text_dark_disabled=0x7f02006c;\n public static final int common_plus_signin_btn_text_dark_focused=0x7f02006d;\n public static final int common_plus_signin_btn_text_dark_normal=0x7f02006e;\n public static final int common_plus_signin_btn_text_dark_pressed=0x7f02006f;\n public static final int common_plus_signin_btn_text_light=0x7f020070;\n public static final int common_plus_signin_btn_text_light_disabled=0x7f020071;\n public static final int common_plus_signin_btn_text_light_focused=0x7f020072;\n public static final int common_plus_signin_btn_text_light_normal=0x7f020073;\n public static final int common_plus_signin_btn_text_light_pressed=0x7f020074;\n public static final int cover=0x7f020075;\n public static final int dark_shadow_background=0x7f020076;\n public static final int darkgray_but_background=0x7f020077;\n public static final int gray_but_background=0x7f020078;\n public static final int gray_shadow_background=0x7f020079;\n public static final int green_but_background=0x7f02007a;\n public static final int ic_cast_dark=0x7f02007b;\n public static final int ic_cast_disabled_light=0x7f02007c;\n public static final int ic_cast_light=0x7f02007d;\n public static final int ic_cast_off_light=0x7f02007e;\n public static final int ic_cast_on_0_light=0x7f02007f;\n public static final int ic_cast_on_1_light=0x7f020080;\n public static final int ic_cast_on_2_light=0x7f020081;\n public static final int ic_cast_on_light=0x7f020082;\n public static final int ic_launcher=0x7f020083;\n public static final int ic_media_pause=0x7f020084;\n public static final int ic_media_play=0x7f020085;\n public static final int ic_media_route_disabled_mono_dark=0x7f020086;\n public static final int ic_media_route_off_mono_dark=0x7f020087;\n public static final int ic_media_route_on_0_mono_dark=0x7f020088;\n public static final int ic_media_route_on_1_mono_dark=0x7f020089;\n public static final int ic_media_route_on_2_mono_dark=0x7f02008a;\n public static final int ic_media_route_on_mono_dark=0x7f02008b;\n public static final int ic_pause_dark=0x7f02008c;\n public static final int ic_pause_light=0x7f02008d;\n public static final int ic_play_dark=0x7f02008e;\n public static final int ic_play_light=0x7f02008f;\n public static final int ic_plusone_medium_off_client=0x7f020090;\n public static final int ic_plusone_small_off_client=0x7f020091;\n public static final int ic_plusone_standard_off_client=0x7f020092;\n public static final int ic_plusone_tall_off_client=0x7f020093;\n public static final int ic_setting_dark=0x7f020094;\n public static final int ic_setting_light=0x7f020095;\n public static final int icon_title=0x7f020096;\n public static final int l_0=0x7f020097;\n public static final int l_1=0x7f020098;\n public static final int l_2=0x7f020099;\n public static final int l_3=0x7f02009a;\n public static final int l_4=0x7f02009b;\n public static final int l_5=0x7f02009c;\n public static final int l_6=0x7f02009d;\n public static final int l_7=0x7f02009e;\n public static final int loading0=0x7f02009f;\n public static final int loading_gif=0x7f0200a0;\n public static final int mego_logo=0x7f0200a1;\n public static final int menu=0x7f0200a2;\n public static final int menu_dropdown=0x7f0200a3;\n public static final int mr_ic_cast_dark=0x7f0200a4;\n public static final int mr_ic_cast_light=0x7f0200a5;\n public static final int mr_ic_media_route_connecting_mono_dark=0x7f0200a6;\n public static final int mr_ic_media_route_connecting_mono_light=0x7f0200a7;\n public static final int mr_ic_media_route_mono_dark=0x7f0200a8;\n public static final int mr_ic_media_route_mono_light=0x7f0200a9;\n public static final int mr_ic_pause_dark=0x7f0200aa;\n public static final int mr_ic_pause_light=0x7f0200ab;\n public static final int mr_ic_play_dark=0x7f0200ac;\n public static final int mr_ic_play_light=0x7f0200ad;\n public static final int mr_ic_settings_dark=0x7f0200ae;\n public static final int mr_ic_settings_light=0x7f0200af;\n public static final int notif_background=0x7f0200b0;\n public static final int notification_template_icon_bg=0x7f0200bb;\n public static final int places_ic_clear=0x7f0200b1;\n public static final int places_ic_search=0x7f0200b2;\n public static final int powered_by_google_dark=0x7f0200b3;\n public static final int powered_by_google_light=0x7f0200b4;\n public static final int red_shadow_background=0x7f0200b5;\n public static final int shadow_background=0x7f0200b6;\n public static final int splash=0x7f0200b7;\n public static final int title_gradient=0x7f0200b8;\n public static final int white_shadow_background=0x7f0200b9;\n public static final int yellow_shadow_background=0x7f0200ba;\n }\n public static final class id {\n public static final int action0=0x7f0c00ec;\n public static final int action_bar=0x7f0c0065;\n public static final int action_bar_activity_content=0x7f0c0000;\n public static final int action_bar_container=0x7f0c0064;\n public static final int action_bar_root=0x7f0c0060;\n public static final int action_bar_spinner=0x7f0c0001;\n public static final int action_bar_subtitle=0x7f0c0049;\n public static final int action_bar_title=0x7f0c0048;\n public static final int action_context_bar=0x7f0c0066;\n public static final int action_divider=0x7f0c00f0;\n public static final int action_menu_divider=0x7f0c0002;\n public static final int action_menu_presenter=0x7f0c0003;\n public static final int action_mode_bar=0x7f0c0062;\n public static final int action_mode_bar_stub=0x7f0c0061;\n public static final int action_mode_close_button=0x7f0c004a;\n public static final int activity_chooser_view_content=0x7f0c004b;\n public static final int adjust_height=0x7f0c001d;\n public static final int adjust_width=0x7f0c001e;\n public static final int alertTitle=0x7f0c0055;\n public static final int always=0x7f0c0022;\n public static final int android_pay=0x7f0c0047;\n public static final int android_pay_dark=0x7f0c003e;\n public static final int android_pay_light=0x7f0c003f;\n public static final int android_pay_light_with_border=0x7f0c0040;\n public static final int art=0x7f0c00e4;\n public static final int auto=0x7f0c002a;\n public static final int beginning=0x7f0c001a;\n public static final int book_now=0x7f0c0037;\n public static final int butSave=0x7f0c008b;\n public static final int butShare=0x7f0c008c;\n public static final int but_back=0x7f0c009f;\n public static final int but_create=0x7f0c00a6;\n public static final int but_forgot=0x7f0c009e;\n public static final int but_next=0x7f0c009d;\n public static final int but_no=0x7f0c008e;\n public static final int but_prev=0x7f0c00d7;\n public static final int but_pull=0x7f0c00dd;\n public static final int but_save=0x7f0c0099;\n public static final int but_save_1=0x7f0c00a4;\n public static final int but_yes=0x7f0c008f;\n public static final int buttonPanel=0x7f0c005b;\n public static final int buttons=0x7f0c00e9;\n public static final int buyButton=0x7f0c0034;\n public static final int buy_now=0x7f0c0038;\n public static final int buy_with=0x7f0c0039;\n public static final int buy_with_google=0x7f0c003a;\n public static final int cancel_action=0x7f0c00ed;\n public static final int cast_notification_id=0x7f0c0004;\n public static final int checkbox=0x7f0c005d;\n public static final int chronometer=0x7f0c00f3;\n public static final int classic=0x7f0c0041;\n public static final int collapseActionView=0x7f0c0023;\n public static final int contentPanel=0x7f0c0056;\n public static final int custom=0x7f0c005a;\n public static final int customPanel=0x7f0c0059;\n public static final int dark=0x7f0c002b;\n public static final int decor_content_parent=0x7f0c0063;\n public static final int default_activity_button=0x7f0c004e;\n public static final int default_control_frame=0x7f0c00e3;\n public static final int dialogMessage=0x7f0c008d;\n public static final int disableHome=0x7f0c000d;\n public static final int disconnect=0x7f0c00ea;\n public static final int donate_with=0x7f0c003b;\n public static final int donate_with_google=0x7f0c003c;\n public static final int edit_address=0x7f0c00ce;\n public static final int edit_city=0x7f0c00d4;\n public static final int edit_code=0x7f0c00a3;\n public static final int edit_confirm=0x7f0c009c;\n public static final int edit_confirm_password=0x7f0c00ab;\n public static final int edit_country=0x7f0c00d0;\n public static final int edit_email=0x7f0c0094;\n public static final int edit_email_1=0x7f0c00a1;\n public static final int edit_name=0x7f0c00cb;\n public static final int edit_new_password=0x7f0c00a9;\n public static final int edit_password=0x7f0c0096;\n public static final int edit_phone=0x7f0c00cc;\n public static final int edit_pincode=0x7f0c00d6;\n public static final int edit_query=0x7f0c0067;\n public static final int edit_repassword=0x7f0c0098;\n public static final int edit_state=0x7f0c00d2;\n public static final int end=0x7f0c001b;\n public static final int end_padder=0x7f0c00f8;\n public static final int expand_activities_button=0x7f0c004c;\n public static final int expanded_menu=0x7f0c005c;\n public static final int google_wallet_classic=0x7f0c0042;\n public static final int google_wallet_grayscale=0x7f0c0043;\n public static final int google_wallet_monochrome=0x7f0c0044;\n public static final int grayscale=0x7f0c0045;\n public static final int holo_dark=0x7f0c002e;\n public static final int holo_light=0x7f0c002f;\n public static final int home=0x7f0c0005;\n public static final int homeAsUp=0x7f0c000e;\n public static final int hybrid=0x7f0c001f;\n public static final int icon=0x7f0c0050;\n public static final int icon_only=0x7f0c0027;\n public static final int ifRoom=0x7f0c0024;\n public static final int image=0x7f0c004d;\n public static final int info=0x7f0c00f7;\n public static final int iv_head_cart=0x7f0c0077;\n public static final int iv_head_menu=0x7f0c0075;\n public static final int iv_head_title=0x7f0c0076;\n public static final int iv_loading=0x7f0c00b1;\n public static final int iv_loading_bg=0x7f0c00b0;\n public static final int light=0x7f0c002c;\n public static final int line1=0x7f0c00f1;\n public static final int line3=0x7f0c00f5;\n public static final int listMode=0x7f0c000a;\n public static final int list_item=0x7f0c004f;\n public static final int ll_body=0x7f0c0079;\n public static final int ll_container=0x7f0c0090;\n public static final int ll_crumbs=0x7f0c00c5;\n public static final int ll_dialog=0x7f0c007d;\n public static final int ll_head=0x7f0c0074;\n public static final int ll_menu_container=0x7f0c0085;\n public static final int ll_more_container=0x7f0c0089;\n public static final int ll_partitionC=0x7f0c0081;\n public static final int ll_partitionLeft=0x7f0c0082;\n public static final int ll_partitionRight=0x7f0c0083;\n public static final int ll_preference_container=0x7f0c0087;\n public static final int logo_only=0x7f0c003d;\n public static final int match_parent=0x7f0c0036;\n public static final int media_actions=0x7f0c00ef;\n public static final int media_route_control_frame=0x7f0c00e2;\n public static final int media_route_list=0x7f0c00de;\n public static final int media_route_volume_layout=0x7f0c00e7;\n public static final int media_route_volume_slider=0x7f0c00e8;\n public static final int middle=0x7f0c001c;\n public static final int monochrome=0x7f0c0046;\n public static final int multiply=0x7f0c0014;\n public static final int never=0x7f0c0025;\n public static final int none=0x7f0c000f;\n public static final int normal=0x7f0c000b;\n public static final int parentPanel=0x7f0c0052;\n public static final int place_autocomplete_clear_button=0x7f0c00fb;\n public static final int place_autocomplete_powered_by_google=0x7f0c00fd;\n public static final int place_autocomplete_prediction_primary_text=0x7f0c00ff;\n public static final int place_autocomplete_prediction_secondary_text=0x7f0c0100;\n public static final int place_autocomplete_progress=0x7f0c00fe;\n public static final int place_autocomplete_search_button=0x7f0c00f9;\n public static final int place_autocomplete_search_input=0x7f0c00fa;\n public static final int place_autocomplete_separator=0x7f0c00fc;\n public static final int play_pause=0x7f0c00e5;\n public static final int poweredby=0x7f0c00b2;\n public static final int production=0x7f0c0030;\n public static final int progress_circular=0x7f0c0006;\n public static final int progress_horizontal=0x7f0c0007;\n public static final int radio=0x7f0c005f;\n public static final int rl_head=0x7f0c00a7;\n public static final int rl_loading_c=0x7f0c00af;\n public static final int route_name=0x7f0c00e0;\n public static final int sandbox=0x7f0c0031;\n public static final int satellite=0x7f0c0020;\n public static final int screen=0x7f0c0015;\n public static final int scrollView=0x7f0c0057;\n public static final int search_badge=0x7f0c0069;\n public static final int search_bar=0x7f0c0068;\n public static final int search_button=0x7f0c006a;\n public static final int search_close_btn=0x7f0c006f;\n public static final int search_edit_frame=0x7f0c006b;\n public static final int search_go_btn=0x7f0c0071;\n public static final int search_mag_icon=0x7f0c006c;\n public static final int search_plate=0x7f0c006d;\n public static final int search_src_text=0x7f0c006e;\n public static final int search_voice_btn=0x7f0c0072;\n public static final int select_dialog_listview=0x7f0c0073;\n public static final int selectionDetails=0x7f0c0035;\n public static final int settings=0x7f0c00e1;\n public static final int shortcut=0x7f0c005e;\n public static final int showCustom=0x7f0c0010;\n public static final int showHome=0x7f0c0011;\n public static final int showTitle=0x7f0c0012;\n public static final int slide=0x7f0c0019;\n public static final int spin_city=0x7f0c00dc;\n public static final int spin_country=0x7f0c00da;\n public static final int spin_dialog=0x7f0c007f;\n public static final int spin_state=0x7f0c00db;\n public static final int split_action_bar=0x7f0c0008;\n public static final int src_atop=0x7f0c0016;\n public static final int src_in=0x7f0c0017;\n public static final int src_over=0x7f0c0018;\n public static final int standard=0x7f0c0028;\n public static final int status_bar_latest_event_content=0x7f0c00ee;\n public static final int stop=0x7f0c00eb;\n public static final int strict_sandbox=0x7f0c0032;\n public static final int submit_area=0x7f0c0070;\n public static final int subtitle=0x7f0c00e6;\n public static final int tabMode=0x7f0c000c;\n public static final int terrain=0x7f0c0021;\n public static final int test=0x7f0c0033;\n public static final int text=0x7f0c00f6;\n public static final int text2=0x7f0c00f4;\n public static final int textSpacerNoButtons=0x7f0c0058;\n public static final int textView1=0x7f0c0101;\n public static final int time=0x7f0c00f2;\n public static final int title=0x7f0c0051;\n public static final int title_bar=0x7f0c00df;\n public static final int title_template=0x7f0c0054;\n public static final int topPanel=0x7f0c0053;\n public static final int tv_about=0x7f0c00c1;\n public static final int tv_alerts=0x7f0c00bb;\n public static final int tv_bar=0x7f0c007c;\n public static final int tv_cart_notif=0x7f0c0078;\n public static final int tv_crumbs_cart=0x7f0c00c6;\n public static final int tv_crumbs_checkout=0x7f0c00c7;\n public static final int tv_crumbs_confirm=0x7f0c00c8;\n public static final int tv_crumbs_payment=0x7f0c00c9;\n public static final int tv_dialog_but=0x7f0c0080;\n public static final int tv_dialog_label=0x7f0c007e;\n public static final int tv_email=0x7f0c00ac;\n public static final int tv_forgot=0x7f0c00b7;\n public static final int tv_label_account=0x7f0c00b4;\n public static final int tv_label_accountinfo=0x7f0c00a5;\n public static final int tv_label_address=0x7f0c00cd;\n public static final int tv_label_as=0x7f0c00b3;\n public static final int tv_label_city=0x7f0c00d3;\n public static final int tv_label_code=0x7f0c00a2;\n public static final int tv_label_confirm=0x7f0c009b;\n public static final int tv_label_confirm_password=0x7f0c00aa;\n public static final int tv_label_country=0x7f0c00cf;\n public static final int tv_label_email=0x7f0c0093;\n public static final int tv_label_email_1=0x7f0c00a0;\n public static final int tv_label_info=0x7f0c009a;\n public static final int tv_label_name=0x7f0c00ca;\n public static final int tv_label_new_password=0x7f0c00a8;\n public static final int tv_label_password=0x7f0c0095;\n public static final int tv_label_phone=0x7f0c00ad;\n public static final int tv_label_pincode=0x7f0c00d5;\n public static final int tv_label_repassword=0x7f0c0097;\n public static final int tv_label_state=0x7f0c00d1;\n public static final int tv_label_subtitle=0x7f0c00d8;\n public static final int tv_label_title=0x7f0c0092;\n public static final int tv_loadmore=0x7f0c0091;\n public static final int tv_location=0x7f0c00bc;\n public static final int tv_login=0x7f0c00b6;\n public static final int tv_logout=0x7f0c00b8;\n public static final int tv_more=0x7f0c0088;\n public static final int tv_orders=0x7f0c00be;\n public static final int tv_phone=0x7f0c00ae;\n public static final int tv_policies=0x7f0c00bf;\n public static final int tv_preferences=0x7f0c0086;\n public static final int tv_rate=0x7f0c00c2;\n public static final int tv_reset=0x7f0c00b9;\n public static final int tv_section_account=0x7f0c00b5;\n public static final int tv_section_other=0x7f0c00c0;\n public static final int tv_section_shop=0x7f0c00ba;\n public static final int tv_share=0x7f0c00c3;\n public static final int tv_shipping=0x7f0c00bd;\n public static final int tv_title=0x7f0c0084;\n public static final int tv_version=0x7f0c00c4;\n public static final int tv_zoncon=0x7f0c007a;\n public static final int up=0x7f0c0009;\n public static final int useLogo=0x7f0c0013;\n public static final int video_ghana=0x7f0c007b;\n public static final int wide=0x7f0c0029;\n public static final int withText=0x7f0c0026;\n public static final int wrap_content=0x7f0c002d;\n public static final int wv_container=0x7f0c00d9;\n public static final int zoomImage=0x7f0c008a;\n }\n public static final class integer {\n public static final int abc_config_activityDefaultDur=0x7f0a0001;\n public static final int abc_config_activityShortDur=0x7f0a0002;\n public static final int abc_max_action_buttons=0x7f0a0000;\n public static final int cancel_button_image_alpha=0x7f0a0003;\n public static final int google_play_services_version=0x7f0a0004;\n public static final int status_bar_notification_info_maxnum=0x7f0a0005;\n }\n public static final class layout {\n public static final int abc_action_bar_title_item=0x7f030000;\n public static final int abc_action_bar_up_container=0x7f030001;\n public static final int abc_action_bar_view_list_nav_layout=0x7f030002;\n public static final int abc_action_menu_item_layout=0x7f030003;\n public static final int abc_action_menu_layout=0x7f030004;\n public static final int abc_action_mode_bar=0x7f030005;\n public static final int abc_action_mode_close_item_material=0x7f030006;\n public static final int abc_activity_chooser_view=0x7f030007;\n public static final int abc_activity_chooser_view_list_item=0x7f030008;\n public static final int abc_alert_dialog_material=0x7f030009;\n public static final int abc_dialog_title_material=0x7f03000a;\n public static final int abc_expanded_menu_layout=0x7f03000b;\n public static final int abc_list_menu_item_checkbox=0x7f03000c;\n public static final int abc_list_menu_item_icon=0x7f03000d;\n public static final int abc_list_menu_item_layout=0x7f03000e;\n public static final int abc_list_menu_item_radio=0x7f03000f;\n public static final int abc_popup_menu_item_layout=0x7f030010;\n public static final int abc_screen_content_include=0x7f030011;\n public static final int abc_screen_simple=0x7f030012;\n public static final int abc_screen_simple_overlay_action_mode=0x7f030013;\n public static final int abc_screen_toolbar=0x7f030014;\n public static final int abc_search_dropdown_item_icons_2line=0x7f030015;\n public static final int abc_search_view=0x7f030016;\n public static final int abc_select_dialog_material=0x7f030017;\n public static final int activity_main=0x7f030018;\n public static final int activity_splash=0x7f030019;\n public static final int activity_video=0x7f03001a;\n public static final int activity_zoomimage=0x7f03001b;\n public static final int dialog_yes_no=0x7f03001c;\n public static final int fragment_about_itemdetails=0x7f03001d;\n public static final int fragment_about_itemslist=0x7f03001e;\n public static final int fragment_account_create=0x7f03001f;\n public static final int fragment_account_detectlogin=0x7f030020;\n public static final int fragment_account_forgot_password=0x7f030021;\n public static final int fragment_account_login=0x7f030022;\n public static final int fragment_account_reset_password=0x7f030023;\n public static final int fragment_alert_itemdetails=0x7f030024;\n public static final int fragment_alert_itemslist=0x7f030025;\n public static final int fragment_dev=0x7f030026;\n public static final int fragment_loading=0x7f030027;\n public static final int fragment_menu=0x7f030028;\n public static final int fragment_messages=0x7f030029;\n public static final int fragment_orderdetails=0x7f03002a;\n public static final int fragment_orderslist=0x7f03002b;\n public static final int fragment_payment_cart=0x7f03002c;\n public static final int fragment_payment_checkout=0x7f03002d;\n public static final int fragment_payment_confirm=0x7f03002e;\n public static final int fragment_payment_gateway=0x7f03002f;\n public static final int fragment_policy_itemdetails=0x7f030030;\n public static final int fragment_policy_itemslist=0x7f030031;\n public static final int fragment_shipping_info=0x7f030032;\n public static final int fragment_shipping_location=0x7f030033;\n public static final int fragment_shop_categories=0x7f030034;\n public static final int fragment_shop_itemdetails=0x7f030035;\n public static final int fragment_shop_itemslist=0x7f030036;\n public static final int mr_media_route_chooser_dialog=0x7f030037;\n public static final int mr_media_route_controller_material_dialog_b=0x7f030038;\n public static final int mr_media_route_list_item=0x7f030039;\n public static final int notification_media_action=0x7f03003a;\n public static final int notification_media_cancel_action=0x7f03003b;\n public static final int notification_template_big_media=0x7f03003c;\n public static final int notification_template_big_media_narrow=0x7f03003d;\n public static final int notification_template_lines=0x7f03003e;\n public static final int notification_template_media=0x7f03003f;\n public static final int notification_template_part_chronometer=0x7f030040;\n public static final int notification_template_part_time=0x7f030041;\n public static final int place_autocomplete_fragment=0x7f030042;\n public static final int place_autocomplete_item_powered_by_google=0x7f030043;\n public static final int place_autocomplete_item_prediction=0x7f030044;\n public static final int place_autocomplete_progress=0x7f030045;\n public static final int select_dialog_item_material=0x7f030046;\n public static final int select_dialog_multichoice_material=0x7f030047;\n public static final int select_dialog_singlechoice_material=0x7f030048;\n public static final int spinner_item=0x7f030049;\n public static final int support_simple_spinner_dropdown_item=0x7f03004a;\n }\n public static final class raw {\n public static final int gtm_analytics=0x7f050000;\n }\n public static final class string {\n public static final int abc_action_bar_home_description=0x7f060000;\n public static final int abc_action_bar_home_description_format=0x7f060001;\n public static final int abc_action_bar_home_subtitle_description_format=0x7f060002;\n public static final int abc_action_bar_up_description=0x7f060003;\n public static final int abc_action_menu_overflow_description=0x7f060004;\n public static final int abc_action_mode_done=0x7f060005;\n public static final int abc_activity_chooser_view_see_all=0x7f060006;\n public static final int abc_activitychooserview_choose_application=0x7f060007;\n public static final int abc_search_hint=0x7f060008;\n public static final int abc_searchview_description_clear=0x7f060009;\n public static final int abc_searchview_description_query=0x7f06000a;\n public static final int abc_searchview_description_search=0x7f06000b;\n public static final int abc_searchview_description_submit=0x7f06000c;\n public static final int abc_searchview_description_voice=0x7f06000d;\n public static final int abc_shareactionprovider_share_with=0x7f06000e;\n public static final int abc_shareactionprovider_share_with_application=0x7f06000f;\n public static final int abc_toolbar_collapse_description=0x7f060010;\n public static final int accept=0x7f06003d;\n public static final int app_name=0x7f06003e;\n public static final int auth_google_play_services_client_facebook_display_name=0x7f06003f;\n public static final int auth_google_play_services_client_google_display_name=0x7f060040;\n public static final int cast_notification_connected_message=0x7f060041;\n public static final int cast_notification_connecting_message=0x7f060042;\n public static final int cast_notification_disconnect=0x7f060043;\n public static final int common_google_play_services_api_unavailable_text=0x7f060011;\n public static final int common_google_play_services_enable_button=0x7f060012;\n public static final int common_google_play_services_enable_text=0x7f060013;\n public static final int common_google_play_services_enable_title=0x7f060014;\n public static final int common_google_play_services_install_button=0x7f060015;\n public static final int common_google_play_services_install_text_phone=0x7f060016;\n public static final int common_google_play_services_install_text_tablet=0x7f060017;\n public static final int common_google_play_services_install_title=0x7f060018;\n public static final int common_google_play_services_invalid_account_text=0x7f060019;\n public static final int common_google_play_services_invalid_account_title=0x7f06001a;\n public static final int common_google_play_services_network_error_text=0x7f06001b;\n public static final int common_google_play_services_network_error_title=0x7f06001c;\n public static final int common_google_play_services_notification_ticker=0x7f06001d;\n public static final int common_google_play_services_restricted_profile_text=0x7f06001e;\n public static final int common_google_play_services_restricted_profile_title=0x7f06001f;\n public static final int common_google_play_services_sign_in_failed_text=0x7f060020;\n public static final int common_google_play_services_sign_in_failed_title=0x7f060021;\n public static final int common_google_play_services_unknown_issue=0x7f060022;\n public static final int common_google_play_services_unsupported_text=0x7f060023;\n public static final int common_google_play_services_unsupported_title=0x7f060024;\n public static final int common_google_play_services_update_button=0x7f060025;\n public static final int common_google_play_services_update_text=0x7f060026;\n public static final int common_google_play_services_update_title=0x7f060027;\n public static final int common_google_play_services_updating_text=0x7f060028;\n public static final int common_google_play_services_updating_title=0x7f060029;\n public static final int common_google_play_services_wear_update_text=0x7f06002a;\n public static final int common_open_on_phone=0x7f06002b;\n public static final int common_signin_button_text=0x7f06002c;\n public static final int common_signin_button_text_long=0x7f06002d;\n public static final int create_calendar_message=0x7f060044;\n public static final int create_calendar_title=0x7f060045;\n public static final int decline=0x7f060046;\n public static final int hello_world=0x7f060047;\n public static final int iv_selfi_dir=0x7f060048;\n public static final int iv_selfi_path=0x7f060049;\n public static final int mr_media_route_button_content_description=0x7f06002e;\n public static final int mr_media_route_chooser_searching=0x7f06002f;\n public static final int mr_media_route_chooser_title=0x7f060030;\n public static final int mr_media_route_controller_disconnect=0x7f060031;\n public static final int mr_media_route_controller_no_info_available=0x7f060032;\n public static final int mr_media_route_controller_pause=0x7f060033;\n public static final int mr_media_route_controller_play=0x7f060034;\n public static final int mr_media_route_controller_settings_description=0x7f060035;\n public static final int mr_media_route_controller_stop=0x7f060036;\n public static final int mr_system_route_name=0x7f060037;\n public static final int mr_user_route_category_name=0x7f060038;\n public static final int place_autocomplete_clear_button=0x7f060039;\n public static final int place_autocomplete_search_hint=0x7f06003a;\n public static final int status_bar_notification_info_overflow=0x7f06003b;\n public static final int store_picture_message=0x7f06004a;\n public static final int store_picture_title=0x7f06004b;\n public static final int wallet_buy_button_place_holder=0x7f06003c;\n }\n public static final class style {\n public static final int AlertDialog_AppCompat=0x7f08007b;\n public static final int AlertDialog_AppCompat_Light=0x7f08007c;\n public static final int Animation_AppCompat_Dialog=0x7f08007d;\n public static final int Animation_AppCompat_DropDownUp=0x7f08007e;\n public static final int Base_AlertDialog_AppCompat=0x7f08007f;\n public static final int Base_AlertDialog_AppCompat_Light=0x7f080080;\n public static final int Base_Animation_AppCompat_Dialog=0x7f080081;\n public static final int Base_Animation_AppCompat_DropDownUp=0x7f080082;\n public static final int Base_DialogWindowTitle_AppCompat=0x7f080083;\n public static final int Base_DialogWindowTitleBackground_AppCompat=0x7f080084;\n public static final int Base_TextAppearance_AppCompat=0x7f08002e;\n public static final int Base_TextAppearance_AppCompat_Body1=0x7f08002f;\n public static final int Base_TextAppearance_AppCompat_Body2=0x7f080030;\n public static final int Base_TextAppearance_AppCompat_Button=0x7f080019;\n public static final int Base_TextAppearance_AppCompat_Caption=0x7f080031;\n public static final int Base_TextAppearance_AppCompat_Display1=0x7f080032;\n public static final int Base_TextAppearance_AppCompat_Display2=0x7f080033;\n public static final int Base_TextAppearance_AppCompat_Display3=0x7f080034;\n public static final int Base_TextAppearance_AppCompat_Display4=0x7f080035;\n public static final int Base_TextAppearance_AppCompat_Headline=0x7f080036;\n public static final int Base_TextAppearance_AppCompat_Inverse=0x7f080003;\n public static final int Base_TextAppearance_AppCompat_Large=0x7f080037;\n public static final int Base_TextAppearance_AppCompat_Large_Inverse=0x7f080004;\n public static final int Base_TextAppearance_AppCompat_Light_Widget_PopupMenu_Large=0x7f080038;\n public static final int Base_TextAppearance_AppCompat_Light_Widget_PopupMenu_Small=0x7f080039;\n public static final int Base_TextAppearance_AppCompat_Medium=0x7f08003a;\n public static final int Base_TextAppearance_AppCompat_Medium_Inverse=0x7f080005;\n public static final int Base_TextAppearance_AppCompat_Menu=0x7f08003b;\n public static final int Base_TextAppearance_AppCompat_SearchResult=0x7f080085;\n public static final int Base_TextAppearance_AppCompat_SearchResult_Subtitle=0x7f08003c;\n public static final int Base_TextAppearance_AppCompat_SearchResult_Title=0x7f08003d;\n public static final int Base_TextAppearance_AppCompat_Small=0x7f08003e;\n public static final int Base_TextAppearance_AppCompat_Small_Inverse=0x7f080006;\n public static final int Base_TextAppearance_AppCompat_Subhead=0x7f08003f;\n public static final int Base_TextAppearance_AppCompat_Subhead_Inverse=0x7f080007;\n public static final int Base_TextAppearance_AppCompat_Title=0x7f080040;\n public static final int Base_TextAppearance_AppCompat_Title_Inverse=0x7f080008;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionBar_Menu=0x7f080041;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionBar_Subtitle=0x7f080042;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse=0x7f080043;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionBar_Title=0x7f080044;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse=0x7f080045;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionMode_Subtitle=0x7f080046;\n public static final int Base_TextAppearance_AppCompat_Widget_ActionMode_Title=0x7f080047;\n public static final int Base_TextAppearance_AppCompat_Widget_Button=0x7f080048;\n public static final int Base_TextAppearance_AppCompat_Widget_Button_Inverse=0x7f080077;\n public static final int Base_TextAppearance_AppCompat_Widget_DropDownItem=0x7f080086;\n public static final int Base_TextAppearance_AppCompat_Widget_PopupMenu_Large=0x7f080049;\n public static final int Base_TextAppearance_AppCompat_Widget_PopupMenu_Small=0x7f08004a;\n public static final int Base_TextAppearance_AppCompat_Widget_Switch=0x7f08004b;\n public static final int Base_TextAppearance_AppCompat_Widget_TextView_SpinnerItem=0x7f08004c;\n public static final int Base_TextAppearance_Widget_AppCompat_ExpandedMenu_Item=0x7f080087;\n public static final int Base_TextAppearance_Widget_AppCompat_Toolbar_Subtitle=0x7f08004d;\n public static final int Base_TextAppearance_Widget_AppCompat_Toolbar_Title=0x7f08004e;\n public static final int Base_Theme_AppCompat=0x7f08004f;\n public static final int Base_Theme_AppCompat_CompactMenu=0x7f080088;\n public static final int Base_Theme_AppCompat_Dialog=0x7f080009;\n public static final int Base_Theme_AppCompat_Dialog_Alert=0x7f080089;\n public static final int Base_Theme_AppCompat_Dialog_FixedSize=0x7f08008a;\n public static final int Base_Theme_AppCompat_Dialog_MinWidth=0x7f08008b;\n public static final int Base_Theme_AppCompat_DialogWhenLarge=0x7f080001;\n public static final int Base_Theme_AppCompat_Light=0x7f080050;\n public static final int Base_Theme_AppCompat_Light_DarkActionBar=0x7f08008c;\n public static final int Base_Theme_AppCompat_Light_Dialog=0x7f08000a;\n public static final int Base_Theme_AppCompat_Light_Dialog_Alert=0x7f08008d;\n public static final int Base_Theme_AppCompat_Light_Dialog_FixedSize=0x7f08008e;\n public static final int Base_Theme_AppCompat_Light_Dialog_MinWidth=0x7f08008f;\n public static final int Base_Theme_AppCompat_Light_DialogWhenLarge=0x7f080002;\n public static final int Base_ThemeOverlay_AppCompat=0x7f080090;\n public static final int Base_ThemeOverlay_AppCompat_ActionBar=0x7f080091;\n public static final int Base_ThemeOverlay_AppCompat_Dark=0x7f080092;\n public static final int Base_ThemeOverlay_AppCompat_Dark_ActionBar=0x7f080093;\n public static final int Base_ThemeOverlay_AppCompat_Light=0x7f080094;\n public static final int Base_V11_Theme_AppCompat_Dialog=0x7f08000b;\n public static final int Base_V11_Theme_AppCompat_Light_Dialog=0x7f08000c;\n public static final int Base_V12_Widget_AppCompat_AutoCompleteTextView=0x7f080015;\n public static final int Base_V12_Widget_AppCompat_EditText=0x7f080016;\n public static final int Base_V21_Theme_AppCompat=0x7f080051;\n public static final int Base_V21_Theme_AppCompat_Dialog=0x7f080052;\n public static final int Base_V21_Theme_AppCompat_Light=0x7f080053;\n public static final int Base_V21_Theme_AppCompat_Light_Dialog=0x7f080054;\n public static final int Base_V22_Theme_AppCompat=0x7f080075;\n public static final int Base_V22_Theme_AppCompat_Light=0x7f080076;\n public static final int Base_V23_Theme_AppCompat=0x7f080078;\n public static final int Base_V23_Theme_AppCompat_Light=0x7f080079;\n public static final int Base_V7_Theme_AppCompat=0x7f080095;\n public static final int Base_V7_Theme_AppCompat_Dialog=0x7f080096;\n public static final int Base_V7_Theme_AppCompat_Light=0x7f080097;\n public static final int Base_V7_Theme_AppCompat_Light_Dialog=0x7f080098;\n public static final int Base_V7_Widget_AppCompat_AutoCompleteTextView=0x7f080099;\n public static final int Base_V7_Widget_AppCompat_EditText=0x7f08009a;\n public static final int Base_Widget_AppCompat_ActionBar=0x7f08009b;\n public static final int Base_Widget_AppCompat_ActionBar_Solid=0x7f08009c;\n public static final int Base_Widget_AppCompat_ActionBar_TabBar=0x7f08009d;\n public static final int Base_Widget_AppCompat_ActionBar_TabText=0x7f080055;\n public static final int Base_Widget_AppCompat_ActionBar_TabView=0x7f080056;\n public static final int Base_Widget_AppCompat_ActionButton=0x7f080057;\n public static final int Base_Widget_AppCompat_ActionButton_CloseMode=0x7f080058;\n public static final int Base_Widget_AppCompat_ActionButton_Overflow=0x7f080059;\n public static final int Base_Widget_AppCompat_ActionMode=0x7f08009e;\n public static final int Base_Widget_AppCompat_ActivityChooserView=0x7f08009f;\n public static final int Base_Widget_AppCompat_AutoCompleteTextView=0x7f080017;\n public static final int Base_Widget_AppCompat_Button=0x7f08005a;\n public static final int Base_Widget_AppCompat_Button_Borderless=0x7f08005b;\n public static final int Base_Widget_AppCompat_Button_Borderless_Colored=0x7f08005c;\n public static final int Base_Widget_AppCompat_Button_ButtonBar_AlertDialog=0x7f0800a0;\n public static final int Base_Widget_AppCompat_Button_Colored=0x7f08007a;\n public static final int Base_Widget_AppCompat_Button_Small=0x7f08005d;\n public static final int Base_Widget_AppCompat_ButtonBar=0x7f08005e;\n public static final int Base_Widget_AppCompat_ButtonBar_AlertDialog=0x7f0800a1;\n public static final int Base_Widget_AppCompat_CompoundButton_CheckBox=0x7f08005f;\n public static final int Base_Widget_AppCompat_CompoundButton_RadioButton=0x7f080060;\n public static final int Base_Widget_AppCompat_CompoundButton_Switch=0x7f0800a2;\n public static final int Base_Widget_AppCompat_DrawerArrowToggle=0x7f080000;\n public static final int Base_Widget_AppCompat_DrawerArrowToggle_Common=0x7f0800a3;\n public static final int Base_Widget_AppCompat_DropDownItem_Spinner=0x7f080061;\n public static final int Base_Widget_AppCompat_EditText=0x7f080018;\n public static final int Base_Widget_AppCompat_Light_ActionBar=0x7f0800a4;\n public static final int Base_Widget_AppCompat_Light_ActionBar_Solid=0x7f0800a5;\n public static final int Base_Widget_AppCompat_Light_ActionBar_TabBar=0x7f0800a6;\n public static final int Base_Widget_AppCompat_Light_ActionBar_TabText=0x7f080062;\n public static final int Base_Widget_AppCompat_Light_ActionBar_TabText_Inverse=0x7f080063;\n public static final int Base_Widget_AppCompat_Light_ActionBar_TabView=0x7f080064;\n public static final int Base_Widget_AppCompat_Light_PopupMenu=0x7f080065;\n public static final int Base_Widget_AppCompat_Light_PopupMenu_Overflow=0x7f080066;\n public static final int Base_Widget_AppCompat_ListPopupWindow=0x7f080067;\n public static final int Base_Widget_AppCompat_ListView=0x7f080068;\n public static final int Base_Widget_AppCompat_ListView_DropDown=0x7f080069;\n public static final int Base_Widget_AppCompat_ListView_Menu=0x7f08006a;\n public static final int Base_Widget_AppCompat_PopupMenu=0x7f08006b;\n public static final int Base_Widget_AppCompat_PopupMenu_Overflow=0x7f08006c;\n public static final int Base_Widget_AppCompat_PopupWindow=0x7f0800a7;\n public static final int Base_Widget_AppCompat_ProgressBar=0x7f08000d;\n public static final int Base_Widget_AppCompat_ProgressBar_Horizontal=0x7f08000e;\n public static final int Base_Widget_AppCompat_RatingBar=0x7f08006d;\n public static final int Base_Widget_AppCompat_SearchView=0x7f0800a8;\n public static final int Base_Widget_AppCompat_SearchView_ActionBar=0x7f0800a9;\n public static final int Base_Widget_AppCompat_Spinner=0x7f08006e;\n public static final int Base_Widget_AppCompat_Spinner_Underlined=0x7f08006f;\n public static final int Base_Widget_AppCompat_TextView_SpinnerItem=0x7f080070;\n public static final int Base_Widget_AppCompat_Toolbar=0x7f0800aa;\n public static final int Base_Widget_AppCompat_Toolbar_Button_Navigation=0x7f080071;\n public static final int Platform_AppCompat=0x7f08000f;\n public static final int Platform_AppCompat_Light=0x7f080010;\n public static final int Platform_ThemeOverlay_AppCompat=0x7f080072;\n public static final int Platform_ThemeOverlay_AppCompat_Dark=0x7f080073;\n public static final int Platform_ThemeOverlay_AppCompat_Light=0x7f080074;\n public static final int Platform_V11_AppCompat=0x7f080011;\n public static final int Platform_V11_AppCompat_Light=0x7f080012;\n public static final int Platform_V14_AppCompat=0x7f08001a;\n public static final int Platform_V14_AppCompat_Light=0x7f08001b;\n public static final int Platform_Widget_AppCompat_Spinner=0x7f080013;\n public static final int RtlOverlay_DialogWindowTitle_AppCompat=0x7f080021;\n public static final int RtlOverlay_Widget_AppCompat_ActionBar_TitleItem=0x7f080022;\n public static final int RtlOverlay_Widget_AppCompat_ActionButton_Overflow=0x7f080023;\n public static final int RtlOverlay_Widget_AppCompat_DialogTitle_Icon=0x7f080024;\n public static final int RtlOverlay_Widget_AppCompat_PopupMenuItem=0x7f080025;\n public static final int RtlOverlay_Widget_AppCompat_PopupMenuItem_InternalGroup=0x7f080026;\n public static final int RtlOverlay_Widget_AppCompat_PopupMenuItem_Text=0x7f080027;\n public static final int RtlOverlay_Widget_AppCompat_Search_DropDown=0x7f080028;\n public static final int RtlOverlay_Widget_AppCompat_Search_DropDown_Icon1=0x7f080029;\n public static final int RtlOverlay_Widget_AppCompat_Search_DropDown_Icon2=0x7f08002a;\n public static final int RtlOverlay_Widget_AppCompat_Search_DropDown_Query=0x7f08002b;\n public static final int RtlOverlay_Widget_AppCompat_Search_DropDown_Text=0x7f08002c;\n public static final int RtlOverlay_Widget_AppCompat_SearchView_MagIcon=0x7f08002d;\n public static final int TextAppearance_AppCompat=0x7f0800ab;\n public static final int TextAppearance_AppCompat_Body1=0x7f0800ac;\n public static final int TextAppearance_AppCompat_Body2=0x7f0800ad;\n public static final int TextAppearance_AppCompat_Button=0x7f0800ae;\n public static final int TextAppearance_AppCompat_Caption=0x7f0800af;\n public static final int TextAppearance_AppCompat_Display1=0x7f0800b0;\n public static final int TextAppearance_AppCompat_Display2=0x7f0800b1;\n public static final int TextAppearance_AppCompat_Display3=0x7f0800b2;\n public static final int TextAppearance_AppCompat_Display4=0x7f0800b3;\n public static final int TextAppearance_AppCompat_Headline=0x7f0800b4;\n public static final int TextAppearance_AppCompat_Inverse=0x7f0800b5;\n public static final int TextAppearance_AppCompat_Large=0x7f0800b6;\n public static final int TextAppearance_AppCompat_Large_Inverse=0x7f0800b7;\n public static final int TextAppearance_AppCompat_Light_SearchResult_Subtitle=0x7f0800b8;\n public static final int TextAppearance_AppCompat_Light_SearchResult_Title=0x7f0800b9;\n public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large=0x7f0800ba;\n public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small=0x7f0800bb;\n public static final int TextAppearance_AppCompat_Medium=0x7f0800bc;\n public static final int TextAppearance_AppCompat_Medium_Inverse=0x7f0800bd;\n public static final int TextAppearance_AppCompat_Menu=0x7f0800be;\n public static final int TextAppearance_AppCompat_SearchResult_Subtitle=0x7f0800bf;\n public static final int TextAppearance_AppCompat_SearchResult_Title=0x7f0800c0;\n public static final int TextAppearance_AppCompat_Small=0x7f0800c1;\n public static final int TextAppearance_AppCompat_Small_Inverse=0x7f0800c2;\n public static final int TextAppearance_AppCompat_Subhead=0x7f0800c3;\n public static final int TextAppearance_AppCompat_Subhead_Inverse=0x7f0800c4;\n public static final int TextAppearance_AppCompat_Title=0x7f0800c5;\n public static final int TextAppearance_AppCompat_Title_Inverse=0x7f0800c6;\n public static final int TextAppearance_AppCompat_Widget_ActionBar_Menu=0x7f0800c7;\n public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle=0x7f0800c8;\n public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse=0x7f0800c9;\n public static final int TextAppearance_AppCompat_Widget_ActionBar_Title=0x7f0800ca;\n public static final int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse=0x7f0800cb;\n public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle=0x7f0800cc;\n public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse=0x7f0800cd;\n public static final int TextAppearance_AppCompat_Widget_ActionMode_Title=0x7f0800ce;\n public static final int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse=0x7f0800cf;\n public static final int TextAppearance_AppCompat_Widget_Button=0x7f0800d0;\n public static final int TextAppearance_AppCompat_Widget_Button_Inverse=0x7f0800d1;\n public static final int TextAppearance_AppCompat_Widget_DropDownItem=0x7f0800d2;\n public static final int TextAppearance_AppCompat_Widget_PopupMenu_Large=0x7f0800d3;\n public static final int TextAppearance_AppCompat_Widget_PopupMenu_Small=0x7f0800d4;\n public static final int TextAppearance_AppCompat_Widget_Switch=0x7f0800d5;\n public static final int TextAppearance_AppCompat_Widget_TextView_SpinnerItem=0x7f0800d6;\n public static final int TextAppearance_StatusBar_EventContent=0x7f08001c;\n public static final int TextAppearance_StatusBar_EventContent_Info=0x7f08001d;\n public static final int TextAppearance_StatusBar_EventContent_Line2=0x7f08001e;\n public static final int TextAppearance_StatusBar_EventContent_Time=0x7f08001f;\n public static final int TextAppearance_StatusBar_EventContent_Title=0x7f080020;\n public static final int TextAppearance_Widget_AppCompat_ExpandedMenu_Item=0x7f0800d7;\n public static final int TextAppearance_Widget_AppCompat_Toolbar_Subtitle=0x7f0800d8;\n public static final int TextAppearance_Widget_AppCompat_Toolbar_Title=0x7f0800d9;\n public static final int Theme_AppCompat=0x7f0800da;\n public static final int Theme_AppCompat_CompactMenu=0x7f0800db;\n public static final int Theme_AppCompat_Dialog=0x7f0800dc;\n public static final int Theme_AppCompat_Dialog_Alert=0x7f0800dd;\n public static final int Theme_AppCompat_Dialog_MinWidth=0x7f0800de;\n public static final int Theme_AppCompat_DialogWhenLarge=0x7f0800df;\n public static final int Theme_AppCompat_Light=0x7f0800e0;\n public static final int Theme_AppCompat_Light_DarkActionBar=0x7f0800e1;\n public static final int Theme_AppCompat_Light_Dialog=0x7f0800e2;\n public static final int Theme_AppCompat_Light_Dialog_Alert=0x7f0800e3;\n public static final int Theme_AppCompat_Light_Dialog_MinWidth=0x7f0800e4;\n public static final int Theme_AppCompat_Light_DialogWhenLarge=0x7f0800e5;\n public static final int Theme_AppCompat_Light_NoActionBar=0x7f0800e6;\n public static final int Theme_AppCompat_NoActionBar=0x7f0800e7;\n public static final int Theme_AppInvite_Preview=0x7f0800e8;\n public static final int Theme_AppInvite_Preview_Base=0x7f080014;\n public static final int Theme_IAPTheme=0x7f0800e9;\n public static final int Theme_MediaRouter=0x7f0800ea;\n public static final int Theme_MediaRouter_Light=0x7f0800eb;\n public static final int ThemeOverlay_AppCompat=0x7f0800ec;\n public static final int ThemeOverlay_AppCompat_ActionBar=0x7f0800ed;\n public static final int ThemeOverlay_AppCompat_Dark=0x7f0800ee;\n public static final int ThemeOverlay_AppCompat_Dark_ActionBar=0x7f0800ef;\n public static final int ThemeOverlay_AppCompat_Light=0x7f0800f0;\n public static final int WalletFragmentDefaultButtonTextAppearance=0x7f0800f1;\n public static final int WalletFragmentDefaultDetailsHeaderTextAppearance=0x7f0800f2;\n public static final int WalletFragmentDefaultDetailsTextAppearance=0x7f0800f3;\n public static final int WalletFragmentDefaultStyle=0x7f0800f4;\n public static final int Widget_AppCompat_ActionBar=0x7f0800f5;\n public static final int Widget_AppCompat_ActionBar_Solid=0x7f0800f6;\n public static final int Widget_AppCompat_ActionBar_TabBar=0x7f0800f7;\n public static final int Widget_AppCompat_ActionBar_TabText=0x7f0800f8;\n public static final int Widget_AppCompat_ActionBar_TabView=0x7f0800f9;\n public static final int Widget_AppCompat_ActionButton=0x7f0800fa;\n public static final int Widget_AppCompat_ActionButton_CloseMode=0x7f0800fb;\n public static final int Widget_AppCompat_ActionButton_Overflow=0x7f0800fc;\n public static final int Widget_AppCompat_ActionMode=0x7f0800fd;\n public static final int Widget_AppCompat_ActivityChooserView=0x7f0800fe;\n public static final int Widget_AppCompat_AutoCompleteTextView=0x7f0800ff;\n public static final int Widget_AppCompat_Button=0x7f080100;\n public static final int Widget_AppCompat_Button_Borderless=0x7f080101;\n public static final int Widget_AppCompat_Button_Borderless_Colored=0x7f080102;\n public static final int Widget_AppCompat_Button_ButtonBar_AlertDialog=0x7f080103;\n public static final int Widget_AppCompat_Button_Colored=0x7f080104;\n public static final int Widget_AppCompat_Button_Small=0x7f080105;\n public static final int Widget_AppCompat_ButtonBar=0x7f080106;\n public static final int Widget_AppCompat_ButtonBar_AlertDialog=0x7f080107;\n public static final int Widget_AppCompat_CompoundButton_CheckBox=0x7f080108;\n public static final int Widget_AppCompat_CompoundButton_RadioButton=0x7f080109;\n public static final int Widget_AppCompat_CompoundButton_Switch=0x7f08010a;\n public static final int Widget_AppCompat_DrawerArrowToggle=0x7f08010b;\n public static final int Widget_AppCompat_DropDownItem_Spinner=0x7f08010c;\n public static final int Widget_AppCompat_EditText=0x7f08010d;\n public static final int Widget_AppCompat_Light_ActionBar=0x7f08010e;\n public static final int Widget_AppCompat_Light_ActionBar_Solid=0x7f08010f;\n public static final int Widget_AppCompat_Light_ActionBar_Solid_Inverse=0x7f080110;\n public static final int Widget_AppCompat_Light_ActionBar_TabBar=0x7f080111;\n public static final int Widget_AppCompat_Light_ActionBar_TabBar_Inverse=0x7f080112;\n public static final int Widget_AppCompat_Light_ActionBar_TabText=0x7f080113;\n public static final int Widget_AppCompat_Light_ActionBar_TabText_Inverse=0x7f080114;\n public static final int Widget_AppCompat_Light_ActionBar_TabView=0x7f080115;\n public static final int Widget_AppCompat_Light_ActionBar_TabView_Inverse=0x7f080116;\n public static final int Widget_AppCompat_Light_ActionButton=0x7f080117;\n public static final int Widget_AppCompat_Light_ActionButton_CloseMode=0x7f080118;\n public static final int Widget_AppCompat_Light_ActionButton_Overflow=0x7f080119;\n public static final int Widget_AppCompat_Light_ActionMode_Inverse=0x7f08011a;\n public static final int Widget_AppCompat_Light_ActivityChooserView=0x7f08011b;\n public static final int Widget_AppCompat_Light_AutoCompleteTextView=0x7f08011c;\n public static final int Widget_AppCompat_Light_DropDownItem_Spinner=0x7f08011d;\n public static final int Widget_AppCompat_Light_ListPopupWindow=0x7f08011e;\n public static final int Widget_AppCompat_Light_ListView_DropDown=0x7f08011f;\n public static final int Widget_AppCompat_Light_PopupMenu=0x7f080120;\n public static final int Widget_AppCompat_Light_PopupMenu_Overflow=0x7f080121;\n public static final int Widget_AppCompat_Light_SearchView=0x7f080122;\n public static final int Widget_AppCompat_Light_Spinner_DropDown_ActionBar=0x7f080123;\n public static final int Widget_AppCompat_ListPopupWindow=0x7f080124;\n public static final int Widget_AppCompat_ListView=0x7f080125;\n public static final int Widget_AppCompat_ListView_DropDown=0x7f080126;\n public static final int Widget_AppCompat_ListView_Menu=0x7f080127;\n public static final int Widget_AppCompat_PopupMenu=0x7f080128;\n public static final int Widget_AppCompat_PopupMenu_Overflow=0x7f080129;\n public static final int Widget_AppCompat_PopupWindow=0x7f08012a;\n public static final int Widget_AppCompat_ProgressBar=0x7f08012b;\n public static final int Widget_AppCompat_ProgressBar_Horizontal=0x7f08012c;\n public static final int Widget_AppCompat_RatingBar=0x7f08012d;\n public static final int Widget_AppCompat_SearchView=0x7f08012e;\n public static final int Widget_AppCompat_SearchView_ActionBar=0x7f08012f;\n public static final int Widget_AppCompat_Spinner=0x7f080130;\n public static final int Widget_AppCompat_Spinner_DropDown=0x7f080131;\n public static final int Widget_AppCompat_Spinner_DropDown_ActionBar=0x7f080132;\n public static final int Widget_AppCompat_Spinner_Underlined=0x7f080133;\n public static final int Widget_AppCompat_TextView_SpinnerItem=0x7f080134;\n public static final int Widget_AppCompat_Toolbar=0x7f080135;\n public static final int Widget_AppCompat_Toolbar_Button_Navigation=0x7f080136;\n public static final int Widget_MediaRouter_Light_MediaRouteButton=0x7f080137;\n public static final int Widget_MediaRouter_MediaRouteButton=0x7f080138;\n public static final int mydialogstyle=0x7f080139;\n }\n public static final class styleable {\n /** Attributes that can be used with a ActionBar.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ActionBar_background com.megotechnologies.ecommerce_retronight:background}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_backgroundSplit com.megotechnologies.ecommerce_retronight:backgroundSplit}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_backgroundStacked com.megotechnologies.ecommerce_retronight:backgroundStacked}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_contentInsetEnd com.megotechnologies.ecommerce_retronight:contentInsetEnd}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_contentInsetLeft com.megotechnologies.ecommerce_retronight:contentInsetLeft}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_contentInsetRight com.megotechnologies.ecommerce_retronight:contentInsetRight}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_contentInsetStart com.megotechnologies.ecommerce_retronight:contentInsetStart}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_customNavigationLayout com.megotechnologies.ecommerce_retronight:customNavigationLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_displayOptions com.megotechnologies.ecommerce_retronight:displayOptions}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_divider com.megotechnologies.ecommerce_retronight:divider}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_elevation com.megotechnologies.ecommerce_retronight:elevation}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_height com.megotechnologies.ecommerce_retronight:height}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_hideOnContentScroll com.megotechnologies.ecommerce_retronight:hideOnContentScroll}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_homeAsUpIndicator com.megotechnologies.ecommerce_retronight:homeAsUpIndicator}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_homeLayout com.megotechnologies.ecommerce_retronight:homeLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_icon com.megotechnologies.ecommerce_retronight:icon}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_indeterminateProgressStyle com.megotechnologies.ecommerce_retronight:indeterminateProgressStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_itemPadding com.megotechnologies.ecommerce_retronight:itemPadding}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_logo com.megotechnologies.ecommerce_retronight:logo}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_navigationMode com.megotechnologies.ecommerce_retronight:navigationMode}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_popupTheme com.megotechnologies.ecommerce_retronight:popupTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_progressBarPadding com.megotechnologies.ecommerce_retronight:progressBarPadding}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_progressBarStyle com.megotechnologies.ecommerce_retronight:progressBarStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_subtitle com.megotechnologies.ecommerce_retronight:subtitle}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_subtitleTextStyle com.megotechnologies.ecommerce_retronight:subtitleTextStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_title com.megotechnologies.ecommerce_retronight:title}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionBar_titleTextStyle com.megotechnologies.ecommerce_retronight:titleTextStyle}</code></td><td></td></tr>\n </table>\n @see #ActionBar_background\n @see #ActionBar_backgroundSplit\n @see #ActionBar_backgroundStacked\n @see #ActionBar_contentInsetEnd\n @see #ActionBar_contentInsetLeft\n @see #ActionBar_contentInsetRight\n @see #ActionBar_contentInsetStart\n @see #ActionBar_customNavigationLayout\n @see #ActionBar_displayOptions\n @see #ActionBar_divider\n @see #ActionBar_elevation\n @see #ActionBar_height\n @see #ActionBar_hideOnContentScroll\n @see #ActionBar_homeAsUpIndicator\n @see #ActionBar_homeLayout\n @see #ActionBar_icon\n @see #ActionBar_indeterminateProgressStyle\n @see #ActionBar_itemPadding\n @see #ActionBar_logo\n @see #ActionBar_navigationMode\n @see #ActionBar_popupTheme\n @see #ActionBar_progressBarPadding\n @see #ActionBar_progressBarStyle\n @see #ActionBar_subtitle\n @see #ActionBar_subtitleTextStyle\n @see #ActionBar_title\n @see #ActionBar_titleTextStyle\n */\n public static final int[] ActionBar = {\n 0x7f010001, 0x7f01000b, 0x7f01000c, 0x7f01000d,\n 0x7f01000e, 0x7f01000f, 0x7f010010, 0x7f010011,\n 0x7f010012, 0x7f010013, 0x7f010014, 0x7f010015,\n 0x7f010016, 0x7f010017, 0x7f010018, 0x7f010019,\n 0x7f01001a, 0x7f01001b, 0x7f01001c, 0x7f01001d,\n 0x7f01001e, 0x7f01001f, 0x7f010020, 0x7f010021,\n 0x7f010022, 0x7f010023, 0x7f01009f\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#background}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:background\n */\n public static final int ActionBar_background = 10;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#backgroundSplit}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:backgroundSplit\n */\n public static final int ActionBar_backgroundSplit = 12;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#backgroundStacked}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:backgroundStacked\n */\n public static final int ActionBar_backgroundStacked = 11;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetEnd}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetEnd\n */\n public static final int ActionBar_contentInsetEnd = 21;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetLeft}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetLeft\n */\n public static final int ActionBar_contentInsetLeft = 22;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetRight}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetRight\n */\n public static final int ActionBar_contentInsetRight = 23;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetStart}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetStart\n */\n public static final int ActionBar_contentInsetStart = 20;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#customNavigationLayout}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:customNavigationLayout\n */\n public static final int ActionBar_customNavigationLayout = 13;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#displayOptions}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be one or more (separated by '|') of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>useLogo</code></td><td>0x1</td><td></td></tr>\n<tr><td><code>showHome</code></td><td>0x2</td><td></td></tr>\n<tr><td><code>homeAsUp</code></td><td>0x4</td><td></td></tr>\n<tr><td><code>showTitle</code></td><td>0x8</td><td></td></tr>\n<tr><td><code>showCustom</code></td><td>0x10</td><td></td></tr>\n<tr><td><code>disableHome</code></td><td>0x20</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:displayOptions\n */\n public static final int ActionBar_displayOptions = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#divider}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:divider\n */\n public static final int ActionBar_divider = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#elevation}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:elevation\n */\n public static final int ActionBar_elevation = 24;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#height}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:height\n */\n public static final int ActionBar_height = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#hideOnContentScroll}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:hideOnContentScroll\n */\n public static final int ActionBar_hideOnContentScroll = 19;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#homeAsUpIndicator}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:homeAsUpIndicator\n */\n public static final int ActionBar_homeAsUpIndicator = 26;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#homeLayout}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:homeLayout\n */\n public static final int ActionBar_homeLayout = 14;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#icon}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:icon\n */\n public static final int ActionBar_icon = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#indeterminateProgressStyle}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:indeterminateProgressStyle\n */\n public static final int ActionBar_indeterminateProgressStyle = 16;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#itemPadding}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:itemPadding\n */\n public static final int ActionBar_itemPadding = 18;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#logo}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:logo\n */\n public static final int ActionBar_logo = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#navigationMode}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>normal</code></td><td>0</td><td></td></tr>\n<tr><td><code>listMode</code></td><td>1</td><td></td></tr>\n<tr><td><code>tabMode</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:navigationMode\n */\n public static final int ActionBar_navigationMode = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#popupTheme}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:popupTheme\n */\n public static final int ActionBar_popupTheme = 25;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#progressBarPadding}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:progressBarPadding\n */\n public static final int ActionBar_progressBarPadding = 17;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#progressBarStyle}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:progressBarStyle\n */\n public static final int ActionBar_progressBarStyle = 15;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#subtitle}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:subtitle\n */\n public static final int ActionBar_subtitle = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#subtitleTextStyle}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:subtitleTextStyle\n */\n public static final int ActionBar_subtitleTextStyle = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#title}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:title\n */\n public static final int ActionBar_title = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleTextStyle}\n attribute's value can be found in the {@link #ActionBar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:titleTextStyle\n */\n public static final int ActionBar_titleTextStyle = 5;\n /** Attributes that can be used with a ActionBarLayout.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ActionBarLayout_android_layout_gravity android:layout_gravity}</code></td><td></td></tr>\n </table>\n @see #ActionBarLayout_android_layout_gravity\n */\n public static final int[] ActionBarLayout = {\n 0x010100b3\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout_gravity}\n attribute's value can be found in the {@link #ActionBarLayout} array.\n @attr name android:layout_gravity\n */\n public static final int ActionBarLayout_android_layout_gravity = 0;\n /** Attributes that can be used with a ActionMenuItemView.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ActionMenuItemView_android_minWidth android:minWidth}</code></td><td></td></tr>\n </table>\n @see #ActionMenuItemView_android_minWidth\n */\n public static final int[] ActionMenuItemView = {\n 0x0101013f\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#minWidth}\n attribute's value can be found in the {@link #ActionMenuItemView} array.\n @attr name android:minWidth\n */\n public static final int ActionMenuItemView_android_minWidth = 0;\n /** Attributes that can be used with a ActionMenuView.\n */\n public static final int[] ActionMenuView = {\n \n };\n /** Attributes that can be used with a ActionMode.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ActionMode_background com.megotechnologies.ecommerce_retronight:background}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionMode_backgroundSplit com.megotechnologies.ecommerce_retronight:backgroundSplit}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionMode_closeItemLayout com.megotechnologies.ecommerce_retronight:closeItemLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionMode_height com.megotechnologies.ecommerce_retronight:height}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionMode_subtitleTextStyle com.megotechnologies.ecommerce_retronight:subtitleTextStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #ActionMode_titleTextStyle com.megotechnologies.ecommerce_retronight:titleTextStyle}</code></td><td></td></tr>\n </table>\n @see #ActionMode_background\n @see #ActionMode_backgroundSplit\n @see #ActionMode_closeItemLayout\n @see #ActionMode_height\n @see #ActionMode_subtitleTextStyle\n @see #ActionMode_titleTextStyle\n */\n public static final int[] ActionMode = {\n 0x7f010001, 0x7f01000f, 0x7f010010, 0x7f010014,\n 0x7f010016, 0x7f010024\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#background}\n attribute's value can be found in the {@link #ActionMode} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:background\n */\n public static final int ActionMode_background = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#backgroundSplit}\n attribute's value can be found in the {@link #ActionMode} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:backgroundSplit\n */\n public static final int ActionMode_backgroundSplit = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#closeItemLayout}\n attribute's value can be found in the {@link #ActionMode} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:closeItemLayout\n */\n public static final int ActionMode_closeItemLayout = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#height}\n attribute's value can be found in the {@link #ActionMode} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:height\n */\n public static final int ActionMode_height = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#subtitleTextStyle}\n attribute's value can be found in the {@link #ActionMode} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:subtitleTextStyle\n */\n public static final int ActionMode_subtitleTextStyle = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleTextStyle}\n attribute's value can be found in the {@link #ActionMode} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:titleTextStyle\n */\n public static final int ActionMode_titleTextStyle = 1;\n /** Attributes that can be used with a ActivityChooserView.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ActivityChooserView_expandActivityOverflowButtonDrawable com.megotechnologies.ecommerce_retronight:expandActivityOverflowButtonDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #ActivityChooserView_initialActivityCount com.megotechnologies.ecommerce_retronight:initialActivityCount}</code></td><td></td></tr>\n </table>\n @see #ActivityChooserView_expandActivityOverflowButtonDrawable\n @see #ActivityChooserView_initialActivityCount\n */\n public static final int[] ActivityChooserView = {\n 0x7f010025, 0x7f010026\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#expandActivityOverflowButtonDrawable}\n attribute's value can be found in the {@link #ActivityChooserView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:expandActivityOverflowButtonDrawable\n */\n public static final int ActivityChooserView_expandActivityOverflowButtonDrawable = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#initialActivityCount}\n attribute's value can be found in the {@link #ActivityChooserView} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:initialActivityCount\n */\n public static final int ActivityChooserView_initialActivityCount = 0;\n /** Attributes that can be used with a AdsAttrs.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #AdsAttrs_adSize com.megotechnologies.ecommerce_retronight:adSize}</code></td><td></td></tr>\n <tr><td><code>{@link #AdsAttrs_adSizes com.megotechnologies.ecommerce_retronight:adSizes}</code></td><td></td></tr>\n <tr><td><code>{@link #AdsAttrs_adUnitId com.megotechnologies.ecommerce_retronight:adUnitId}</code></td><td></td></tr>\n </table>\n @see #AdsAttrs_adSize\n @see #AdsAttrs_adSizes\n @see #AdsAttrs_adUnitId\n */\n public static final int[] AdsAttrs = {\n 0x7f010027, 0x7f010028, 0x7f010029\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#adSize}\n attribute's value can be found in the {@link #AdsAttrs} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:adSize\n */\n public static final int AdsAttrs_adSize = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#adSizes}\n attribute's value can be found in the {@link #AdsAttrs} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:adSizes\n */\n public static final int AdsAttrs_adSizes = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#adUnitId}\n attribute's value can be found in the {@link #AdsAttrs} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:adUnitId\n */\n public static final int AdsAttrs_adUnitId = 2;\n /** Attributes that can be used with a AlertDialog.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #AlertDialog_android_layout android:layout}</code></td><td></td></tr>\n <tr><td><code>{@link #AlertDialog_buttonPanelSideLayout com.megotechnologies.ecommerce_retronight:buttonPanelSideLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #AlertDialog_listItemLayout com.megotechnologies.ecommerce_retronight:listItemLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #AlertDialog_listLayout com.megotechnologies.ecommerce_retronight:listLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #AlertDialog_multiChoiceItemLayout com.megotechnologies.ecommerce_retronight:multiChoiceItemLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #AlertDialog_singleChoiceItemLayout com.megotechnologies.ecommerce_retronight:singleChoiceItemLayout}</code></td><td></td></tr>\n </table>\n @see #AlertDialog_android_layout\n @see #AlertDialog_buttonPanelSideLayout\n @see #AlertDialog_listItemLayout\n @see #AlertDialog_listLayout\n @see #AlertDialog_multiChoiceItemLayout\n @see #AlertDialog_singleChoiceItemLayout\n */\n public static final int[] AlertDialog = {\n 0x010100f2, 0x7f01002a, 0x7f01002b, 0x7f01002c,\n 0x7f01002d, 0x7f01002e\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout}\n attribute's value can be found in the {@link #AlertDialog} array.\n @attr name android:layout\n */\n public static final int AlertDialog_android_layout = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonPanelSideLayout}\n attribute's value can be found in the {@link #AlertDialog} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonPanelSideLayout\n */\n public static final int AlertDialog_buttonPanelSideLayout = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listItemLayout}\n attribute's value can be found in the {@link #AlertDialog} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:listItemLayout\n */\n public static final int AlertDialog_listItemLayout = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listLayout}\n attribute's value can be found in the {@link #AlertDialog} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:listLayout\n */\n public static final int AlertDialog_listLayout = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#multiChoiceItemLayout}\n attribute's value can be found in the {@link #AlertDialog} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:multiChoiceItemLayout\n */\n public static final int AlertDialog_multiChoiceItemLayout = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#singleChoiceItemLayout}\n attribute's value can be found in the {@link #AlertDialog} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:singleChoiceItemLayout\n */\n public static final int AlertDialog_singleChoiceItemLayout = 4;\n /** Attributes that can be used with a AppCompatTextView.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #AppCompatTextView_android_textAppearance android:textAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #AppCompatTextView_textAllCaps com.megotechnologies.ecommerce_retronight:textAllCaps}</code></td><td></td></tr>\n </table>\n @see #AppCompatTextView_android_textAppearance\n @see #AppCompatTextView_textAllCaps\n */\n public static final int[] AppCompatTextView = {\n 0x01010034, 0x7f01002f\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#textAppearance}\n attribute's value can be found in the {@link #AppCompatTextView} array.\n @attr name android:textAppearance\n */\n public static final int AppCompatTextView_android_textAppearance = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAllCaps}\n attribute's value can be found in the {@link #AppCompatTextView} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAllCaps\n */\n public static final int AppCompatTextView_textAllCaps = 1;\n /** Attributes that can be used with a CompoundButton.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #CompoundButton_android_button android:button}</code></td><td></td></tr>\n <tr><td><code>{@link #CompoundButton_buttonTint com.megotechnologies.ecommerce_retronight:buttonTint}</code></td><td></td></tr>\n <tr><td><code>{@link #CompoundButton_buttonTintMode com.megotechnologies.ecommerce_retronight:buttonTintMode}</code></td><td></td></tr>\n </table>\n @see #CompoundButton_android_button\n @see #CompoundButton_buttonTint\n @see #CompoundButton_buttonTintMode\n */\n public static final int[] CompoundButton = {\n 0x01010107, 0x7f010030, 0x7f010031\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#button}\n attribute's value can be found in the {@link #CompoundButton} array.\n @attr name android:button\n */\n public static final int CompoundButton_android_button = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonTint}\n attribute's value can be found in the {@link #CompoundButton} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:buttonTint\n */\n public static final int CompoundButton_buttonTint = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonTintMode}\n attribute's value can be found in the {@link #CompoundButton} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>src_over</code></td><td>3</td><td></td></tr>\n<tr><td><code>src_in</code></td><td>5</td><td></td></tr>\n<tr><td><code>src_atop</code></td><td>9</td><td></td></tr>\n<tr><td><code>multiply</code></td><td>14</td><td></td></tr>\n<tr><td><code>screen</code></td><td>15</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:buttonTintMode\n */\n public static final int CompoundButton_buttonTintMode = 2;\n /** Attributes that can be used with a CustomWalletTheme.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #CustomWalletTheme_windowTransitionStyle com.megotechnologies.ecommerce_retronight:windowTransitionStyle}</code></td><td></td></tr>\n </table>\n @see #CustomWalletTheme_windowTransitionStyle\n */\n public static final int[] CustomWalletTheme = {\n 0x7f010032\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowTransitionStyle}\n attribute's value can be found in the {@link #CustomWalletTheme} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>slide</code></td><td>1</td><td></td></tr>\n<tr><td><code>none</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:windowTransitionStyle\n */\n public static final int CustomWalletTheme_windowTransitionStyle = 0;\n /** Attributes that can be used with a DrawerArrowToggle.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #DrawerArrowToggle_arrowHeadLength com.megotechnologies.ecommerce_retronight:arrowHeadLength}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_arrowShaftLength com.megotechnologies.ecommerce_retronight:arrowShaftLength}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_barLength com.megotechnologies.ecommerce_retronight:barLength}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_color com.megotechnologies.ecommerce_retronight:color}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_drawableSize com.megotechnologies.ecommerce_retronight:drawableSize}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_gapBetweenBars com.megotechnologies.ecommerce_retronight:gapBetweenBars}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_spinBars com.megotechnologies.ecommerce_retronight:spinBars}</code></td><td></td></tr>\n <tr><td><code>{@link #DrawerArrowToggle_thickness com.megotechnologies.ecommerce_retronight:thickness}</code></td><td></td></tr>\n </table>\n @see #DrawerArrowToggle_arrowHeadLength\n @see #DrawerArrowToggle_arrowShaftLength\n @see #DrawerArrowToggle_barLength\n @see #DrawerArrowToggle_color\n @see #DrawerArrowToggle_drawableSize\n @see #DrawerArrowToggle_gapBetweenBars\n @see #DrawerArrowToggle_spinBars\n @see #DrawerArrowToggle_thickness\n */\n public static final int[] DrawerArrowToggle = {\n 0x7f010033, 0x7f010034, 0x7f010035, 0x7f010036,\n 0x7f010037, 0x7f010038, 0x7f010039, 0x7f01003a\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#arrowHeadLength}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:arrowHeadLength\n */\n public static final int DrawerArrowToggle_arrowHeadLength = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#arrowShaftLength}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:arrowShaftLength\n */\n public static final int DrawerArrowToggle_arrowShaftLength = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#barLength}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:barLength\n */\n public static final int DrawerArrowToggle_barLength = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#color}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:color\n */\n public static final int DrawerArrowToggle_color = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#drawableSize}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:drawableSize\n */\n public static final int DrawerArrowToggle_drawableSize = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#gapBetweenBars}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:gapBetweenBars\n */\n public static final int DrawerArrowToggle_gapBetweenBars = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#spinBars}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:spinBars\n */\n public static final int DrawerArrowToggle_spinBars = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#thickness}\n attribute's value can be found in the {@link #DrawerArrowToggle} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:thickness\n */\n public static final int DrawerArrowToggle_thickness = 7;\n /** Attributes that can be used with a LinearLayoutCompat.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #LinearLayoutCompat_android_baselineAligned android:baselineAligned}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_android_baselineAlignedChildIndex android:baselineAlignedChildIndex}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_android_gravity android:gravity}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_android_orientation android:orientation}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_android_weightSum android:weightSum}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_divider com.megotechnologies.ecommerce_retronight:divider}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_dividerPadding com.megotechnologies.ecommerce_retronight:dividerPadding}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_measureWithLargestChild com.megotechnologies.ecommerce_retronight:measureWithLargestChild}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_showDividers com.megotechnologies.ecommerce_retronight:showDividers}</code></td><td></td></tr>\n </table>\n @see #LinearLayoutCompat_android_baselineAligned\n @see #LinearLayoutCompat_android_baselineAlignedChildIndex\n @see #LinearLayoutCompat_android_gravity\n @see #LinearLayoutCompat_android_orientation\n @see #LinearLayoutCompat_android_weightSum\n @see #LinearLayoutCompat_divider\n @see #LinearLayoutCompat_dividerPadding\n @see #LinearLayoutCompat_measureWithLargestChild\n @see #LinearLayoutCompat_showDividers\n */\n public static final int[] LinearLayoutCompat = {\n 0x010100af, 0x010100c4, 0x01010126, 0x01010127,\n 0x01010128, 0x7f010013, 0x7f01003b, 0x7f01003c,\n 0x7f01003d\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#baselineAligned}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n @attr name android:baselineAligned\n */\n public static final int LinearLayoutCompat_android_baselineAligned = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#baselineAlignedChildIndex}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n @attr name android:baselineAlignedChildIndex\n */\n public static final int LinearLayoutCompat_android_baselineAlignedChildIndex = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#gravity}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n @attr name android:gravity\n */\n public static final int LinearLayoutCompat_android_gravity = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#orientation}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n @attr name android:orientation\n */\n public static final int LinearLayoutCompat_android_orientation = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#weightSum}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n @attr name android:weightSum\n */\n public static final int LinearLayoutCompat_android_weightSum = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#divider}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:divider\n */\n public static final int LinearLayoutCompat_divider = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dividerPadding}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:dividerPadding\n */\n public static final int LinearLayoutCompat_dividerPadding = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#measureWithLargestChild}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:measureWithLargestChild\n */\n public static final int LinearLayoutCompat_measureWithLargestChild = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#showDividers}\n attribute's value can be found in the {@link #LinearLayoutCompat} array.\n\n\n <p>Must be one or more (separated by '|') of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>beginning</code></td><td>1</td><td></td></tr>\n<tr><td><code>middle</code></td><td>2</td><td></td></tr>\n<tr><td><code>end</code></td><td>4</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:showDividers\n */\n public static final int LinearLayoutCompat_showDividers = 7;\n /** Attributes that can be used with a LinearLayoutCompat_Layout.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #LinearLayoutCompat_Layout_android_layout_gravity android:layout_gravity}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_Layout_android_layout_height android:layout_height}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_Layout_android_layout_weight android:layout_weight}</code></td><td></td></tr>\n <tr><td><code>{@link #LinearLayoutCompat_Layout_android_layout_width android:layout_width}</code></td><td></td></tr>\n </table>\n @see #LinearLayoutCompat_Layout_android_layout_gravity\n @see #LinearLayoutCompat_Layout_android_layout_height\n @see #LinearLayoutCompat_Layout_android_layout_weight\n @see #LinearLayoutCompat_Layout_android_layout_width\n */\n public static final int[] LinearLayoutCompat_Layout = {\n 0x010100b3, 0x010100f4, 0x010100f5, 0x01010181\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout_gravity}\n attribute's value can be found in the {@link #LinearLayoutCompat_Layout} array.\n @attr name android:layout_gravity\n */\n public static final int LinearLayoutCompat_Layout_android_layout_gravity = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout_height}\n attribute's value can be found in the {@link #LinearLayoutCompat_Layout} array.\n @attr name android:layout_height\n */\n public static final int LinearLayoutCompat_Layout_android_layout_height = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout_weight}\n attribute's value can be found in the {@link #LinearLayoutCompat_Layout} array.\n @attr name android:layout_weight\n */\n public static final int LinearLayoutCompat_Layout_android_layout_weight = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout_width}\n attribute's value can be found in the {@link #LinearLayoutCompat_Layout} array.\n @attr name android:layout_width\n */\n public static final int LinearLayoutCompat_Layout_android_layout_width = 1;\n /** Attributes that can be used with a ListPopupWindow.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ListPopupWindow_android_dropDownHorizontalOffset android:dropDownHorizontalOffset}</code></td><td></td></tr>\n <tr><td><code>{@link #ListPopupWindow_android_dropDownVerticalOffset android:dropDownVerticalOffset}</code></td><td></td></tr>\n </table>\n @see #ListPopupWindow_android_dropDownHorizontalOffset\n @see #ListPopupWindow_android_dropDownVerticalOffset\n */\n public static final int[] ListPopupWindow = {\n 0x010102ac, 0x010102ad\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#dropDownHorizontalOffset}\n attribute's value can be found in the {@link #ListPopupWindow} array.\n @attr name android:dropDownHorizontalOffset\n */\n public static final int ListPopupWindow_android_dropDownHorizontalOffset = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#dropDownVerticalOffset}\n attribute's value can be found in the {@link #ListPopupWindow} array.\n @attr name android:dropDownVerticalOffset\n */\n public static final int ListPopupWindow_android_dropDownVerticalOffset = 1;\n /** Attributes that can be used with a LoadingImageView.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #LoadingImageView_circleCrop com.megotechnologies.ecommerce_retronight:circleCrop}</code></td><td></td></tr>\n <tr><td><code>{@link #LoadingImageView_imageAspectRatio com.megotechnologies.ecommerce_retronight:imageAspectRatio}</code></td><td></td></tr>\n <tr><td><code>{@link #LoadingImageView_imageAspectRatioAdjust com.megotechnologies.ecommerce_retronight:imageAspectRatioAdjust}</code></td><td></td></tr>\n </table>\n @see #LoadingImageView_circleCrop\n @see #LoadingImageView_imageAspectRatio\n @see #LoadingImageView_imageAspectRatioAdjust\n */\n public static final int[] LoadingImageView = {\n 0x7f01003e, 0x7f01003f, 0x7f010040\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#circleCrop}\n attribute's value can be found in the {@link #LoadingImageView} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:circleCrop\n */\n public static final int LoadingImageView_circleCrop = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#imageAspectRatio}\n attribute's value can be found in the {@link #LoadingImageView} array.\n\n\n <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:imageAspectRatio\n */\n public static final int LoadingImageView_imageAspectRatio = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#imageAspectRatioAdjust}\n attribute's value can be found in the {@link #LoadingImageView} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>adjust_width</code></td><td>1</td><td></td></tr>\n<tr><td><code>adjust_height</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:imageAspectRatioAdjust\n */\n public static final int LoadingImageView_imageAspectRatioAdjust = 0;\n /** Attributes that can be used with a MapAttrs.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #MapAttrs_ambientEnabled com.megotechnologies.ecommerce_retronight:ambientEnabled}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_cameraBearing com.megotechnologies.ecommerce_retronight:cameraBearing}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_cameraTargetLat com.megotechnologies.ecommerce_retronight:cameraTargetLat}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_cameraTargetLng com.megotechnologies.ecommerce_retronight:cameraTargetLng}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_cameraTilt com.megotechnologies.ecommerce_retronight:cameraTilt}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_cameraZoom com.megotechnologies.ecommerce_retronight:cameraZoom}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_liteMode com.megotechnologies.ecommerce_retronight:liteMode}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_mapType com.megotechnologies.ecommerce_retronight:mapType}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiCompass com.megotechnologies.ecommerce_retronight:uiCompass}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiMapToolbar com.megotechnologies.ecommerce_retronight:uiMapToolbar}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiRotateGestures com.megotechnologies.ecommerce_retronight:uiRotateGestures}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiScrollGestures com.megotechnologies.ecommerce_retronight:uiScrollGestures}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiTiltGestures com.megotechnologies.ecommerce_retronight:uiTiltGestures}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiZoomControls com.megotechnologies.ecommerce_retronight:uiZoomControls}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_uiZoomGestures com.megotechnologies.ecommerce_retronight:uiZoomGestures}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_useViewLifecycle com.megotechnologies.ecommerce_retronight:useViewLifecycle}</code></td><td></td></tr>\n <tr><td><code>{@link #MapAttrs_zOrderOnTop com.megotechnologies.ecommerce_retronight:zOrderOnTop}</code></td><td></td></tr>\n </table>\n @see #MapAttrs_ambientEnabled\n @see #MapAttrs_cameraBearing\n @see #MapAttrs_cameraTargetLat\n @see #MapAttrs_cameraTargetLng\n @see #MapAttrs_cameraTilt\n @see #MapAttrs_cameraZoom\n @see #MapAttrs_liteMode\n @see #MapAttrs_mapType\n @see #MapAttrs_uiCompass\n @see #MapAttrs_uiMapToolbar\n @see #MapAttrs_uiRotateGestures\n @see #MapAttrs_uiScrollGestures\n @see #MapAttrs_uiTiltGestures\n @see #MapAttrs_uiZoomControls\n @see #MapAttrs_uiZoomGestures\n @see #MapAttrs_useViewLifecycle\n @see #MapAttrs_zOrderOnTop\n */\n public static final int[] MapAttrs = {\n 0x7f010041, 0x7f010042, 0x7f010043, 0x7f010044,\n 0x7f010045, 0x7f010046, 0x7f010047, 0x7f010048,\n 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c,\n 0x7f01004d, 0x7f01004e, 0x7f01004f, 0x7f010050,\n 0x7f010051\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#ambientEnabled}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:ambientEnabled\n */\n public static final int MapAttrs_ambientEnabled = 16;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#cameraBearing}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:cameraBearing\n */\n public static final int MapAttrs_cameraBearing = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#cameraTargetLat}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:cameraTargetLat\n */\n public static final int MapAttrs_cameraTargetLat = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#cameraTargetLng}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:cameraTargetLng\n */\n public static final int MapAttrs_cameraTargetLng = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#cameraTilt}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:cameraTilt\n */\n public static final int MapAttrs_cameraTilt = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#cameraZoom}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a floating point value, such as \"<code>1.2</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:cameraZoom\n */\n public static final int MapAttrs_cameraZoom = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#liteMode}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:liteMode\n */\n public static final int MapAttrs_liteMode = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#mapType}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>none</code></td><td>0</td><td></td></tr>\n<tr><td><code>normal</code></td><td>1</td><td></td></tr>\n<tr><td><code>satellite</code></td><td>2</td><td></td></tr>\n<tr><td><code>terrain</code></td><td>3</td><td></td></tr>\n<tr><td><code>hybrid</code></td><td>4</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:mapType\n */\n public static final int MapAttrs_mapType = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiCompass}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiCompass\n */\n public static final int MapAttrs_uiCompass = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiMapToolbar}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiMapToolbar\n */\n public static final int MapAttrs_uiMapToolbar = 15;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiRotateGestures}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiRotateGestures\n */\n public static final int MapAttrs_uiRotateGestures = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiScrollGestures}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiScrollGestures\n */\n public static final int MapAttrs_uiScrollGestures = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiTiltGestures}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiTiltGestures\n */\n public static final int MapAttrs_uiTiltGestures = 10;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiZoomControls}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiZoomControls\n */\n public static final int MapAttrs_uiZoomControls = 11;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#uiZoomGestures}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:uiZoomGestures\n */\n public static final int MapAttrs_uiZoomGestures = 12;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#useViewLifecycle}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:useViewLifecycle\n */\n public static final int MapAttrs_useViewLifecycle = 13;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#zOrderOnTop}\n attribute's value can be found in the {@link #MapAttrs} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:zOrderOnTop\n */\n public static final int MapAttrs_zOrderOnTop = 14;\n /** Attributes that can be used with a MediaRouteButton.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #MediaRouteButton_android_minHeight android:minHeight}</code></td><td></td></tr>\n <tr><td><code>{@link #MediaRouteButton_android_minWidth android:minWidth}</code></td><td></td></tr>\n <tr><td><code>{@link #MediaRouteButton_externalRouteEnabledDrawable com.megotechnologies.ecommerce_retronight:externalRouteEnabledDrawable}</code></td><td></td></tr>\n </table>\n @see #MediaRouteButton_android_minHeight\n @see #MediaRouteButton_android_minWidth\n @see #MediaRouteButton_externalRouteEnabledDrawable\n */\n public static final int[] MediaRouteButton = {\n 0x0101013f, 0x01010140, 0x7f010052\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#minHeight}\n attribute's value can be found in the {@link #MediaRouteButton} array.\n @attr name android:minHeight\n */\n public static final int MediaRouteButton_android_minHeight = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#minWidth}\n attribute's value can be found in the {@link #MediaRouteButton} array.\n @attr name android:minWidth\n */\n public static final int MediaRouteButton_android_minWidth = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#externalRouteEnabledDrawable}\n attribute's value can be found in the {@link #MediaRouteButton} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:externalRouteEnabledDrawable\n */\n public static final int MediaRouteButton_externalRouteEnabledDrawable = 2;\n /** Attributes that can be used with a MenuGroup.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #MenuGroup_android_checkableBehavior android:checkableBehavior}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuGroup_android_enabled android:enabled}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuGroup_android_id android:id}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuGroup_android_menuCategory android:menuCategory}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuGroup_android_orderInCategory android:orderInCategory}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuGroup_android_visible android:visible}</code></td><td></td></tr>\n </table>\n @see #MenuGroup_android_checkableBehavior\n @see #MenuGroup_android_enabled\n @see #MenuGroup_android_id\n @see #MenuGroup_android_menuCategory\n @see #MenuGroup_android_orderInCategory\n @see #MenuGroup_android_visible\n */\n public static final int[] MenuGroup = {\n 0x0101000e, 0x010100d0, 0x01010194, 0x010101de,\n 0x010101df, 0x010101e0\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#checkableBehavior}\n attribute's value can be found in the {@link #MenuGroup} array.\n @attr name android:checkableBehavior\n */\n public static final int MenuGroup_android_checkableBehavior = 5;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#enabled}\n attribute's value can be found in the {@link #MenuGroup} array.\n @attr name android:enabled\n */\n public static final int MenuGroup_android_enabled = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#id}\n attribute's value can be found in the {@link #MenuGroup} array.\n @attr name android:id\n */\n public static final int MenuGroup_android_id = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#menuCategory}\n attribute's value can be found in the {@link #MenuGroup} array.\n @attr name android:menuCategory\n */\n public static final int MenuGroup_android_menuCategory = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#orderInCategory}\n attribute's value can be found in the {@link #MenuGroup} array.\n @attr name android:orderInCategory\n */\n public static final int MenuGroup_android_orderInCategory = 4;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#visible}\n attribute's value can be found in the {@link #MenuGroup} array.\n @attr name android:visible\n */\n public static final int MenuGroup_android_visible = 2;\n /** Attributes that can be used with a MenuItem.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #MenuItem_actionLayout com.megotechnologies.ecommerce_retronight:actionLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_actionProviderClass com.megotechnologies.ecommerce_retronight:actionProviderClass}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_actionViewClass com.megotechnologies.ecommerce_retronight:actionViewClass}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_alphabeticShortcut android:alphabeticShortcut}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_checkable android:checkable}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_checked android:checked}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_enabled android:enabled}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_icon android:icon}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_id android:id}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_menuCategory android:menuCategory}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_numericShortcut android:numericShortcut}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_onClick android:onClick}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_orderInCategory android:orderInCategory}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_title android:title}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_titleCondensed android:titleCondensed}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_android_visible android:visible}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuItem_showAsAction com.megotechnologies.ecommerce_retronight:showAsAction}</code></td><td></td></tr>\n </table>\n @see #MenuItem_actionLayout\n @see #MenuItem_actionProviderClass\n @see #MenuItem_actionViewClass\n @see #MenuItem_android_alphabeticShortcut\n @see #MenuItem_android_checkable\n @see #MenuItem_android_checked\n @see #MenuItem_android_enabled\n @see #MenuItem_android_icon\n @see #MenuItem_android_id\n @see #MenuItem_android_menuCategory\n @see #MenuItem_android_numericShortcut\n @see #MenuItem_android_onClick\n @see #MenuItem_android_orderInCategory\n @see #MenuItem_android_title\n @see #MenuItem_android_titleCondensed\n @see #MenuItem_android_visible\n @see #MenuItem_showAsAction\n */\n public static final int[] MenuItem = {\n 0x01010002, 0x0101000e, 0x010100d0, 0x01010106,\n 0x01010194, 0x010101de, 0x010101df, 0x010101e1,\n 0x010101e2, 0x010101e3, 0x010101e4, 0x010101e5,\n 0x0101026f, 0x7f010053, 0x7f010054, 0x7f010055,\n 0x7f010056\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionLayout}\n attribute's value can be found in the {@link #MenuItem} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionLayout\n */\n public static final int MenuItem_actionLayout = 14;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionProviderClass}\n attribute's value can be found in the {@link #MenuItem} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:actionProviderClass\n */\n public static final int MenuItem_actionProviderClass = 16;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionViewClass}\n attribute's value can be found in the {@link #MenuItem} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:actionViewClass\n */\n public static final int MenuItem_actionViewClass = 15;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#alphabeticShortcut}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:alphabeticShortcut\n */\n public static final int MenuItem_android_alphabeticShortcut = 9;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#checkable}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:checkable\n */\n public static final int MenuItem_android_checkable = 11;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#checked}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:checked\n */\n public static final int MenuItem_android_checked = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#enabled}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:enabled\n */\n public static final int MenuItem_android_enabled = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#icon}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:icon\n */\n public static final int MenuItem_android_icon = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#id}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:id\n */\n public static final int MenuItem_android_id = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#menuCategory}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:menuCategory\n */\n public static final int MenuItem_android_menuCategory = 5;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#numericShortcut}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:numericShortcut\n */\n public static final int MenuItem_android_numericShortcut = 10;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#onClick}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:onClick\n */\n public static final int MenuItem_android_onClick = 12;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#orderInCategory}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:orderInCategory\n */\n public static final int MenuItem_android_orderInCategory = 6;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#title}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:title\n */\n public static final int MenuItem_android_title = 7;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#titleCondensed}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:titleCondensed\n */\n public static final int MenuItem_android_titleCondensed = 8;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#visible}\n attribute's value can be found in the {@link #MenuItem} array.\n @attr name android:visible\n */\n public static final int MenuItem_android_visible = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#showAsAction}\n attribute's value can be found in the {@link #MenuItem} array.\n\n\n <p>Must be one or more (separated by '|') of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>never</code></td><td>0</td><td></td></tr>\n<tr><td><code>ifRoom</code></td><td>1</td><td></td></tr>\n<tr><td><code>always</code></td><td>2</td><td></td></tr>\n<tr><td><code>withText</code></td><td>4</td><td></td></tr>\n<tr><td><code>collapseActionView</code></td><td>8</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:showAsAction\n */\n public static final int MenuItem_showAsAction = 13;\n /** Attributes that can be used with a MenuView.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #MenuView_android_headerBackground android:headerBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_android_horizontalDivider android:horizontalDivider}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_android_itemBackground android:itemBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_android_itemIconDisabledAlpha android:itemIconDisabledAlpha}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_android_itemTextAppearance android:itemTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_android_verticalDivider android:verticalDivider}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_android_windowAnimationStyle android:windowAnimationStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #MenuView_preserveIconSpacing com.megotechnologies.ecommerce_retronight:preserveIconSpacing}</code></td><td></td></tr>\n </table>\n @see #MenuView_android_headerBackground\n @see #MenuView_android_horizontalDivider\n @see #MenuView_android_itemBackground\n @see #MenuView_android_itemIconDisabledAlpha\n @see #MenuView_android_itemTextAppearance\n @see #MenuView_android_verticalDivider\n @see #MenuView_android_windowAnimationStyle\n @see #MenuView_preserveIconSpacing\n */\n public static final int[] MenuView = {\n 0x010100ae, 0x0101012c, 0x0101012d, 0x0101012e,\n 0x0101012f, 0x01010130, 0x01010131, 0x7f010057\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#headerBackground}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:headerBackground\n */\n public static final int MenuView_android_headerBackground = 4;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#horizontalDivider}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:horizontalDivider\n */\n public static final int MenuView_android_horizontalDivider = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#itemBackground}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:itemBackground\n */\n public static final int MenuView_android_itemBackground = 5;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#itemIconDisabledAlpha}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:itemIconDisabledAlpha\n */\n public static final int MenuView_android_itemIconDisabledAlpha = 6;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#itemTextAppearance}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:itemTextAppearance\n */\n public static final int MenuView_android_itemTextAppearance = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#verticalDivider}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:verticalDivider\n */\n public static final int MenuView_android_verticalDivider = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#windowAnimationStyle}\n attribute's value can be found in the {@link #MenuView} array.\n @attr name android:windowAnimationStyle\n */\n public static final int MenuView_android_windowAnimationStyle = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#preserveIconSpacing}\n attribute's value can be found in the {@link #MenuView} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:preserveIconSpacing\n */\n public static final int MenuView_preserveIconSpacing = 7;\n /** Attributes that can be used with a PopupWindow.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #PopupWindow_android_popupBackground android:popupBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #PopupWindow_overlapAnchor com.megotechnologies.ecommerce_retronight:overlapAnchor}</code></td><td></td></tr>\n </table>\n @see #PopupWindow_android_popupBackground\n @see #PopupWindow_overlapAnchor\n */\n public static final int[] PopupWindow = {\n 0x01010176, 0x7f010058\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#popupBackground}\n attribute's value can be found in the {@link #PopupWindow} array.\n @attr name android:popupBackground\n */\n public static final int PopupWindow_android_popupBackground = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#overlapAnchor}\n attribute's value can be found in the {@link #PopupWindow} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:overlapAnchor\n */\n public static final int PopupWindow_overlapAnchor = 1;\n /** Attributes that can be used with a PopupWindowBackgroundState.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #PopupWindowBackgroundState_state_above_anchor com.megotechnologies.ecommerce_retronight:state_above_anchor}</code></td><td></td></tr>\n </table>\n @see #PopupWindowBackgroundState_state_above_anchor\n */\n public static final int[] PopupWindowBackgroundState = {\n 0x7f010059\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#state_above_anchor}\n attribute's value can be found in the {@link #PopupWindowBackgroundState} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:state_above_anchor\n */\n public static final int PopupWindowBackgroundState_state_above_anchor = 0;\n /** Attributes that can be used with a SearchView.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #SearchView_android_focusable android:focusable}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_android_imeOptions android:imeOptions}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_android_inputType android:inputType}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_android_maxWidth android:maxWidth}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_closeIcon com.megotechnologies.ecommerce_retronight:closeIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_commitIcon com.megotechnologies.ecommerce_retronight:commitIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_defaultQueryHint com.megotechnologies.ecommerce_retronight:defaultQueryHint}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_goIcon com.megotechnologies.ecommerce_retronight:goIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_iconifiedByDefault com.megotechnologies.ecommerce_retronight:iconifiedByDefault}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_layout com.megotechnologies.ecommerce_retronight:layout}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_queryBackground com.megotechnologies.ecommerce_retronight:queryBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_queryHint com.megotechnologies.ecommerce_retronight:queryHint}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_searchHintIcon com.megotechnologies.ecommerce_retronight:searchHintIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_searchIcon com.megotechnologies.ecommerce_retronight:searchIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_submitBackground com.megotechnologies.ecommerce_retronight:submitBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_suggestionRowLayout com.megotechnologies.ecommerce_retronight:suggestionRowLayout}</code></td><td></td></tr>\n <tr><td><code>{@link #SearchView_voiceIcon com.megotechnologies.ecommerce_retronight:voiceIcon}</code></td><td></td></tr>\n </table>\n @see #SearchView_android_focusable\n @see #SearchView_android_imeOptions\n @see #SearchView_android_inputType\n @see #SearchView_android_maxWidth\n @see #SearchView_closeIcon\n @see #SearchView_commitIcon\n @see #SearchView_defaultQueryHint\n @see #SearchView_goIcon\n @see #SearchView_iconifiedByDefault\n @see #SearchView_layout\n @see #SearchView_queryBackground\n @see #SearchView_queryHint\n @see #SearchView_searchHintIcon\n @see #SearchView_searchIcon\n @see #SearchView_submitBackground\n @see #SearchView_suggestionRowLayout\n @see #SearchView_voiceIcon\n */\n public static final int[] SearchView = {\n 0x010100da, 0x0101011f, 0x01010220, 0x01010264,\n 0x7f01005a, 0x7f01005b, 0x7f01005c, 0x7f01005d,\n 0x7f01005e, 0x7f01005f, 0x7f010060, 0x7f010061,\n 0x7f010062, 0x7f010063, 0x7f010064, 0x7f010065,\n 0x7f010066\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#focusable}\n attribute's value can be found in the {@link #SearchView} array.\n @attr name android:focusable\n */\n public static final int SearchView_android_focusable = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#imeOptions}\n attribute's value can be found in the {@link #SearchView} array.\n @attr name android:imeOptions\n */\n public static final int SearchView_android_imeOptions = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#inputType}\n attribute's value can be found in the {@link #SearchView} array.\n @attr name android:inputType\n */\n public static final int SearchView_android_inputType = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#maxWidth}\n attribute's value can be found in the {@link #SearchView} array.\n @attr name android:maxWidth\n */\n public static final int SearchView_android_maxWidth = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#closeIcon}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:closeIcon\n */\n public static final int SearchView_closeIcon = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#commitIcon}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:commitIcon\n */\n public static final int SearchView_commitIcon = 13;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#defaultQueryHint}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:defaultQueryHint\n */\n public static final int SearchView_defaultQueryHint = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#goIcon}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:goIcon\n */\n public static final int SearchView_goIcon = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#iconifiedByDefault}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:iconifiedByDefault\n */\n public static final int SearchView_iconifiedByDefault = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#layout}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:layout\n */\n public static final int SearchView_layout = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#queryBackground}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:queryBackground\n */\n public static final int SearchView_queryBackground = 15;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#queryHint}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:queryHint\n */\n public static final int SearchView_queryHint = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#searchHintIcon}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:searchHintIcon\n */\n public static final int SearchView_searchHintIcon = 11;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#searchIcon}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:searchIcon\n */\n public static final int SearchView_searchIcon = 10;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#submitBackground}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:submitBackground\n */\n public static final int SearchView_submitBackground = 16;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#suggestionRowLayout}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:suggestionRowLayout\n */\n public static final int SearchView_suggestionRowLayout = 14;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#voiceIcon}\n attribute's value can be found in the {@link #SearchView} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:voiceIcon\n */\n public static final int SearchView_voiceIcon = 12;\n /** Attributes that can be used with a SignInButton.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #SignInButton_buttonSize com.megotechnologies.ecommerce_retronight:buttonSize}</code></td><td></td></tr>\n <tr><td><code>{@link #SignInButton_colorScheme com.megotechnologies.ecommerce_retronight:colorScheme}</code></td><td></td></tr>\n <tr><td><code>{@link #SignInButton_scopeUris com.megotechnologies.ecommerce_retronight:scopeUris}</code></td><td></td></tr>\n </table>\n @see #SignInButton_buttonSize\n @see #SignInButton_colorScheme\n @see #SignInButton_scopeUris\n */\n public static final int[] SignInButton = {\n 0x7f010067, 0x7f010068, 0x7f010069\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonSize}\n attribute's value can be found in the {@link #SignInButton} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>standard</code></td><td>0</td><td></td></tr>\n<tr><td><code>wide</code></td><td>1</td><td></td></tr>\n<tr><td><code>icon_only</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:buttonSize\n */\n public static final int SignInButton_buttonSize = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorScheme}\n attribute's value can be found in the {@link #SignInButton} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>dark</code></td><td>0</td><td></td></tr>\n<tr><td><code>light</code></td><td>1</td><td></td></tr>\n<tr><td><code>auto</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:colorScheme\n */\n public static final int SignInButton_colorScheme = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#scopeUris}\n attribute's value can be found in the {@link #SignInButton} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n @attr name com.megotechnologies.ecommerce_retronight:scopeUris\n */\n public static final int SignInButton_scopeUris = 2;\n /** Attributes that can be used with a Spinner.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #Spinner_android_dropDownWidth android:dropDownWidth}</code></td><td></td></tr>\n <tr><td><code>{@link #Spinner_android_popupBackground android:popupBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Spinner_android_prompt android:prompt}</code></td><td></td></tr>\n <tr><td><code>{@link #Spinner_popupTheme com.megotechnologies.ecommerce_retronight:popupTheme}</code></td><td></td></tr>\n </table>\n @see #Spinner_android_dropDownWidth\n @see #Spinner_android_popupBackground\n @see #Spinner_android_prompt\n @see #Spinner_popupTheme\n */\n public static final int[] Spinner = {\n 0x01010176, 0x0101017b, 0x01010262, 0x7f010023\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#dropDownWidth}\n attribute's value can be found in the {@link #Spinner} array.\n @attr name android:dropDownWidth\n */\n public static final int Spinner_android_dropDownWidth = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#popupBackground}\n attribute's value can be found in the {@link #Spinner} array.\n @attr name android:popupBackground\n */\n public static final int Spinner_android_popupBackground = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#prompt}\n attribute's value can be found in the {@link #Spinner} array.\n @attr name android:prompt\n */\n public static final int Spinner_android_prompt = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#popupTheme}\n attribute's value can be found in the {@link #Spinner} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:popupTheme\n */\n public static final int Spinner_popupTheme = 3;\n /** Attributes that can be used with a SwitchCompat.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #SwitchCompat_android_textOff android:textOff}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_android_textOn android:textOn}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_android_thumb android:thumb}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_showText com.megotechnologies.ecommerce_retronight:showText}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_splitTrack com.megotechnologies.ecommerce_retronight:splitTrack}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_switchMinWidth com.megotechnologies.ecommerce_retronight:switchMinWidth}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_switchPadding com.megotechnologies.ecommerce_retronight:switchPadding}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_switchTextAppearance com.megotechnologies.ecommerce_retronight:switchTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_thumbTextPadding com.megotechnologies.ecommerce_retronight:thumbTextPadding}</code></td><td></td></tr>\n <tr><td><code>{@link #SwitchCompat_track com.megotechnologies.ecommerce_retronight:track}</code></td><td></td></tr>\n </table>\n @see #SwitchCompat_android_textOff\n @see #SwitchCompat_android_textOn\n @see #SwitchCompat_android_thumb\n @see #SwitchCompat_showText\n @see #SwitchCompat_splitTrack\n @see #SwitchCompat_switchMinWidth\n @see #SwitchCompat_switchPadding\n @see #SwitchCompat_switchTextAppearance\n @see #SwitchCompat_thumbTextPadding\n @see #SwitchCompat_track\n */\n public static final int[] SwitchCompat = {\n 0x01010124, 0x01010125, 0x01010142, 0x7f01006a,\n 0x7f01006b, 0x7f01006c, 0x7f01006d, 0x7f01006e,\n 0x7f01006f, 0x7f010070\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#textOff}\n attribute's value can be found in the {@link #SwitchCompat} array.\n @attr name android:textOff\n */\n public static final int SwitchCompat_android_textOff = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#textOn}\n attribute's value can be found in the {@link #SwitchCompat} array.\n @attr name android:textOn\n */\n public static final int SwitchCompat_android_textOn = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#thumb}\n attribute's value can be found in the {@link #SwitchCompat} array.\n @attr name android:thumb\n */\n public static final int SwitchCompat_android_thumb = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#showText}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:showText\n */\n public static final int SwitchCompat_showText = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#splitTrack}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:splitTrack\n */\n public static final int SwitchCompat_splitTrack = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#switchMinWidth}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:switchMinWidth\n */\n public static final int SwitchCompat_switchMinWidth = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#switchPadding}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:switchPadding\n */\n public static final int SwitchCompat_switchPadding = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#switchTextAppearance}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:switchTextAppearance\n */\n public static final int SwitchCompat_switchTextAppearance = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#thumbTextPadding}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:thumbTextPadding\n */\n public static final int SwitchCompat_thumbTextPadding = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#track}\n attribute's value can be found in the {@link #SwitchCompat} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:track\n */\n public static final int SwitchCompat_track = 3;\n /** Attributes that can be used with a TextAppearance.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #TextAppearance_android_textColor android:textColor}</code></td><td></td></tr>\n <tr><td><code>{@link #TextAppearance_android_textSize android:textSize}</code></td><td></td></tr>\n <tr><td><code>{@link #TextAppearance_android_textStyle android:textStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #TextAppearance_android_typeface android:typeface}</code></td><td></td></tr>\n <tr><td><code>{@link #TextAppearance_textAllCaps com.megotechnologies.ecommerce_retronight:textAllCaps}</code></td><td></td></tr>\n </table>\n @see #TextAppearance_android_textColor\n @see #TextAppearance_android_textSize\n @see #TextAppearance_android_textStyle\n @see #TextAppearance_android_typeface\n @see #TextAppearance_textAllCaps\n */\n public static final int[] TextAppearance = {\n 0x01010095, 0x01010096, 0x01010097, 0x01010098,\n 0x7f01002f\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#textColor}\n attribute's value can be found in the {@link #TextAppearance} array.\n @attr name android:textColor\n */\n public static final int TextAppearance_android_textColor = 3;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#textSize}\n attribute's value can be found in the {@link #TextAppearance} array.\n @attr name android:textSize\n */\n public static final int TextAppearance_android_textSize = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#textStyle}\n attribute's value can be found in the {@link #TextAppearance} array.\n @attr name android:textStyle\n */\n public static final int TextAppearance_android_textStyle = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#typeface}\n attribute's value can be found in the {@link #TextAppearance} array.\n @attr name android:typeface\n */\n public static final int TextAppearance_android_typeface = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAllCaps}\n attribute's value can be found in the {@link #TextAppearance} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAllCaps\n */\n public static final int TextAppearance_textAllCaps = 4;\n /** Attributes that can be used with a Theme.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #Theme_actionBarDivider com.megotechnologies.ecommerce_retronight:actionBarDivider}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarItemBackground com.megotechnologies.ecommerce_retronight:actionBarItemBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarPopupTheme com.megotechnologies.ecommerce_retronight:actionBarPopupTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarSize com.megotechnologies.ecommerce_retronight:actionBarSize}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarSplitStyle com.megotechnologies.ecommerce_retronight:actionBarSplitStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarStyle com.megotechnologies.ecommerce_retronight:actionBarStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarTabBarStyle com.megotechnologies.ecommerce_retronight:actionBarTabBarStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarTabStyle com.megotechnologies.ecommerce_retronight:actionBarTabStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarTabTextStyle com.megotechnologies.ecommerce_retronight:actionBarTabTextStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarTheme com.megotechnologies.ecommerce_retronight:actionBarTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionBarWidgetTheme com.megotechnologies.ecommerce_retronight:actionBarWidgetTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionButtonStyle com.megotechnologies.ecommerce_retronight:actionButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionDropDownStyle com.megotechnologies.ecommerce_retronight:actionDropDownStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionMenuTextAppearance com.megotechnologies.ecommerce_retronight:actionMenuTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionMenuTextColor com.megotechnologies.ecommerce_retronight:actionMenuTextColor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeBackground com.megotechnologies.ecommerce_retronight:actionModeBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeCloseButtonStyle com.megotechnologies.ecommerce_retronight:actionModeCloseButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeCloseDrawable com.megotechnologies.ecommerce_retronight:actionModeCloseDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeCopyDrawable com.megotechnologies.ecommerce_retronight:actionModeCopyDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeCutDrawable com.megotechnologies.ecommerce_retronight:actionModeCutDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeFindDrawable com.megotechnologies.ecommerce_retronight:actionModeFindDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModePasteDrawable com.megotechnologies.ecommerce_retronight:actionModePasteDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModePopupWindowStyle com.megotechnologies.ecommerce_retronight:actionModePopupWindowStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeSelectAllDrawable com.megotechnologies.ecommerce_retronight:actionModeSelectAllDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeShareDrawable com.megotechnologies.ecommerce_retronight:actionModeShareDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeSplitBackground com.megotechnologies.ecommerce_retronight:actionModeSplitBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeStyle com.megotechnologies.ecommerce_retronight:actionModeStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionModeWebSearchDrawable com.megotechnologies.ecommerce_retronight:actionModeWebSearchDrawable}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionOverflowButtonStyle com.megotechnologies.ecommerce_retronight:actionOverflowButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_actionOverflowMenuStyle com.megotechnologies.ecommerce_retronight:actionOverflowMenuStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_activityChooserViewStyle com.megotechnologies.ecommerce_retronight:activityChooserViewStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_alertDialogButtonGroupStyle com.megotechnologies.ecommerce_retronight:alertDialogButtonGroupStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_alertDialogCenterButtons com.megotechnologies.ecommerce_retronight:alertDialogCenterButtons}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_alertDialogStyle com.megotechnologies.ecommerce_retronight:alertDialogStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_alertDialogTheme com.megotechnologies.ecommerce_retronight:alertDialogTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_android_windowAnimationStyle android:windowAnimationStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_android_windowIsFloating android:windowIsFloating}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_autoCompleteTextViewStyle com.megotechnologies.ecommerce_retronight:autoCompleteTextViewStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_borderlessButtonStyle com.megotechnologies.ecommerce_retronight:borderlessButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonBarButtonStyle com.megotechnologies.ecommerce_retronight:buttonBarButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonBarNegativeButtonStyle com.megotechnologies.ecommerce_retronight:buttonBarNegativeButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonBarNeutralButtonStyle com.megotechnologies.ecommerce_retronight:buttonBarNeutralButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonBarPositiveButtonStyle com.megotechnologies.ecommerce_retronight:buttonBarPositiveButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonBarStyle com.megotechnologies.ecommerce_retronight:buttonBarStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonStyle com.megotechnologies.ecommerce_retronight:buttonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_buttonStyleSmall com.megotechnologies.ecommerce_retronight:buttonStyleSmall}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_checkboxStyle com.megotechnologies.ecommerce_retronight:checkboxStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_checkedTextViewStyle com.megotechnologies.ecommerce_retronight:checkedTextViewStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorAccent com.megotechnologies.ecommerce_retronight:colorAccent}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorButtonNormal com.megotechnologies.ecommerce_retronight:colorButtonNormal}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorControlActivated com.megotechnologies.ecommerce_retronight:colorControlActivated}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorControlHighlight com.megotechnologies.ecommerce_retronight:colorControlHighlight}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorControlNormal com.megotechnologies.ecommerce_retronight:colorControlNormal}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorPrimary com.megotechnologies.ecommerce_retronight:colorPrimary}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorPrimaryDark com.megotechnologies.ecommerce_retronight:colorPrimaryDark}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_colorSwitchThumbNormal com.megotechnologies.ecommerce_retronight:colorSwitchThumbNormal}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_controlBackground com.megotechnologies.ecommerce_retronight:controlBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_dialogPreferredPadding com.megotechnologies.ecommerce_retronight:dialogPreferredPadding}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_dialogTheme com.megotechnologies.ecommerce_retronight:dialogTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_dividerHorizontal com.megotechnologies.ecommerce_retronight:dividerHorizontal}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_dividerVertical com.megotechnologies.ecommerce_retronight:dividerVertical}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_dropDownListViewStyle com.megotechnologies.ecommerce_retronight:dropDownListViewStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_dropdownListPreferredItemHeight com.megotechnologies.ecommerce_retronight:dropdownListPreferredItemHeight}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_editTextBackground com.megotechnologies.ecommerce_retronight:editTextBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_editTextColor com.megotechnologies.ecommerce_retronight:editTextColor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_editTextStyle com.megotechnologies.ecommerce_retronight:editTextStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_homeAsUpIndicator com.megotechnologies.ecommerce_retronight:homeAsUpIndicator}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listChoiceBackgroundIndicator com.megotechnologies.ecommerce_retronight:listChoiceBackgroundIndicator}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listDividerAlertDialog com.megotechnologies.ecommerce_retronight:listDividerAlertDialog}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listPopupWindowStyle com.megotechnologies.ecommerce_retronight:listPopupWindowStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listPreferredItemHeight com.megotechnologies.ecommerce_retronight:listPreferredItemHeight}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listPreferredItemHeightLarge com.megotechnologies.ecommerce_retronight:listPreferredItemHeightLarge}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listPreferredItemHeightSmall com.megotechnologies.ecommerce_retronight:listPreferredItemHeightSmall}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listPreferredItemPaddingLeft com.megotechnologies.ecommerce_retronight:listPreferredItemPaddingLeft}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_listPreferredItemPaddingRight com.megotechnologies.ecommerce_retronight:listPreferredItemPaddingRight}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_panelBackground com.megotechnologies.ecommerce_retronight:panelBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_panelMenuListTheme com.megotechnologies.ecommerce_retronight:panelMenuListTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_panelMenuListWidth com.megotechnologies.ecommerce_retronight:panelMenuListWidth}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_popupMenuStyle com.megotechnologies.ecommerce_retronight:popupMenuStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_popupWindowStyle com.megotechnologies.ecommerce_retronight:popupWindowStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_radioButtonStyle com.megotechnologies.ecommerce_retronight:radioButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_ratingBarStyle com.megotechnologies.ecommerce_retronight:ratingBarStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_searchViewStyle com.megotechnologies.ecommerce_retronight:searchViewStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_selectableItemBackground com.megotechnologies.ecommerce_retronight:selectableItemBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_selectableItemBackgroundBorderless com.megotechnologies.ecommerce_retronight:selectableItemBackgroundBorderless}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_spinnerDropDownItemStyle com.megotechnologies.ecommerce_retronight:spinnerDropDownItemStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_spinnerStyle com.megotechnologies.ecommerce_retronight:spinnerStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_switchStyle com.megotechnologies.ecommerce_retronight:switchStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textAppearanceLargePopupMenu com.megotechnologies.ecommerce_retronight:textAppearanceLargePopupMenu}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textAppearanceListItem com.megotechnologies.ecommerce_retronight:textAppearanceListItem}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textAppearanceListItemSmall com.megotechnologies.ecommerce_retronight:textAppearanceListItemSmall}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textAppearanceSearchResultSubtitle com.megotechnologies.ecommerce_retronight:textAppearanceSearchResultSubtitle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textAppearanceSearchResultTitle com.megotechnologies.ecommerce_retronight:textAppearanceSearchResultTitle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textAppearanceSmallPopupMenu com.megotechnologies.ecommerce_retronight:textAppearanceSmallPopupMenu}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textColorAlertDialogListItem com.megotechnologies.ecommerce_retronight:textColorAlertDialogListItem}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_textColorSearchUrl com.megotechnologies.ecommerce_retronight:textColorSearchUrl}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_toolbarNavigationButtonStyle com.megotechnologies.ecommerce_retronight:toolbarNavigationButtonStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_toolbarStyle com.megotechnologies.ecommerce_retronight:toolbarStyle}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowActionBar com.megotechnologies.ecommerce_retronight:windowActionBar}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowActionBarOverlay com.megotechnologies.ecommerce_retronight:windowActionBarOverlay}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowActionModeOverlay com.megotechnologies.ecommerce_retronight:windowActionModeOverlay}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowFixedHeightMajor com.megotechnologies.ecommerce_retronight:windowFixedHeightMajor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowFixedHeightMinor com.megotechnologies.ecommerce_retronight:windowFixedHeightMinor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowFixedWidthMajor com.megotechnologies.ecommerce_retronight:windowFixedWidthMajor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowFixedWidthMinor com.megotechnologies.ecommerce_retronight:windowFixedWidthMinor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowMinWidthMajor com.megotechnologies.ecommerce_retronight:windowMinWidthMajor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowMinWidthMinor com.megotechnologies.ecommerce_retronight:windowMinWidthMinor}</code></td><td></td></tr>\n <tr><td><code>{@link #Theme_windowNoTitle com.megotechnologies.ecommerce_retronight:windowNoTitle}</code></td><td></td></tr>\n </table>\n @see #Theme_actionBarDivider\n @see #Theme_actionBarItemBackground\n @see #Theme_actionBarPopupTheme\n @see #Theme_actionBarSize\n @see #Theme_actionBarSplitStyle\n @see #Theme_actionBarStyle\n @see #Theme_actionBarTabBarStyle\n @see #Theme_actionBarTabStyle\n @see #Theme_actionBarTabTextStyle\n @see #Theme_actionBarTheme\n @see #Theme_actionBarWidgetTheme\n @see #Theme_actionButtonStyle\n @see #Theme_actionDropDownStyle\n @see #Theme_actionMenuTextAppearance\n @see #Theme_actionMenuTextColor\n @see #Theme_actionModeBackground\n @see #Theme_actionModeCloseButtonStyle\n @see #Theme_actionModeCloseDrawable\n @see #Theme_actionModeCopyDrawable\n @see #Theme_actionModeCutDrawable\n @see #Theme_actionModeFindDrawable\n @see #Theme_actionModePasteDrawable\n @see #Theme_actionModePopupWindowStyle\n @see #Theme_actionModeSelectAllDrawable\n @see #Theme_actionModeShareDrawable\n @see #Theme_actionModeSplitBackground\n @see #Theme_actionModeStyle\n @see #Theme_actionModeWebSearchDrawable\n @see #Theme_actionOverflowButtonStyle\n @see #Theme_actionOverflowMenuStyle\n @see #Theme_activityChooserViewStyle\n @see #Theme_alertDialogButtonGroupStyle\n @see #Theme_alertDialogCenterButtons\n @see #Theme_alertDialogStyle\n @see #Theme_alertDialogTheme\n @see #Theme_android_windowAnimationStyle\n @see #Theme_android_windowIsFloating\n @see #Theme_autoCompleteTextViewStyle\n @see #Theme_borderlessButtonStyle\n @see #Theme_buttonBarButtonStyle\n @see #Theme_buttonBarNegativeButtonStyle\n @see #Theme_buttonBarNeutralButtonStyle\n @see #Theme_buttonBarPositiveButtonStyle\n @see #Theme_buttonBarStyle\n @see #Theme_buttonStyle\n @see #Theme_buttonStyleSmall\n @see #Theme_checkboxStyle\n @see #Theme_checkedTextViewStyle\n @see #Theme_colorAccent\n @see #Theme_colorButtonNormal\n @see #Theme_colorControlActivated\n @see #Theme_colorControlHighlight\n @see #Theme_colorControlNormal\n @see #Theme_colorPrimary\n @see #Theme_colorPrimaryDark\n @see #Theme_colorSwitchThumbNormal\n @see #Theme_controlBackground\n @see #Theme_dialogPreferredPadding\n @see #Theme_dialogTheme\n @see #Theme_dividerHorizontal\n @see #Theme_dividerVertical\n @see #Theme_dropDownListViewStyle\n @see #Theme_dropdownListPreferredItemHeight\n @see #Theme_editTextBackground\n @see #Theme_editTextColor\n @see #Theme_editTextStyle\n @see #Theme_homeAsUpIndicator\n @see #Theme_listChoiceBackgroundIndicator\n @see #Theme_listDividerAlertDialog\n @see #Theme_listPopupWindowStyle\n @see #Theme_listPreferredItemHeight\n @see #Theme_listPreferredItemHeightLarge\n @see #Theme_listPreferredItemHeightSmall\n @see #Theme_listPreferredItemPaddingLeft\n @see #Theme_listPreferredItemPaddingRight\n @see #Theme_panelBackground\n @see #Theme_panelMenuListTheme\n @see #Theme_panelMenuListWidth\n @see #Theme_popupMenuStyle\n @see #Theme_popupWindowStyle\n @see #Theme_radioButtonStyle\n @see #Theme_ratingBarStyle\n @see #Theme_searchViewStyle\n @see #Theme_selectableItemBackground\n @see #Theme_selectableItemBackgroundBorderless\n @see #Theme_spinnerDropDownItemStyle\n @see #Theme_spinnerStyle\n @see #Theme_switchStyle\n @see #Theme_textAppearanceLargePopupMenu\n @see #Theme_textAppearanceListItem\n @see #Theme_textAppearanceListItemSmall\n @see #Theme_textAppearanceSearchResultSubtitle\n @see #Theme_textAppearanceSearchResultTitle\n @see #Theme_textAppearanceSmallPopupMenu\n @see #Theme_textColorAlertDialogListItem\n @see #Theme_textColorSearchUrl\n @see #Theme_toolbarNavigationButtonStyle\n @see #Theme_toolbarStyle\n @see #Theme_windowActionBar\n @see #Theme_windowActionBarOverlay\n @see #Theme_windowActionModeOverlay\n @see #Theme_windowFixedHeightMajor\n @see #Theme_windowFixedHeightMinor\n @see #Theme_windowFixedWidthMajor\n @see #Theme_windowFixedWidthMinor\n @see #Theme_windowMinWidthMajor\n @see #Theme_windowMinWidthMinor\n @see #Theme_windowNoTitle\n */\n public static final int[] Theme = {\n 0x01010057, 0x010100ae, 0x7f010071, 0x7f010072,\n 0x7f010073, 0x7f010074, 0x7f010075, 0x7f010076,\n 0x7f010077, 0x7f010078, 0x7f010079, 0x7f01007a,\n 0x7f01007b, 0x7f01007c, 0x7f01007d, 0x7f01007e,\n 0x7f01007f, 0x7f010080, 0x7f010081, 0x7f010082,\n 0x7f010083, 0x7f010084, 0x7f010085, 0x7f010086,\n 0x7f010087, 0x7f010088, 0x7f010089, 0x7f01008a,\n 0x7f01008b, 0x7f01008c, 0x7f01008d, 0x7f01008e,\n 0x7f01008f, 0x7f010090, 0x7f010091, 0x7f010092,\n 0x7f010093, 0x7f010094, 0x7f010095, 0x7f010096,\n 0x7f010097, 0x7f010098, 0x7f010099, 0x7f01009a,\n 0x7f01009b, 0x7f01009c, 0x7f01009d, 0x7f01009e,\n 0x7f01009f, 0x7f0100a0, 0x7f0100a1, 0x7f0100a2,\n 0x7f0100a3, 0x7f0100a4, 0x7f0100a5, 0x7f0100a6,\n 0x7f0100a7, 0x7f0100a8, 0x7f0100a9, 0x7f0100aa,\n 0x7f0100ab, 0x7f0100ac, 0x7f0100ad, 0x7f0100ae,\n 0x7f0100af, 0x7f0100b0, 0x7f0100b1, 0x7f0100b2,\n 0x7f0100b3, 0x7f0100b4, 0x7f0100b5, 0x7f0100b6,\n 0x7f0100b7, 0x7f0100b8, 0x7f0100b9, 0x7f0100ba,\n 0x7f0100bb, 0x7f0100bc, 0x7f0100bd, 0x7f0100be,\n 0x7f0100bf, 0x7f0100c0, 0x7f0100c1, 0x7f0100c2,\n 0x7f0100c3, 0x7f0100c4, 0x7f0100c5, 0x7f0100c6,\n 0x7f0100c7, 0x7f0100c8, 0x7f0100c9, 0x7f0100ca,\n 0x7f0100cb, 0x7f0100cc, 0x7f0100cd, 0x7f0100ce,\n 0x7f0100cf, 0x7f0100d0, 0x7f0100d1, 0x7f0100d2,\n 0x7f0100d3, 0x7f0100d4, 0x7f0100d5, 0x7f0100d6,\n 0x7f0100d7, 0x7f0100d8, 0x7f0100d9, 0x7f0100da\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarDivider}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarDivider\n */\n public static final int Theme_actionBarDivider = 23;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarItemBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarItemBackground\n */\n public static final int Theme_actionBarItemBackground = 24;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarPopupTheme}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarPopupTheme\n */\n public static final int Theme_actionBarPopupTheme = 17;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarSize}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>wrap_content</code></td><td>0</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:actionBarSize\n */\n public static final int Theme_actionBarSize = 22;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarSplitStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarSplitStyle\n */\n public static final int Theme_actionBarSplitStyle = 19;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarStyle\n */\n public static final int Theme_actionBarStyle = 18;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarTabBarStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarTabBarStyle\n */\n public static final int Theme_actionBarTabBarStyle = 13;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarTabStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarTabStyle\n */\n public static final int Theme_actionBarTabStyle = 12;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarTabTextStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarTabTextStyle\n */\n public static final int Theme_actionBarTabTextStyle = 14;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarTheme}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarTheme\n */\n public static final int Theme_actionBarTheme = 20;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionBarWidgetTheme}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionBarWidgetTheme\n */\n public static final int Theme_actionBarWidgetTheme = 21;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionButtonStyle\n */\n public static final int Theme_actionButtonStyle = 49;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionDropDownStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionDropDownStyle\n */\n public static final int Theme_actionDropDownStyle = 45;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionMenuTextAppearance}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionMenuTextAppearance\n */\n public static final int Theme_actionMenuTextAppearance = 25;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionMenuTextColor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionMenuTextColor\n */\n public static final int Theme_actionMenuTextColor = 26;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeBackground\n */\n public static final int Theme_actionModeBackground = 29;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeCloseButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeCloseButtonStyle\n */\n public static final int Theme_actionModeCloseButtonStyle = 28;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeCloseDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeCloseDrawable\n */\n public static final int Theme_actionModeCloseDrawable = 31;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeCopyDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeCopyDrawable\n */\n public static final int Theme_actionModeCopyDrawable = 33;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeCutDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeCutDrawable\n */\n public static final int Theme_actionModeCutDrawable = 32;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeFindDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeFindDrawable\n */\n public static final int Theme_actionModeFindDrawable = 37;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModePasteDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModePasteDrawable\n */\n public static final int Theme_actionModePasteDrawable = 34;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModePopupWindowStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModePopupWindowStyle\n */\n public static final int Theme_actionModePopupWindowStyle = 39;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeSelectAllDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeSelectAllDrawable\n */\n public static final int Theme_actionModeSelectAllDrawable = 35;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeShareDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeShareDrawable\n */\n public static final int Theme_actionModeShareDrawable = 36;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeSplitBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeSplitBackground\n */\n public static final int Theme_actionModeSplitBackground = 30;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeStyle\n */\n public static final int Theme_actionModeStyle = 27;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionModeWebSearchDrawable}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionModeWebSearchDrawable\n */\n public static final int Theme_actionModeWebSearchDrawable = 38;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionOverflowButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionOverflowButtonStyle\n */\n public static final int Theme_actionOverflowButtonStyle = 15;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#actionOverflowMenuStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:actionOverflowMenuStyle\n */\n public static final int Theme_actionOverflowMenuStyle = 16;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#activityChooserViewStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:activityChooserViewStyle\n */\n public static final int Theme_activityChooserViewStyle = 57;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#alertDialogButtonGroupStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:alertDialogButtonGroupStyle\n */\n public static final int Theme_alertDialogButtonGroupStyle = 91;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#alertDialogCenterButtons}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:alertDialogCenterButtons\n */\n public static final int Theme_alertDialogCenterButtons = 92;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#alertDialogStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:alertDialogStyle\n */\n public static final int Theme_alertDialogStyle = 90;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#alertDialogTheme}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:alertDialogTheme\n */\n public static final int Theme_alertDialogTheme = 93;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#windowAnimationStyle}\n attribute's value can be found in the {@link #Theme} array.\n @attr name android:windowAnimationStyle\n */\n public static final int Theme_android_windowAnimationStyle = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#windowIsFloating}\n attribute's value can be found in the {@link #Theme} array.\n @attr name android:windowIsFloating\n */\n public static final int Theme_android_windowIsFloating = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#autoCompleteTextViewStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:autoCompleteTextViewStyle\n */\n public static final int Theme_autoCompleteTextViewStyle = 98;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#borderlessButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:borderlessButtonStyle\n */\n public static final int Theme_borderlessButtonStyle = 54;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonBarButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonBarButtonStyle\n */\n public static final int Theme_buttonBarButtonStyle = 51;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonBarNegativeButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonBarNegativeButtonStyle\n */\n public static final int Theme_buttonBarNegativeButtonStyle = 96;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonBarNeutralButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonBarNeutralButtonStyle\n */\n public static final int Theme_buttonBarNeutralButtonStyle = 97;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonBarPositiveButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonBarPositiveButtonStyle\n */\n public static final int Theme_buttonBarPositiveButtonStyle = 95;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonBarStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonBarStyle\n */\n public static final int Theme_buttonBarStyle = 50;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonStyle\n */\n public static final int Theme_buttonStyle = 99;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buttonStyleSmall}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:buttonStyleSmall\n */\n public static final int Theme_buttonStyleSmall = 100;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#checkboxStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:checkboxStyle\n */\n public static final int Theme_checkboxStyle = 101;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#checkedTextViewStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:checkedTextViewStyle\n */\n public static final int Theme_checkedTextViewStyle = 102;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorAccent}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorAccent\n */\n public static final int Theme_colorAccent = 83;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorButtonNormal}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorButtonNormal\n */\n public static final int Theme_colorButtonNormal = 87;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorControlActivated}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorControlActivated\n */\n public static final int Theme_colorControlActivated = 85;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorControlHighlight}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorControlHighlight\n */\n public static final int Theme_colorControlHighlight = 86;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorControlNormal}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorControlNormal\n */\n public static final int Theme_colorControlNormal = 84;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorPrimary}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorPrimary\n */\n public static final int Theme_colorPrimary = 81;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorPrimaryDark}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorPrimaryDark\n */\n public static final int Theme_colorPrimaryDark = 82;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#colorSwitchThumbNormal}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:colorSwitchThumbNormal\n */\n public static final int Theme_colorSwitchThumbNormal = 88;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#controlBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:controlBackground\n */\n public static final int Theme_controlBackground = 89;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dialogPreferredPadding}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:dialogPreferredPadding\n */\n public static final int Theme_dialogPreferredPadding = 43;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dialogTheme}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:dialogTheme\n */\n public static final int Theme_dialogTheme = 42;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dividerHorizontal}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:dividerHorizontal\n */\n public static final int Theme_dividerHorizontal = 56;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dividerVertical}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:dividerVertical\n */\n public static final int Theme_dividerVertical = 55;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dropDownListViewStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:dropDownListViewStyle\n */\n public static final int Theme_dropDownListViewStyle = 73;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#dropdownListPreferredItemHeight}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:dropdownListPreferredItemHeight\n */\n public static final int Theme_dropdownListPreferredItemHeight = 46;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#editTextBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:editTextBackground\n */\n public static final int Theme_editTextBackground = 63;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#editTextColor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:editTextColor\n */\n public static final int Theme_editTextColor = 62;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#editTextStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:editTextStyle\n */\n public static final int Theme_editTextStyle = 103;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#homeAsUpIndicator}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:homeAsUpIndicator\n */\n public static final int Theme_homeAsUpIndicator = 48;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listChoiceBackgroundIndicator}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:listChoiceBackgroundIndicator\n */\n public static final int Theme_listChoiceBackgroundIndicator = 80;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listDividerAlertDialog}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:listDividerAlertDialog\n */\n public static final int Theme_listDividerAlertDialog = 44;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listPopupWindowStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:listPopupWindowStyle\n */\n public static final int Theme_listPopupWindowStyle = 74;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listPreferredItemHeight}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:listPreferredItemHeight\n */\n public static final int Theme_listPreferredItemHeight = 68;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listPreferredItemHeightLarge}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:listPreferredItemHeightLarge\n */\n public static final int Theme_listPreferredItemHeightLarge = 70;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listPreferredItemHeightSmall}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:listPreferredItemHeightSmall\n */\n public static final int Theme_listPreferredItemHeightSmall = 69;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listPreferredItemPaddingLeft}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:listPreferredItemPaddingLeft\n */\n public static final int Theme_listPreferredItemPaddingLeft = 71;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#listPreferredItemPaddingRight}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:listPreferredItemPaddingRight\n */\n public static final int Theme_listPreferredItemPaddingRight = 72;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#panelBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:panelBackground\n */\n public static final int Theme_panelBackground = 77;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#panelMenuListTheme}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:panelMenuListTheme\n */\n public static final int Theme_panelMenuListTheme = 79;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#panelMenuListWidth}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:panelMenuListWidth\n */\n public static final int Theme_panelMenuListWidth = 78;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#popupMenuStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:popupMenuStyle\n */\n public static final int Theme_popupMenuStyle = 60;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#popupWindowStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:popupWindowStyle\n */\n public static final int Theme_popupWindowStyle = 61;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#radioButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:radioButtonStyle\n */\n public static final int Theme_radioButtonStyle = 104;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#ratingBarStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:ratingBarStyle\n */\n public static final int Theme_ratingBarStyle = 105;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#searchViewStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:searchViewStyle\n */\n public static final int Theme_searchViewStyle = 67;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#selectableItemBackground}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:selectableItemBackground\n */\n public static final int Theme_selectableItemBackground = 52;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#selectableItemBackgroundBorderless}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:selectableItemBackgroundBorderless\n */\n public static final int Theme_selectableItemBackgroundBorderless = 53;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#spinnerDropDownItemStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:spinnerDropDownItemStyle\n */\n public static final int Theme_spinnerDropDownItemStyle = 47;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#spinnerStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:spinnerStyle\n */\n public static final int Theme_spinnerStyle = 106;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#switchStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:switchStyle\n */\n public static final int Theme_switchStyle = 107;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAppearanceLargePopupMenu}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAppearanceLargePopupMenu\n */\n public static final int Theme_textAppearanceLargePopupMenu = 40;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAppearanceListItem}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAppearanceListItem\n */\n public static final int Theme_textAppearanceListItem = 75;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAppearanceListItemSmall}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAppearanceListItemSmall\n */\n public static final int Theme_textAppearanceListItemSmall = 76;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAppearanceSearchResultSubtitle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAppearanceSearchResultSubtitle\n */\n public static final int Theme_textAppearanceSearchResultSubtitle = 65;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAppearanceSearchResultTitle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAppearanceSearchResultTitle\n */\n public static final int Theme_textAppearanceSearchResultTitle = 64;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textAppearanceSmallPopupMenu}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textAppearanceSmallPopupMenu\n */\n public static final int Theme_textAppearanceSmallPopupMenu = 41;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textColorAlertDialogListItem}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textColorAlertDialogListItem\n */\n public static final int Theme_textColorAlertDialogListItem = 94;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#textColorSearchUrl}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:textColorSearchUrl\n */\n public static final int Theme_textColorSearchUrl = 66;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#toolbarNavigationButtonStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:toolbarNavigationButtonStyle\n */\n public static final int Theme_toolbarNavigationButtonStyle = 59;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#toolbarStyle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:toolbarStyle\n */\n public static final int Theme_toolbarStyle = 58;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowActionBar}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowActionBar\n */\n public static final int Theme_windowActionBar = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowActionBarOverlay}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowActionBarOverlay\n */\n public static final int Theme_windowActionBarOverlay = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowActionModeOverlay}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowActionModeOverlay\n */\n public static final int Theme_windowActionModeOverlay = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowFixedHeightMajor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowFixedHeightMajor\n */\n public static final int Theme_windowFixedHeightMajor = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowFixedHeightMinor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowFixedHeightMinor\n */\n public static final int Theme_windowFixedHeightMinor = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowFixedWidthMajor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowFixedWidthMajor\n */\n public static final int Theme_windowFixedWidthMajor = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowFixedWidthMinor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowFixedWidthMinor\n */\n public static final int Theme_windowFixedWidthMinor = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowMinWidthMajor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowMinWidthMajor\n */\n public static final int Theme_windowMinWidthMajor = 10;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowMinWidthMinor}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>May be a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\nThe % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\nsome parent container.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowMinWidthMinor\n */\n public static final int Theme_windowMinWidthMinor = 11;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#windowNoTitle}\n attribute's value can be found in the {@link #Theme} array.\n\n\n <p>Must be a boolean value, either \"<code>true</code>\" or \"<code>false</code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:windowNoTitle\n */\n public static final int Theme_windowNoTitle = 3;\n /** Attributes that can be used with a Toolbar.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #Toolbar_android_gravity android:gravity}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_android_minHeight android:minHeight}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_collapseContentDescription com.megotechnologies.ecommerce_retronight:collapseContentDescription}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_collapseIcon com.megotechnologies.ecommerce_retronight:collapseIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_contentInsetEnd com.megotechnologies.ecommerce_retronight:contentInsetEnd}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_contentInsetLeft com.megotechnologies.ecommerce_retronight:contentInsetLeft}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_contentInsetRight com.megotechnologies.ecommerce_retronight:contentInsetRight}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_contentInsetStart com.megotechnologies.ecommerce_retronight:contentInsetStart}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_logo com.megotechnologies.ecommerce_retronight:logo}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_logoDescription com.megotechnologies.ecommerce_retronight:logoDescription}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_maxButtonHeight com.megotechnologies.ecommerce_retronight:maxButtonHeight}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_navigationContentDescription com.megotechnologies.ecommerce_retronight:navigationContentDescription}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_navigationIcon com.megotechnologies.ecommerce_retronight:navigationIcon}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_popupTheme com.megotechnologies.ecommerce_retronight:popupTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_subtitle com.megotechnologies.ecommerce_retronight:subtitle}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_subtitleTextAppearance com.megotechnologies.ecommerce_retronight:subtitleTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_subtitleTextColor com.megotechnologies.ecommerce_retronight:subtitleTextColor}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_title com.megotechnologies.ecommerce_retronight:title}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleMarginBottom com.megotechnologies.ecommerce_retronight:titleMarginBottom}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleMarginEnd com.megotechnologies.ecommerce_retronight:titleMarginEnd}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleMarginStart com.megotechnologies.ecommerce_retronight:titleMarginStart}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleMarginTop com.megotechnologies.ecommerce_retronight:titleMarginTop}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleMargins com.megotechnologies.ecommerce_retronight:titleMargins}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleTextAppearance com.megotechnologies.ecommerce_retronight:titleTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #Toolbar_titleTextColor com.megotechnologies.ecommerce_retronight:titleTextColor}</code></td><td></td></tr>\n </table>\n @see #Toolbar_android_gravity\n @see #Toolbar_android_minHeight\n @see #Toolbar_collapseContentDescription\n @see #Toolbar_collapseIcon\n @see #Toolbar_contentInsetEnd\n @see #Toolbar_contentInsetLeft\n @see #Toolbar_contentInsetRight\n @see #Toolbar_contentInsetStart\n @see #Toolbar_logo\n @see #Toolbar_logoDescription\n @see #Toolbar_maxButtonHeight\n @see #Toolbar_navigationContentDescription\n @see #Toolbar_navigationIcon\n @see #Toolbar_popupTheme\n @see #Toolbar_subtitle\n @see #Toolbar_subtitleTextAppearance\n @see #Toolbar_subtitleTextColor\n @see #Toolbar_title\n @see #Toolbar_titleMarginBottom\n @see #Toolbar_titleMarginEnd\n @see #Toolbar_titleMarginStart\n @see #Toolbar_titleMarginTop\n @see #Toolbar_titleMargins\n @see #Toolbar_titleTextAppearance\n @see #Toolbar_titleTextColor\n */\n public static final int[] Toolbar = {\n 0x010100af, 0x01010140, 0x7f01000b, 0x7f01000e,\n 0x7f010012, 0x7f01001e, 0x7f01001f, 0x7f010020,\n 0x7f010021, 0x7f010023, 0x7f0100db, 0x7f0100dc,\n 0x7f0100dd, 0x7f0100de, 0x7f0100df, 0x7f0100e0,\n 0x7f0100e1, 0x7f0100e2, 0x7f0100e3, 0x7f0100e4,\n 0x7f0100e5, 0x7f0100e6, 0x7f0100e7, 0x7f0100e8,\n 0x7f0100e9\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#gravity}\n attribute's value can be found in the {@link #Toolbar} array.\n @attr name android:gravity\n */\n public static final int Toolbar_android_gravity = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#minHeight}\n attribute's value can be found in the {@link #Toolbar} array.\n @attr name android:minHeight\n */\n public static final int Toolbar_android_minHeight = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#collapseContentDescription}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:collapseContentDescription\n */\n public static final int Toolbar_collapseContentDescription = 19;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#collapseIcon}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:collapseIcon\n */\n public static final int Toolbar_collapseIcon = 18;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetEnd}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetEnd\n */\n public static final int Toolbar_contentInsetEnd = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetLeft}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetLeft\n */\n public static final int Toolbar_contentInsetLeft = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetRight}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetRight\n */\n public static final int Toolbar_contentInsetRight = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#contentInsetStart}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:contentInsetStart\n */\n public static final int Toolbar_contentInsetStart = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#logo}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:logo\n */\n public static final int Toolbar_logo = 4;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#logoDescription}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:logoDescription\n */\n public static final int Toolbar_logoDescription = 22;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maxButtonHeight}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:maxButtonHeight\n */\n public static final int Toolbar_maxButtonHeight = 17;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#navigationContentDescription}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:navigationContentDescription\n */\n public static final int Toolbar_navigationContentDescription = 21;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#navigationIcon}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:navigationIcon\n */\n public static final int Toolbar_navigationIcon = 20;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#popupTheme}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:popupTheme\n */\n public static final int Toolbar_popupTheme = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#subtitle}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:subtitle\n */\n public static final int Toolbar_subtitle = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#subtitleTextAppearance}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:subtitleTextAppearance\n */\n public static final int Toolbar_subtitleTextAppearance = 11;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#subtitleTextColor}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:subtitleTextColor\n */\n public static final int Toolbar_subtitleTextColor = 24;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#title}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character.\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:title\n */\n public static final int Toolbar_title = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleMarginBottom}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:titleMarginBottom\n */\n public static final int Toolbar_titleMarginBottom = 16;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleMarginEnd}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:titleMarginEnd\n */\n public static final int Toolbar_titleMarginEnd = 14;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleMarginStart}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:titleMarginStart\n */\n public static final int Toolbar_titleMarginStart = 13;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleMarginTop}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:titleMarginTop\n */\n public static final int Toolbar_titleMarginTop = 15;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleMargins}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:titleMargins\n */\n public static final int Toolbar_titleMargins = 12;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleTextAppearance}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:titleTextAppearance\n */\n public static final int Toolbar_titleTextAppearance = 10;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#titleTextColor}\n attribute's value can be found in the {@link #Toolbar} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:titleTextColor\n */\n public static final int Toolbar_titleTextColor = 23;\n /** Attributes that can be used with a View.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #View_android_focusable android:focusable}</code></td><td></td></tr>\n <tr><td><code>{@link #View_android_theme android:theme}</code></td><td></td></tr>\n <tr><td><code>{@link #View_paddingEnd com.megotechnologies.ecommerce_retronight:paddingEnd}</code></td><td></td></tr>\n <tr><td><code>{@link #View_paddingStart com.megotechnologies.ecommerce_retronight:paddingStart}</code></td><td></td></tr>\n <tr><td><code>{@link #View_theme com.megotechnologies.ecommerce_retronight:theme}</code></td><td></td></tr>\n </table>\n @see #View_android_focusable\n @see #View_android_theme\n @see #View_paddingEnd\n @see #View_paddingStart\n @see #View_theme\n */\n public static final int[] View = {\n 0x01010000, 0x010100da, 0x7f0100ea, 0x7f0100eb,\n 0x7f0100ec\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#focusable}\n attribute's value can be found in the {@link #View} array.\n @attr name android:focusable\n */\n public static final int View_android_focusable = 1;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#theme}\n attribute's value can be found in the {@link #View} array.\n @attr name android:theme\n */\n public static final int View_android_theme = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#paddingEnd}\n attribute's value can be found in the {@link #View} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:paddingEnd\n */\n public static final int View_paddingEnd = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#paddingStart}\n attribute's value can be found in the {@link #View} array.\n\n\n <p>Must be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:paddingStart\n */\n public static final int View_paddingStart = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#theme}\n attribute's value can be found in the {@link #View} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:theme\n */\n public static final int View_theme = 4;\n /** Attributes that can be used with a ViewBackgroundHelper.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ViewBackgroundHelper_android_background android:background}</code></td><td></td></tr>\n <tr><td><code>{@link #ViewBackgroundHelper_backgroundTint com.megotechnologies.ecommerce_retronight:backgroundTint}</code></td><td></td></tr>\n <tr><td><code>{@link #ViewBackgroundHelper_backgroundTintMode com.megotechnologies.ecommerce_retronight:backgroundTintMode}</code></td><td></td></tr>\n </table>\n @see #ViewBackgroundHelper_android_background\n @see #ViewBackgroundHelper_backgroundTint\n @see #ViewBackgroundHelper_backgroundTintMode\n */\n public static final int[] ViewBackgroundHelper = {\n 0x010100d4, 0x7f0100ed, 0x7f0100ee\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#background}\n attribute's value can be found in the {@link #ViewBackgroundHelper} array.\n @attr name android:background\n */\n public static final int ViewBackgroundHelper_android_background = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#backgroundTint}\n attribute's value can be found in the {@link #ViewBackgroundHelper} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:backgroundTint\n */\n public static final int ViewBackgroundHelper_backgroundTint = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#backgroundTintMode}\n attribute's value can be found in the {@link #ViewBackgroundHelper} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>src_over</code></td><td>3</td><td></td></tr>\n<tr><td><code>src_in</code></td><td>5</td><td></td></tr>\n<tr><td><code>src_atop</code></td><td>9</td><td></td></tr>\n<tr><td><code>multiply</code></td><td>14</td><td></td></tr>\n<tr><td><code>screen</code></td><td>15</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:backgroundTintMode\n */\n public static final int ViewBackgroundHelper_backgroundTintMode = 2;\n /** Attributes that can be used with a ViewStubCompat.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #ViewStubCompat_android_id android:id}</code></td><td></td></tr>\n <tr><td><code>{@link #ViewStubCompat_android_inflatedId android:inflatedId}</code></td><td></td></tr>\n <tr><td><code>{@link #ViewStubCompat_android_layout android:layout}</code></td><td></td></tr>\n </table>\n @see #ViewStubCompat_android_id\n @see #ViewStubCompat_android_inflatedId\n @see #ViewStubCompat_android_layout\n */\n public static final int[] ViewStubCompat = {\n 0x010100d0, 0x010100f2, 0x010100f3\n };\n /**\n <p>This symbol is the offset where the {@link android.R.attr#id}\n attribute's value can be found in the {@link #ViewStubCompat} array.\n @attr name android:id\n */\n public static final int ViewStubCompat_android_id = 0;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#inflatedId}\n attribute's value can be found in the {@link #ViewStubCompat} array.\n @attr name android:inflatedId\n */\n public static final int ViewStubCompat_android_inflatedId = 2;\n /**\n <p>This symbol is the offset where the {@link android.R.attr#layout}\n attribute's value can be found in the {@link #ViewStubCompat} array.\n @attr name android:layout\n */\n public static final int ViewStubCompat_android_layout = 1;\n /** Attributes that can be used with a WalletFragmentOptions.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #WalletFragmentOptions_appTheme com.megotechnologies.ecommerce_retronight:appTheme}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentOptions_environment com.megotechnologies.ecommerce_retronight:environment}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentOptions_fragmentMode com.megotechnologies.ecommerce_retronight:fragmentMode}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentOptions_fragmentStyle com.megotechnologies.ecommerce_retronight:fragmentStyle}</code></td><td></td></tr>\n </table>\n @see #WalletFragmentOptions_appTheme\n @see #WalletFragmentOptions_environment\n @see #WalletFragmentOptions_fragmentMode\n @see #WalletFragmentOptions_fragmentStyle\n */\n public static final int[] WalletFragmentOptions = {\n 0x7f0100ef, 0x7f0100f0, 0x7f0100f1, 0x7f0100f2\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#appTheme}\n attribute's value can be found in the {@link #WalletFragmentOptions} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>holo_dark</code></td><td>0</td><td></td></tr>\n<tr><td><code>holo_light</code></td><td>1</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:appTheme\n */\n public static final int WalletFragmentOptions_appTheme = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#environment}\n attribute's value can be found in the {@link #WalletFragmentOptions} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>production</code></td><td>1</td><td></td></tr>\n<tr><td><code>test</code></td><td>3</td><td></td></tr>\n<tr><td><code>sandbox</code></td><td>0</td><td></td></tr>\n<tr><td><code>strict_sandbox</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:environment\n */\n public static final int WalletFragmentOptions_environment = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#fragmentMode}\n attribute's value can be found in the {@link #WalletFragmentOptions} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>buyButton</code></td><td>1</td><td></td></tr>\n<tr><td><code>selectionDetails</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:fragmentMode\n */\n public static final int WalletFragmentOptions_fragmentMode = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#fragmentStyle}\n attribute's value can be found in the {@link #WalletFragmentOptions} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:fragmentStyle\n */\n public static final int WalletFragmentOptions_fragmentStyle = 2;\n /** Attributes that can be used with a WalletFragmentStyle.\n <p>Includes the following attributes:</p>\n <table>\n <colgroup align=\"left\" />\n <colgroup align=\"left\" />\n <tr><th>Attribute</th><th>Description</th></tr>\n <tr><td><code>{@link #WalletFragmentStyle_buyButtonAppearance com.megotechnologies.ecommerce_retronight:buyButtonAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_buyButtonHeight com.megotechnologies.ecommerce_retronight:buyButtonHeight}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_buyButtonText com.megotechnologies.ecommerce_retronight:buyButtonText}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_buyButtonWidth com.megotechnologies.ecommerce_retronight:buyButtonWidth}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsBackground com.megotechnologies.ecommerce_retronight:maskedWalletDetailsBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsButtonBackground com.megotechnologies.ecommerce_retronight:maskedWalletDetailsButtonBackground}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance com.megotechnologies.ecommerce_retronight:maskedWalletDetailsButtonTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance com.megotechnologies.ecommerce_retronight:maskedWalletDetailsHeaderTextAppearance}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsLogoImageType com.megotechnologies.ecommerce_retronight:maskedWalletDetailsLogoImageType}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsLogoTextColor com.megotechnologies.ecommerce_retronight:maskedWalletDetailsLogoTextColor}</code></td><td></td></tr>\n <tr><td><code>{@link #WalletFragmentStyle_maskedWalletDetailsTextAppearance com.megotechnologies.ecommerce_retronight:maskedWalletDetailsTextAppearance}</code></td><td></td></tr>\n </table>\n @see #WalletFragmentStyle_buyButtonAppearance\n @see #WalletFragmentStyle_buyButtonHeight\n @see #WalletFragmentStyle_buyButtonText\n @see #WalletFragmentStyle_buyButtonWidth\n @see #WalletFragmentStyle_maskedWalletDetailsBackground\n @see #WalletFragmentStyle_maskedWalletDetailsButtonBackground\n @see #WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance\n @see #WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance\n @see #WalletFragmentStyle_maskedWalletDetailsLogoImageType\n @see #WalletFragmentStyle_maskedWalletDetailsLogoTextColor\n @see #WalletFragmentStyle_maskedWalletDetailsTextAppearance\n */\n public static final int[] WalletFragmentStyle = {\n 0x7f0100f3, 0x7f0100f4, 0x7f0100f5, 0x7f0100f6,\n 0x7f0100f7, 0x7f0100f8, 0x7f0100f9, 0x7f0100fa,\n 0x7f0100fb, 0x7f0100fc, 0x7f0100fd\n };\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buyButtonAppearance}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>google_wallet_classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>google_wallet_grayscale</code></td><td>2</td><td></td></tr>\n<tr><td><code>google_wallet_monochrome</code></td><td>3</td><td></td></tr>\n<tr><td><code>android_pay_dark</code></td><td>4</td><td></td></tr>\n<tr><td><code>android_pay_light</code></td><td>5</td><td></td></tr>\n<tr><td><code>android_pay_light_with_border</code></td><td>6</td><td></td></tr>\n<tr><td><code>classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>grayscale</code></td><td>2</td><td></td></tr>\n<tr><td><code>monochrome</code></td><td>3</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:buyButtonAppearance\n */\n public static final int WalletFragmentStyle_buyButtonAppearance = 3;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buyButtonHeight}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>match_parent</code></td><td>-1</td><td></td></tr>\n<tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:buyButtonHeight\n */\n public static final int WalletFragmentStyle_buyButtonHeight = 0;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buyButtonText}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>buy_with</code></td><td>5</td><td></td></tr>\n<tr><td><code>logo_only</code></td><td>6</td><td></td></tr>\n<tr><td><code>donate_with</code></td><td>7</td><td></td></tr>\n<tr><td><code>buy_with_google</code></td><td>1</td><td></td></tr>\n<tr><td><code>buy_now</code></td><td>2</td><td></td></tr>\n<tr><td><code>book_now</code></td><td>3</td><td></td></tr>\n<tr><td><code>donate_with_google</code></td><td>4</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:buyButtonText\n */\n public static final int WalletFragmentStyle_buyButtonText = 2;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#buyButtonWidth}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>May be a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\nAvailable units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\nin (inches), mm (millimeters).\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n<p>May be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>match_parent</code></td><td>-1</td><td></td></tr>\n<tr><td><code>wrap_content</code></td><td>-2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:buyButtonWidth\n */\n public static final int WalletFragmentStyle_buyButtonWidth = 1;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsBackground}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsBackground\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsButtonBackground}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>May be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsButtonBackground\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsButtonTextAppearance}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsButtonTextAppearance\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsHeaderTextAppearance}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsHeaderTextAppearance\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsLogoImageType}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be one of the following constant values.</p>\n<table>\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<colgroup align=\"left\" />\n<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n<tr><td><code>google_wallet_classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>google_wallet_monochrome</code></td><td>2</td><td></td></tr>\n<tr><td><code>android_pay</code></td><td>3</td><td></td></tr>\n<tr><td><code>classic</code></td><td>1</td><td></td></tr>\n<tr><td><code>monochrome</code></td><td>2</td><td></td></tr>\n</table>\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsLogoImageType\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsLogoTextColor}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\".\n<p>This may also be a reference to a resource (in the form\n\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\ntheme attribute (in the form\n\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\ncontaining a value of this type.\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsLogoTextColor\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9;\n /**\n <p>This symbol is the offset where the {@link com.megotechnologies.ecommerce_retronight.R.attr#maskedWalletDetailsTextAppearance}\n attribute's value can be found in the {@link #WalletFragmentStyle} array.\n\n\n <p>Must be a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\nor to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\".\n @attr name com.megotechnologies.ecommerce_retronight:maskedWalletDetailsTextAppearance\n */\n public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4;\n };\n}", "public class ZonConApplication extends Application implements ActivityLifecycleCallbacks, ComponentCallbacks2{\n\n\tpublic SharedPreferences sharedPreferences;\n\n\tpublic boolean wasInBackground = false;\n\tpublic String stateOfLifeCycle = \"\";\n\tpublic boolean ENABLE_SYNC = true;\n\tpublic boolean APP_EXIT_ON_BACK = false;\n\tpublic boolean ENABLE_BACK = true;\n\tpublic boolean ISGOINGOUTOFAPP = false;\n\tpublic boolean PREVENT_CLOSE_AND_SYNC = false;\n\t\n\tpublic Timer timer = null;\n\t\n\tContext context = null;\n\n\tpublic DbConnection conn;\n\n\t@Override\n\tpublic void onCreate() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onCreate();\n\n\t\tregisterActivityLifecycleCallbacks(this);\n\n\t\tsharedPreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);\n\n\t\tconn = new DbConnection(getApplicationContext());\n\t\tif(!conn.isOpen()) conn.open();\n\n\t}\n\n\t@Override\n\tpublic void onTerminate() {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onTerminate();\n\n\t\tif(conn.isOpen()) conn.close();\n\n\t}\n\n\n\t@Override\n\tpublic void onActivityCreated(Activity activity, Bundle savedInstanceState) {\n\t\t// TODO Auto-generated method stub\n\t\twasInBackground = false;\n\t\tstateOfLifeCycle = \"Create\";\n\t}\n\n\n\t@Override\n\tpublic void onActivityStarted(Activity activity) {\n\t\t// TODO Auto-generated method stub\n\t\tstateOfLifeCycle = \"Start\";\n\t}\n\n\n\t@Override\n\tpublic void onActivityResumed(Activity activity) {\n\t\t// TODO Auto-generated method stub\n\t\tstateOfLifeCycle = \"Resume\";\n\t\tif(timer != null) {\n\n\t\t\ttimer.cancel();\n\t\t\ttimer = null;\n\n\t\t}\n\t}\n\n\n\t@Override\n\tpublic void onActivityPaused(Activity activity) {\n\t\t// TODO Auto-generated method stub\n\t\tstateOfLifeCycle = \"Pause\";\n\t\tif(!ISGOINGOUTOFAPP && !PREVENT_CLOSE_AND_SYNC) {\n\n\t\t\tif(timer == null) {\n\n\t\t\t\ttimer = new Timer();\n\t\t\t\ttimer.schedule(new TimerTask() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\n\t\t\t\t\t\tif(context != null) {\n\n\t\t\t\t\t\t\t((Activity)context).finish();\n\t\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}, 2000);\n\n\t\t\t} else {\n\n\t\t\t\ttimer.cancel();\n\t\t\t\ttimer = null;\n\n\t\t\t}\n\n\t\t}\n\t}\n\n\n\t@Override\n\tpublic void onActivityStopped(Activity activity) {\n\t\t// TODO Auto-generated method stub\n\t\tstateOfLifeCycle = \"Stop\";\n\t}\n\n\n\t@Override\n\tpublic void onActivitySaveInstanceState(Activity activity, Bundle outState) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\n\t@Override\n\tpublic void onActivityDestroyed(Activity activity) {\n\t\t// TODO Auto-generated method stub\n\t\twasInBackground = false;\n\t\tstateOfLifeCycle = \"Destroy\";\n\t}\n\n\t@Override\n\tpublic void onTrimMemory(int level) {\n\t\t// TODO Auto-generated method stub\n\t\tif (stateOfLifeCycle.equals(\"Stop\")) {\n\t\t\twasInBackground = true;\n\t\t}\n\t\tsuper.onTrimMemory(level);\n\t}\n\n\n}", "public class DbConnection {\n\n\t// Database fields\n\t\n\tprivate SQLiteDatabase database;\n\tprivate ZCSQLiteHelper dbHelper;\n\t\n\tpublic DbConnection(Context context) {\n\t\tdbHelper = new ZCSQLiteHelper(context);\n\t}\n\n\tpublic void open() throws SQLException {\n\t\tdatabase = dbHelper.getWritableDatabase();\n\t}\n\n\tpublic void close() {\n\t\tdbHelper.close();\n\t}\n\t\n\tpublic Boolean isOpen() {\n\t\t\n\t\tif(database == null) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn database.isOpen();\n\t\t}\n\t\t\n\t}\n\t\n\tpublic Boolean isAvailale() {\n\t\t\n\t\twhile(database.isDbLockedByCurrentThread() || database.isDbLockedByOtherThreads()) {\n\t //db is locked, keep looping\n\t\t\ttry {\n\t\t\t\tRandom r = new Random();\n\t\t\t\tint i1 = r.nextInt(200 - 0) + 0;\n\t\t\t\t\n\t\t\t\tThread.sleep(i1);\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t }\n\t\treturn true;\n\t\t\n\t}\n\n\tpublic void insertRecord(HashMap<String, String> map) {\n\n\t\tContentValues values = new ContentValues();\n\n\t\tIterator i = map.keySet().iterator();\n\t\twhile(i.hasNext()) {\n\n\t\t\tString key = (String)i.next();\n\t\t\tString value = (String)map.get(key);\n\t\t\tvalues.put(key, value);\n\n\t\t}\n\n\t\tdatabase.insert(MainActivity.DB_TABLE, null, values);\n\n\t}\n\n\tpublic void deleteRecord(HashMap<String, String> map) {\n\n\t\tString WHERE_STR = \"\";\n\t\tIterator i = map.keySet().iterator();\n\t\tint j = 0;\n\t\twhile(i.hasNext()) {\n\n\t\t\tString key = (String)i.next();\n\t\t\tString value = (String)map.get(key);\n\n\t\t\tif(j == (map.size()- 1)) {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"'\");\n\n\t\t\t} else {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"' and \");\n\n\t\t\t}\n\n\t\t\tj++;\n\t\t}\n\n\t\tdatabase.delete(MainActivity.DB_TABLE, WHERE_STR, null);\n\n\t}\n\n\tpublic void updateRecord(HashMap<String, String> map, HashMap<String, String> mapWhere) {\n\n\t\tContentValues values = new ContentValues();\n\n\t\tIterator i = map.keySet().iterator();\n\t\twhile(i.hasNext()) {\n\n\t\t\tString key = (String)i.next();\n\t\t\tString value = (String)map.get(key);\n\t\t\tvalues.put(key, value);\n\n\t\t}\n\n\t\tString WHERE_STR = \"\";\n\t\ti = mapWhere.keySet().iterator();\n\t\tint j = 0;\n\t\twhile(i.hasNext()) {\n\n\t\t\tString key = (String)i.next();\n\t\t\tString value = (String)mapWhere.get(key);\n\n\t\t\tif(j == (mapWhere.size()- 1)) {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"'\");\n\n\t\t\t} else {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"' and \");\n\n\t\t\t}\n\n\t\t\tj++;\n\t\t}\n\n\t\tMLog.log(WHERE_STR);\n\n\t\tdatabase.update(MainActivity.DB_TABLE, values, WHERE_STR, null);\n\n\t}\n\n\tpublic ArrayList<HashMap<String, String>> retrieveDB() {\n\n\t\tCursor cursor = database.query(MainActivity.DB_TABLE, MainActivity.DB_ALL_COL, null, null, null, null, null);\n\n\t\tArrayList<HashMap<String, String>> arrRet = new ArrayList<HashMap<String,String>>();\n\n\t\tcursor.moveToFirst();\n\t\twhile(!cursor.isAfterLast()) {\n\n\t\t\tHashMap<String, String> mapRet = new HashMap<String, String>();\n\t\t\tfor(int j = 0; j < cursor.getColumnCount(); j++) {\n\n\t\t\t\tString key = cursor.getColumnName(j);\n\t\t\t\tString value = cursor.getString(j);\n\t\t\t\tmapRet.put(key, value);\n\n\t\t\t}\n\t\t\tarrRet.add(mapRet);\n\n\t\t}\n\n\t\treturn arrRet;\n\n\t}\n\n\tpublic ArrayList<HashMap<String, String>> retrieveRecords(HashMap<String, String> map) {\n\n\t\tString WHERE_STR = \"\";\n\t\tIterator i = map.keySet().iterator();\n\t\tint j = 0;\n\t\twhile(i.hasNext()) {\n\n\t\t\tString key = (String)i.next();\n\t\t\tString value = (String)map.get(key);\n\n\t\t\tif(j == (map.size()- 1)) {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"'\");\n\n\t\t\t} else {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"' and \");\n\n\t\t\t}\n\n\t\t\tj++;\n\t\t}\n\n\t\tCursor cursor = database.query(MainActivity.DB_TABLE, MainActivity.DB_ALL_COL, WHERE_STR, null, null, null, null);\n\n\t\tArrayList<HashMap<String, String>> arrRet = new ArrayList<HashMap<String,String>>();\n\n\t\tcursor.moveToFirst();\n\t\twhile(!cursor.isAfterLast()) {\n\n\t\t\tHashMap<String, String> mapRet = new HashMap<String, String>();\n\t\t\tfor(j = 0; j < cursor.getColumnCount(); j++) {\n\n\t\t\t\tString key = cursor.getColumnName(j);\n\t\t\t\tString value = cursor.getString(j);\n\t\t\t\tmapRet.put(key, value);\n\t\t\t\t//MLog.log(\"Retrieving \" + key + \" \" + value);\n\n\t\t\t}\n\t\t\tarrRet.add(mapRet);\n\n\t\t\tcursor.moveToNext();\n\n\t\t}\n\n\t\treturn arrRet;\n\n\t}\n\n\tpublic String retrieveId(HashMap<String, String> map) {\n\n\t\tString WHERE_STR = \"\";\n\t\tIterator i = map.keySet().iterator();\n\t\tint j = 0;\n\t\twhile(i.hasNext()) {\n\n\t\t\tString key = (String)i.next();\n\t\t\tString value = (String)map.get(key);\n\n\t\t\tif(j == (map.size()- 1)) {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"'\");\n\n\t\t\t} else {\n\n\t\t\t\tWHERE_STR += (key + \" = '\" + value + \"' and \");\n\n\t\t\t}\n\n\t\t\tj++;\n\t\t}\n\n\t\t//MLog.log(\"Retrieving ID where \" + WHERE_STR);\n\n\t\tCursor cursor = database.query(MainActivity.DB_TABLE, MainActivity.DB_ALL_COL, WHERE_STR, null, null, null, null);\n\t\tif(cursor.getCount() > 0) {\n\t\t\tcursor.moveToFirst();\n\t\t\treturn cursor.getString(0);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t}\n\n\tpublic void clearPendingCartRecords() {\n\n\t\tMLog.log(\"Insode clear pending cart records\");\n\t\t\n\t\tString WHERE_CART_STR = \"\";\n\n\t\tWHERE_CART_STR += MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_CART + \"' and \";\n\t\tWHERE_CART_STR += MainActivity.DB_COL_CART_CART_ISOPEN + \" = '\" + MainActivity.DB_RECORD_VALUE_CART_OPEN + \"'\";\n\t\t\n\t\tCursor cursorCart = database.query(MainActivity.DB_TABLE, MainActivity.DB_ALL_COL, WHERE_CART_STR, null, null, null, null);\n\t\tif(cursorCart.getCount() > 0) {\n\n\t\t\tcursorCart.moveToFirst();\n\n\t\t\tlong timeCurrent = System.currentTimeMillis();\n\t\t\tString strTime = cursorCart.getString(cursorCart.getColumnIndex(MainActivity.DB_COL_TIMESTAMP));\n\n\n\t\t\tMLog.log(\"Cart time =\" + strTime);\n\n\t\t\t\n\t\t\tif(strTime != null) {\n\n\t\t\t\tlong cartTime = Long.parseLong(strTime);\n\n\t\t\t\tMLog.log(\"Cart time difference = \" + (timeCurrent - cartTime));\n\t\t\t\t\n\t\t\t\tif((timeCurrent - cartTime) > MainActivity.TIMEOUT_CART_CLEAR) {\n\n\t\t\t\t\tString _idCart = cursorCart.getString(cursorCart.getColumnIndex(MainActivity.DB_COL_ID));\n\t\t\t\t\tString WHERE_STR = \"\";\n\t\t\t\t\tWHERE_STR += MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_CART_ITEM + \"' and \";\n\t\t\t\t\tWHERE_STR += MainActivity.DB_COL_FOREIGN_KEY + \" = '\" + _idCart + \"'\";\n\t\t\t\t\tdatabase.delete(MainActivity.DB_TABLE, WHERE_STR, null);\n\n\t\t\t\t\tdatabase.delete(MainActivity.DB_TABLE, WHERE_CART_STR, null);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tString _idCart = cursorCart.getString(cursorCart.getColumnIndex(MainActivity.DB_COL_ID));\n\t\t\t\tString WHERE_STR = \"\";\n\t\t\t\tWHERE_STR += MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_CART_ITEM + \"' and \";\n\t\t\t\tWHERE_STR += MainActivity.DB_COL_FOREIGN_KEY + \" = '\" + _idCart + \"'\";\n\t\t\t\tdatabase.delete(MainActivity.DB_TABLE, WHERE_STR, null);\n\n\t\t\t\tdatabase.delete(MainActivity.DB_TABLE, WHERE_CART_STR, null);\n\t\t\t\t\n\t\t\t}\n\n\t\t}\n\n\n\t}\n\n\tpublic void clearDynamicRecords() {\n\n\t\tString WHERE_STR = MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_ITEM + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_PICTURE + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_URL + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_LOCATION + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_CONTACT + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_ATTACHMENT + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_DISCOUNT + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_COUPON + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_TAX_1 + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_TAX_2 + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_CART_ITEM + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_CART + \"' or \"\n\t\t\t\t+ MainActivity.DB_COL_TYPE + \" = '\" + MainActivity.DB_RECORD_TYPE_STREAM + \"'\";\n\n\t\tdatabase.delete(MainActivity.DB_TABLE, WHERE_STR, null);\n\n\t\t// Delete open cart if it is expired...\n\t\tclearPendingCartRecords();\n\n\t}\n\n\tpublic void printRecords() {\n\n\t\tMLog.log(\"Printing...\");\n\t\tCursor cursor = database.query(MainActivity.DB_TABLE, MainActivity.DB_ALL_COL, null, null, null, null, null);\n\t\tcursor.moveToFirst();\n\t\twhile(!cursor.isAfterLast()) {\n\n\t\t\tString str = \"\";\n\t\t\tfor(int i = 0; i < cursor.getColumnCount(); i++) {\n\n\t\t\t\tstr += cursor.getColumnName(i) + \"=\" + cursor.getString(i) + \" \"; \n\n\t\t\t}\n\n\t\t\tMLog.log(str);\n\t\t\tcursor.moveToNext();\n\t\t}\n\n\n\t}\n\n}", "public class SplashActivity extends Activity{\n\t\n\tTextView tvZonCon;\n\t\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onCreate(savedInstanceState);\n\t\trequestWindowFeature(Window.FEATURE_NO_TITLE); \n\t\tthis.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);\n\t\tsetContentView(R.layout.activity_splash);\n\t\t\n\t\tTimer timer = new Timer();\n\t\ttimer.schedule(new TimerTask() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\n\t\t\t\tIntent intent = new Intent(SplashActivity.this, MainActivity.class);\n\t\t\t\tstartActivity(intent);\n\t\t\t\tfinish();\n\t\t\t\t\n\t\t\t}\n\t\t}, MainActivity.SPLASH_DURATION);\n\n\t\ttvZonCon = (TextView)findViewById(R.id.tv_zoncon);\n\t\ttvZonCon.setShadowLayer(2, 1, 1, getResources().getColor(R.color.black));\n\t\ttvZonCon.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);\n\t\ttvZonCon.setVisibility(RelativeLayout.GONE);\n\t\t\n\t}\n\n}", "public class MLog {\n\t\n\tpublic static void log(String str) {\n\t\t\n\t\tif(MainActivity.LOG) {\n\t\t\t\n\t\t\tLog.i(\"mego\", str);\n\t\t\t\n\t\t}\n\t\t\n\t}\n\t\n\n}" ]
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.support.v4.app.NotificationCompat; import com.megotechnologies.ecommerce_retronight.MainActivity; import com.megotechnologies.ecommerce_retronight.R; import com.megotechnologies.ecommerce_retronight.ZonConApplication; import com.megotechnologies.ecommerce_retronight.db.DbConnection; import com.megotechnologies.ecommerce_retronight.loading.SplashActivity; import com.megotechnologies.ecommerce_retronight.utilities.MLog; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
package com.megotechnologies.ecommerce_retronight.push; public class NotificationService extends Service { public static final int NOTIFICATION_ID = 0; Thread checkNotifThread; NotificationManager mNotificationManager; String previousNotifMsg = ""; Boolean RUN_FLAG = true; DbConnection dbC; public ZonConApplication app; private class CheckNotifications implements Runnable { @Override public void run() { // TODO Auto-generated method stub while(RUN_FLAG) { HashMap<String, String> map = new HashMap<String, String>();
map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_STREAM);
0
Rsgm/Hakd
core/src/game/GamePlay.java
[ "public class Character {\n String name; // does not really change\n Network network; // meant to be used as the players network base\n City city;\n\n\n public Character(Network network, String name, City city) {\n this.network = network;\n this.name = name;\n this.city = city;\n }\n\n public void update() { // updates the character and runs its AI\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 Network getNetwork() {\n return network;\n }\n\n public void setNetwork(Network network) {\n this.network = network;\n }\n\n public City getCity() {\n return city;\n }\n}", "public class City {\n public static final int width = 150;\n public static final int height = 150;\n\n private final Vector2 position;\n private final Sprite icon;\n private final String name;\n private final float density;\n private final Map<String, Network> networks;\n\n public City(Vector2 position) {\n this.position = position;\n\n icon = Hakd.assets.get(\"lTextures.txt\", TextureAtlas.class).createSprite(\"circle\");\n icon.setBounds(position.x - width / 2, position.y - height / 2, width, height);\n\n name = Util.ganerateCityName();\n density = (float) Noise.DENSITY.getValue(position.x, 0, position.y);\n networks = new HashMap<String, Network>();\n }\n\n public void addNetwork(Network n) {\n networks.put(n.getIp(), n);\n }\n\n public void removeNetwork(Network n) {\n networks.remove(n);\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n public Sprite getIcon() {\n return icon;\n }\n\n public Vector2 getPosition() {\n return position;\n }\n\n public String getName() {\n return name;\n }\n\n public float getDensity() {\n return density;\n }\n\n public Map<String, Network> getNetworks() {\n return networks;\n }\n}", "public class Player extends Character {\n private Room room;\n private DeviceScene openWindow;\n\n // --------methods--------\n public Player(String name, City city) {\n super(null, name, city);\n this.name = name;\n }\n\n @Override\n public void update() {\n }\n\n public DeviceScene getOpenWindow() {\n return openWindow;\n }\n\n public void setOpenWindow(DeviceScene openWindow) {\n this.openWindow = openWindow;\n }\n\n public Room getRoom() {\n return room;\n }\n\n public void setRoom(Room room) {\n this.room = room;\n }\n}", "public class Room {\n public static int TILE_SIZE;\n public static int ROOM_HEIGHT;\n\n private final Character player;\n private final Network network;\n private final Map<String, Device> devices;\n private final Map<Vector2, DeviceTile> deviceTileMap;\n\n private final TiledMap map;\n\n private final TiledMapTileLayer floorLayer;\n private final TiledMapTileLayer wallLayer;\n private final MapLayer deviceLayer; // if it matters, maybe rename this to wall/boundary layer\n private final TiledMapTileLayer objectLayer; // Interactable tiles?\n\n private final GamePlay gamePlay;\n\n public Room(Character player, GamePlay gamePlay, RoomMap roomMap) {\n this.player = player;\n this.gamePlay = gamePlay;\n\n ((Player) player).setRoom(this);\n deviceTileMap = new HashMap<Vector2, DeviceTile>();\n\n\n map = new TmxMapLoader().load(Util.ASSETS + \"maps/\" + roomMap.toString() + \".tmx\");\n\n floorLayer = (TiledMapTileLayer) map.getLayers().get(\"floor\");\n wallLayer = (TiledMapTileLayer) map.getLayers().get(\"wall\");\n deviceLayer = map.getLayers().get(\"devices\");\n objectLayer = (TiledMapTileLayer) map.getLayers().get(\"objects\");\n\n ROOM_HEIGHT = floorLayer.getHeight();\n TILE_SIZE = (int) floorLayer.getTileWidth();\n\n buildRoom();\n gamePlay.getGameScreen().setRenderer(new IsometricTiledMapRenderer(map, 1f / TILE_SIZE)); // don't let this round, that is why 1 is a floatmap\n\n if (player.getNetwork() == null) {\n City playerCity = player.getCity();\n List<InternetProviderNetwork> isps = new ArrayList<InternetProviderNetwork>(5);\n for (Network n : playerCity.getNetworks().values()) {\n if (n instanceof InternetProviderNetwork) {\n isps.add((InternetProviderNetwork) n);\n }\n }\n\n network = NetworkFactory.createPlayerNetwork((Player) player, playerCity, gamePlay.getInternet());\n InternetProviderNetwork isp = isps.get((int) (Math.random() * isps.size()));\n gamePlay.getInternet().addNetworkToInternet(network, isp);\n playerCity.addNetwork(network);\n network.setDeviceLimit(1);\n\n Device device = DeviceFactory.createDevice(0, Device.DeviceType.SERVER);\n HakdSprite tile = new HakdSprite(Hakd.assets.get(\"nTextures.txt\", TextureAtlas.class).findRegion(\"d0\"));\n tile.setSize(tile.getWidth() / TILE_SIZE, tile.getHeight() / TILE_SIZE);\n tile.setObject(device);\n device.setTile(tile);\n network.addDevice(device);\n } else {\n network = player.getNetwork();\n }\n int deviceLimit = deviceLayer.getObjects().getCount();\n network.setDeviceLimit(deviceLimit);\n devices = network.getDevices();\n }\n\n private void buildRoom() {\n for (MapObject o : deviceLayer.getObjects()) {\n if (!(o instanceof RectangleMapObject)) {\n continue;\n }\n RectangleMapObject r = (RectangleMapObject) o; // all objects on the device layer will be rectangles\n\n int x = Integer.parseInt((String) r.getProperties().get(\"x\"));\n int y = Integer.parseInt((String) r.getProperties().get(\"y\"));\n DeviceTile tile = new DeviceTile(x, y);\n deviceTileMap.put(tile.isoPos, tile);\n }\n }\n\n /**\n * Finds the device at the specified isometric coordinates.\n *\n * @return The device found.\n * The string \"other\", if no device was found there.\n * Null if the tile in the map does not have an object.\n */\n\n public DeviceTile getDeviceAtTile(int x, int y) {\n return deviceTileMap.get(new Vector2(x, y));\n }\n\n public void addDevice(Device device) {\n if (deviceTileMap.containsKey(device.getIsoPos())) {\n deviceTileMap.get(device.getIsoPos()).device = device;\n } else { // if the device is not in the room, assign it to a random tile\n for (DeviceTile tile : deviceTileMap.values()) { // due to the nature of a set, this should be considered random\n if (tile.device == null) {\n Vector2 v = tile.getIsoPos();\n device.setIsoPos(v);\n tile.setDevice(device);\n break;\n }\n }\n }\n\n device.setDeviceScene(new DeviceScene(gamePlay.getGameScreen(), device));\n }\n\n public void removeDevice(Device device) {\n deviceTileMap.get(device.getIsoPos()).device = null;\n }\n\n public enum RoomMap {\n room1(), room2(), room3(), room4(), room5(), room6();\n\n private RoomMap() {\n }\n }\n\n public void dispose() {\n map.dispose();\n }\n\n public static class DeviceTile {\n final Vector2 isoPos;\n Device device;\n\n private static final Sprite TABLE;\n private final HakdSprite table; // the default sprite if there is no device, or the empty device tile\n\n static {\n TABLE = new Sprite(Hakd.assets.get(\"nTextures.txt\", TextureAtlas.class).findRegion(\"d-1\"));\n TABLE.setSize(TABLE.getWidth() / TILE_SIZE, TABLE.getHeight() / TILE_SIZE);\n }\n\n public DeviceTile(int x, int y) {\n isoPos = new Vector2(x, y);\n\n table = new HakdSprite(TABLE);\n Vector2 pos = Util.isoToOrtho(isoPos.x, isoPos.y);\n table.setPosition(pos.x, pos.y);\n }\n\n public Vector2 getIsoPos() {\n return isoPos;\n }\n\n public HakdSprite getTile() {\n if (device == null || device.getTile() == null) {\n return table;\n }\n\n return device.getTile();\n }\n\n public Device getDevice() {\n return device;\n }\n\n public void setDevice(Device device) {\n this.device = device;\n\n if (device.getTile() != null) {\n device.getTile().setPosition(table.getX(), table.getY());\n }\n }\n }\n\n public Character getPlayer() {\n return player;\n }\n\n public Network getNetwork() {\n return network;\n }\n\n public TiledMap getMap() {\n return map;\n }\n\n public TiledMapTileLayer getFloorLayer() {\n return floorLayer;\n }\n\n public GamePlay getGamePlay() {\n return gamePlay;\n }\n\n public TiledMapTileLayer getWallLayer() {\n return wallLayer;\n }\n\n public MapLayer getDeviceLayer() {\n return deviceLayer;\n }\n\n public TiledMapTileLayer getObjectLayer() {\n return objectLayer;\n }\n\n public Map<String, Device> getDevices() {\n return devices;\n }\n\n public Map<Vector2, DeviceTile> getDeviceTileMap() {\n return Collections.unmodifiableMap(deviceTileMap);\n }\n}", "public class GameScreen extends HakdScreen {\n private String playerName;\n private Character player;\n private Room room;\n private DeviceScene deviceScene = null;\n private MapScreen map;\n private IsometricTiledMapRenderer renderer; // it says this is experimental, but it was an old article\n private GameInput input;\n\n private boolean firstTimeShown = true;\n private final Stage dialogStage = new Stage(); // TODO this will be the overlay\n\n public GameScreen(Hakd game, String playerName) {\n super(game);\n this.playerName = playerName;\n }\n\n @Override\n public void show() {\n super.show();\n\n // this should all be in the constructor, but there is a bug where the top right 1/4th of the screen is white and all textures are white, this somehow works\n if (firstTimeShown) {\n firstTimeShown = false;\n\n for (short i = 1; i < 256; i++) {\n Internet.ipNumbers.add(i);\n }\n\n GamePlay gamePlay = new GamePlay(this, playerName);\n (game).setGamePlay(gamePlay);\n\n cam = new OrthographicCamera();\n ((OrthographicCamera) cam).setToOrtho(false, room.getFloorLayer().getWidth(), room.getFloorLayer().getHeight());\n cam.update();\n\n renderer.setView((OrthographicCamera) cam);\n\n cam.position.x = room.getFloorLayer().getWidth() / 2;\n cam.position.y = 0;\n\n map = new MapScreen(game, gamePlay.getInternet());\n input = new GameInput(game, (OrthographicCamera) cam);\n\n Gdx.input.setInputProcessor(input);\n }\n Gdx.gl.glClearColor(0, 0, 0, 0);\n }\n\n @Override\n public void render(float delta) {\n super.render(delta);\n\n SpriteBatch rBatch = (SpriteBatch) renderer.getBatch();\n renderer.setView((OrthographicCamera) cam);\n renderer.render();\n\n rBatch.begin();\n for (Room.DeviceTile t : room.getDeviceTileMap().values()) {\n t.getTile().draw(rBatch);\n }\n rBatch.end();\n\n if (deviceScene != null) {\n deviceScene.render();\n }\n\n dialogStage.act(Gdx.graphics.getDeltaTime());\n dialogStage.draw();\n }\n\n @Override\n public void dispose() {\n super.dispose();\n room.dispose();\n game.getGamePlay().dispose();\n game.setGamePlay(null);\n }\n\n @Override\n public void hide() {\n Gdx.input.setInputProcessor(null);\n }\n\n public Character getPlayer() {\n return player;\n }\n\n public void setPlayer(Player player) {\n this.player = player;\n }\n\n public Room getRoom() {\n return room;\n }\n\n public void setRoom(Room room) {\n this.room = room;\n }\n\n public IsometricTiledMapRenderer getRenderer() {\n return renderer;\n }\n\n public DeviceScene getDeviceScene() {\n return deviceScene;\n }\n\n public void setDeviceScene(DeviceScene deviceScene) {\n this.deviceScene = deviceScene;\n }\n\n public MapScreen getMap() {\n return map;\n }\n\n public GameInput getInput() {\n return input;\n }\n\n public void setInput(GameInput input) {\n this.input = input;\n }\n\n public void setRenderer(IsometricTiledMapRenderer renderer) {\n this.renderer = renderer;\n }\n}", "public class MapScreen extends HakdScreen {\n private final Internet internet;\n\n private final GameScreen gameScreen;\n private final MapInput input;\n private float time = 0;\n\n private final SpriteBatch territoryBatch;\n\n private final Set<Sprite> networkSprites;\n private final Set<Sprite> ispSprites;\n private final Set<Sprite> territorySprites;\n private final Set<Sprite> backboneSprites;\n\n private final Set<Line> connectionLines; // change this to a line set\n private final Set<Line> parentLines;\n private final Set<Line> backboneLines;\n\n private Mesh connectionLinesMesh;\n private Mesh parentLinesMesh;\n private Mesh backboneLinesMesh;\n\n private Texture land;\n private Texture density;\n private Texture politics;\n private Texture ethics;\n private Texture country;\n private Texture income;\n private Texture crime;\n\n BitmapFont textFont = assets.get(\"skins/font/Fonts_7.fnt\", BitmapFont.class);\n\n private Noise.NoiseType currentBackground;\n\n public static final int NOISE_GENERATION_SIZE = 800; // how many points to draw. default: 800, best quality would be around 2500\n public static final int NOISE_DISPLAY_SIZE = 50000; // how large of an area to spread the points out on. default: 50000\n public static final int INITIAL_TRIANGLE_SIZE = MapScreen.NOISE_DISPLAY_SIZE * 1000;\n// private overlay mapOverlay;\n\n public MapScreen(Hakd game, Internet internet) {\n super(game);\n\n this.internet = internet;\n this.gameScreen = (GameScreen) game.getScreen();\n\n territoryBatch = new SpriteBatch();\n networkSprites = new HashSet<Sprite>(internet.getNetworkMap().size());\n ispSprites = new HashSet<Sprite>(internet.getInternetProviderNetworksMap().size());\n territorySprites = new HashSet<Sprite>(internet.getInternetProviderNetworksMap().size());\n backboneSprites = new HashSet<Sprite>(internet.getBackboneProviderNetworksMap().size());\n\n connectionLines = new HashSet<Line>(50);\n parentLines = new HashSet<Line>(internet.getBackboneProviderNetworksMap().size());\n backboneLines = new HashSet<Line>(internet.getBackboneProviderNetworksMap().size());\n\n try {\n generateNoiseTexture(Noise.NoiseType.TERRAIN);\n generateNoiseTexture(Noise.NoiseType.DENSITY);\n generateNoiseTexture(Noise.NoiseType.COUNTRY);\n generateNoiseTexture(Noise.NoiseType.ETHICS);\n generateNoiseTexture(Noise.NoiseType.POLITICS);\n generateNoiseTexture(Noise.NoiseType.INCOME);\n generateNoiseTexture(Noise.NoiseType.CRIME);\n } catch (ExceptionInvalidParam exceptionInvalidParam) {\n exceptionInvalidParam.printStackTrace();\n }\n currentBackground = Noise.NoiseType.TERRAIN;\n\n cam = new OrthographicCamera();\n ((OrthographicCamera) cam).setToOrtho(false, width, height);\n\n input = new MapInput(this);\n }\n\n @Override\n public void show() {\n super.show();\n\n cam.position.set(gameScreen.getPlayer().getNetwork().getPos(), 0);\n ((OrthographicCamera) cam).zoom = 2;\n cam.update();\n\n reloadSprites();\n\n// mapOverlay = new overlay();\n\n Gdx.gl.glClearColor(1, 1, 1, 1);\n Gdx.input.setInputProcessor(input);\n }\n\n @Override\n public void render(float delta) {\n super.render(delta);\n\n// System.out.println((int) (1 / delta));\n time += delta;\n if (time >= 1) {\n reloadSprites();\n time = 0;\n }\n\n renderBackground();\n renderSprites();\n renderLines();\n\n// mapOverlay.render();\n }\n\n private void renderBackground() {\n territoryBatch.setProjectionMatrix(cam.combined);\n territoryBatch.begin();\n switch (currentBackground) {\n case TERRAIN:\n territoryBatch.draw(land,\n -NOISE_DISPLAY_SIZE / 2, -NOISE_DISPLAY_SIZE / 2, NOISE_DISPLAY_SIZE, NOISE_DISPLAY_SIZE);\n break;\n case DENSITY:\n territoryBatch.draw(density,\n -NOISE_DISPLAY_SIZE / 2, -NOISE_DISPLAY_SIZE / 2, NOISE_DISPLAY_SIZE, NOISE_DISPLAY_SIZE);\n break;\n case POLITICS:\n territoryBatch.draw(politics,\n -NOISE_DISPLAY_SIZE / 2, -NOISE_DISPLAY_SIZE / 2, NOISE_DISPLAY_SIZE, NOISE_DISPLAY_SIZE);\n break;\n case ETHICS:\n territoryBatch.draw(ethics,\n -NOISE_DISPLAY_SIZE / 2, -NOISE_DISPLAY_SIZE / 2, NOISE_DISPLAY_SIZE, NOISE_DISPLAY_SIZE);\n break;\n case COUNTRY:\n territoryBatch.draw(country,\n -NOISE_DISPLAY_SIZE / 2, -NOISE_DISPLAY_SIZE / 2, NOISE_DISPLAY_SIZE, NOISE_DISPLAY_SIZE);\n break;\n case INCOME:\n territoryBatch.draw(income,\n -NOISE_DISPLAY_SIZE / 2, -NOISE_DISPLAY_SIZE / 2, NOISE_DISPLAY_SIZE, NOISE_DISPLAY_SIZE);\n }\n territoryBatch.end();\n }\n\n private void renderSprites() {\n batch.setProjectionMatrix(cam.combined);\n batch.begin();\n\n// for (Sprite s : territorySprites) {\n// s.draw(batch);\n// }\n\n for (Sprite s : backboneSprites) {\n s.draw(batch);\n }\n\n for (Sprite s : ispSprites) {\n s.draw(batch);\n }\n\n for (Sprite s : networkSprites) {\n s.draw(batch);\n }\n\n// for (Sprite s : connectionLineSprites) {\n// s.draw(batch);\n// }\n\n for (City c : game.getGamePlay().getCityMap().values()) {\n c.getIcon().draw(batch);\n textFont.draw(batch, c.getName(), c.getPosition().x, c.getPosition().y + 80);\n }\n batch.end();\n }\n\n private void renderLines() {\n ShaderProgram lines = shaders.get(\"lines\");\n\n lines.begin();\n lines.setUniformMatrix(\"u_worldView\", cam.combined);\n\n if (backboneLinesMesh != null && backboneLinesMesh.getNumVertices() > 0) {\n lines.setAttributef(\"a_color\", 255f / 255f, 149f / 255f, 38f / 255f, 1);\n backboneLinesMesh.render(lines, GL20.GL_LINES);\n }\n\n if (parentLinesMesh != null && parentLinesMesh.getNumVertices() > 0) {\n lines.setAttributef(\"a_color\", 0f / 255f, 255f / 255f, 142f / 255f, 1);\n parentLinesMesh.render(lines, GL20.GL_LINES);\n }\n\n// if (connectionLinesMesh != null && connectionLinesMesh.getNumVertices() > 0) {\n// lines.setAttributef(\"a_color\", 0f / 255f, 255f / 255f, 142f / 255f, 1);\n// connectionLinesMesh.render(shaders.getCurrent(), GL20.GL_LINES);\n// }\n\n lines.end();\n }\n\n private void reloadSprites() {\n networkSprites.clear();\n ispSprites.clear();\n territorySprites.clear();\n backboneSprites.clear();\n\n backboneLines.clear();\n parentLines.clear();\n connectionLines.clear();\n\n for (Network n : internet.getNetworkMap().values()) {\n if (n instanceof BackboneProviderNetwork) {\n backboneSprites.add(n.getMapIcon());\n } else if (n instanceof InternetProviderNetwork) {\n ispSprites.add(n.getMapIcon());\n parentLines.add(n.getMapParentLine());\n } else {\n networkSprites.add(n.getMapIcon());\n parentLines.add(n.getMapParentLine());\n }\n }\n\n drawBackboneLines();\n\n // create backbone line mesh\n float[] vertexArray = fillLineVertexArray(backboneLines, new Color(255f / 255f, 149f / 255f, 38f / 255f, 1));\n backboneLinesMesh = new Mesh(true, vertexArray.length, 0, VertexAttribute.Position());\n backboneLinesMesh.setVertices(vertexArray);\n\n // create parent line mesh\n vertexArray = fillLineVertexArray(parentLines, new Color(0f / 255f, 255f / 255f, 142f / 255f, 1));\n parentLinesMesh = new Mesh(true, vertexArray.length, 0, VertexAttribute.Position());\n parentLinesMesh.setVertices(vertexArray);\n\n // create connection line mesh\n vertexArray = fillLineVertexArray(connectionLines, new Color(0f / 255f, 0f / 255f, 0f / 255f, 1));\n connectionLinesMesh = new Mesh(true, vertexArray.length, 0, VertexAttribute.Position());\n connectionLinesMesh.setVertices(vertexArray);\n }\n\n /**\n * Fills a vertex array to be used in openGL rendering for the lines.\n *\n * @param lineList which line list to use\n * @param color the color to use\n * @return\n */\n private float[] fillLineVertexArray(Set<Line> lineList, Color color) {\n List<Float> vertexList = new ArrayList<Float>();\n for (Line line : lineList) {\n // position A\n vertexList.add(line.getPointA().x);\n vertexList.add(line.getPointA().y);\n vertexList.add(0f);\n\n // position B\n vertexList.add(line.getPointB().x);\n vertexList.add(line.getPointB().y);\n vertexList.add(0f);\n }\n\n float[] vertexArray = new float[vertexList.size()]; // probably could only use an array and set the size to linelist.size*3 or something\n int i = 0;\n for (Float v : vertexList) {\n vertexArray[i++] = (v != null ? v : 0f); // Or whatever default you want.\n }\n return vertexArray;\n }\n\n\n /**\n * Generate the noise texture to use for the map, then renders it\n *\n * @param type\n * @throws ExceptionInvalidParam\n */\n private void generateNoiseTexture(Noise.NoiseType type) throws ExceptionInvalidParam {\n ModuleBase noise = null;\n RendererImage renderer = new RendererImage();\n double[][] noiseArray = new double[NOISE_GENERATION_SIZE][NOISE_GENERATION_SIZE];\n\n switch (type) {\n case TERRAIN:\n if (land != null) {\n return;\n }\n noise = Noise.TERRAIN;\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(10, 10, 80, 255));\n renderer.addGradientPoint(1, new ColorCafe(39, 140, 255, 255));\n break;\n case DENSITY:\n if (density != null) {\n return;\n }\n noise = Noise.DENSITY;\n renderer.clearGradient();\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(0, 0, 0, 255));\n renderer.addGradientPoint(1, new ColorCafe(50, 50, 255, 255));\n break;\n case COUNTRY:\n if (country != null) {\n return;\n }\n noise = Noise.COUNTRY;\n renderer.clearGradient();\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(0, 0, 0, 255));\n renderer.addGradientPoint(1, new ColorCafe(0, 0, 0, 255));\n break;\n case POLITICS:\n if (politics != null) {\n return;\n }\n noise = Noise.POLITICS;\n renderer.clearGradient();\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(0, 0, 0, 255));\n renderer.addGradientPoint(1, new ColorCafe(255, 0, 0, 255));\n break;\n case ETHICS:\n if (ethics != null) {\n return;\n }\n noise = Noise.ETHICS;\n renderer.clearGradient();\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(0, 0, 0, 255));\n renderer.addGradientPoint(1, new ColorCafe(255, 255, 255, 255));\n break;\n case INCOME:\n if (income != null) {\n return;\n }\n noise = Noise.INCOME;\n renderer.clearGradient();\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(0, 0, 0, 255));\n renderer.addGradientPoint(1, new ColorCafe(0, 255, 0, 255));\n break;\n case CRIME:\n if (income != null) {\n return;\n }\n noise = Noise.INCOME;\n renderer.clearGradient();\n renderer.clearGradient();\n renderer.addGradientPoint(-1, new ColorCafe(0, 0, 0, 255));\n renderer.addGradientPoint(1, new ColorCafe(255, 160, 80, 255));\n break;\n }\n\n // fill noise array\n for (int y = 0; y < NOISE_GENERATION_SIZE; y++) {\n for (int x = 0; x <\n NOISE_GENERATION_SIZE; x++) { // maybe use separate threads to get the values and set them to arrays. e.g. float[250][5000] ten times\n float f = (float) noise.getValue(\n (x - NOISE_GENERATION_SIZE / 2) * NOISE_DISPLAY_SIZE / NOISE_GENERATION_SIZE, 0,\n (y - NOISE_GENERATION_SIZE / 2) * NOISE_DISPLAY_SIZE / NOISE_GENERATION_SIZE);\n noiseArray[x][NOISE_GENERATION_SIZE - y - 1] = f;\n }\n Gdx.app.debug(\"Filling Noise Array\", (float) y / NOISE_GENERATION_SIZE * 100 + \"% done\");\n }\n\n Pixmap pixmap = new Pixmap(NOISE_GENERATION_SIZE, NOISE_GENERATION_SIZE, Pixmap.Format.RGBA8888);\n NoiseMap noiseMap = new NoiseMap(NOISE_GENERATION_SIZE, NOISE_GENERATION_SIZE);\n noiseMap.setNoiseMap(noiseArray);\n ImageCafe imageCafe = new ImageCafe(NOISE_GENERATION_SIZE, NOISE_GENERATION_SIZE);\n renderer.setSourceNoiseMap(noiseMap);\n renderer.setDestImage(imageCafe);\n renderer.render();\n\n // fill color array\n for (int y = 0; y < NOISE_GENERATION_SIZE; y++) {\n for (int x = 0; x <\n NOISE_GENERATION_SIZE; x++) { // maybe use separate threads to get the values and set them to arrays. e.g. float[250][5000] ten times\n ColorCafe color = imageCafe.getValue(x, y);\n int c = Color.rgba8888(\n (float) color.getRed() / 255f,\n (float) color.getGreen() / 255f,\n (float) color.getBlue() / 255f, (float) color.getAlpha() / 255f);\n pixmap.drawPixel(x, y, c);\n }\n Gdx.app.debug(\"Filling Pixmap\", (float) y / NOISE_GENERATION_SIZE * 100 + \"% done\");\n }\n\n switch (type) {\n case TERRAIN:\n land = new Texture(pixmap);\n land.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n case DENSITY:\n density = new Texture(pixmap);\n density.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n case COUNTRY:\n country = new Texture(pixmap);\n country.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n case POLITICS:\n politics = new Texture(pixmap);\n politics.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n case ETHICS:\n ethics = new Texture(pixmap);\n ethics.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n case INCOME:\n income = new Texture(pixmap);\n income.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n case CRIME:\n income = new Texture(pixmap);\n income.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n break;\n }\n pixmap.dispose();\n }\n\n private void drawBackboneLines() {\n ConstrainedMesh mesh = new ConstrainedMesh(); // everything will be on the x/y plane, so z will always be zero\n\n try {\n mesh.addConstraintEdge(new DEdge(-INITIAL_TRIANGLE_SIZE, -INITIAL_TRIANGLE_SIZE, 0, INITIAL_TRIANGLE_SIZE, -INITIAL_TRIANGLE_SIZE, 0));\n mesh.addConstraintEdge(new DEdge(-INITIAL_TRIANGLE_SIZE, -INITIAL_TRIANGLE_SIZE, 0, -INITIAL_TRIANGLE_SIZE, INITIAL_TRIANGLE_SIZE, 0));\n mesh.addConstraintEdge(new DEdge(INITIAL_TRIANGLE_SIZE, INITIAL_TRIANGLE_SIZE, 0, INITIAL_TRIANGLE_SIZE, -INITIAL_TRIANGLE_SIZE, 0));\n mesh.addConstraintEdge(new DEdge(INITIAL_TRIANGLE_SIZE, INITIAL_TRIANGLE_SIZE, 0, -INITIAL_TRIANGLE_SIZE, INITIAL_TRIANGLE_SIZE, 0));\n\n for (BackboneProviderNetwork backbone : game.getGamePlay().getInternet().getBackboneProviderNetworksMap().values()) { // iterate through backbones and add points to set and triangulation\n mesh.addPoint(new DPoint(backbone.getPos().x, backbone.getPos().y, 0));\n }\n\n mesh.processDelaunay();// run delaunay algorithm\n List<DEdge> edges = mesh.getEdges(); // hold edges\n for (DEdge e : edges) {\n if (!backboneLines.contains(e)) {\n backboneLines.add(new Line(e));\n }\n }\n\n } catch (DelaunayError delaunayError) {\n delaunayError.printStackTrace();\n }\n }\n\n @Override\n public void dispose() {\n super.dispose();\n }\n\n @Override\n public void hide() {\n Gdx.input.setInputProcessor(gameScreen.getInput());\n time = 0;\n }\n\n public GameScreen getGameScreen() {\n return gameScreen;\n }\n\n public Noise.NoiseType getCurrentBackground() {\n return currentBackground;\n }\n\n public void setCurrentBackground(Noise.NoiseType currentBackground) {\n this.currentBackground = currentBackground;\n }\n}", "public class InternetProviderNetwork extends Network {\n private final HashMap<String, Network> ipChildNetworkHashMap = new HashMap<String, Network>(255);\n\n public static final int MAX_DISTANCE = 1000;\n\n public InternetProviderNetwork(Internet internet) {\n this.internet = internet;\n }\n\n /**\n * For non-provider networks.\n */\n public void registerNewNetwork(Network network, int speed) {\n network.setParent(this);\n network.setIp(internet.assignIp(network));\n network.setSpeed(speed);\n ipChildNetworkHashMap.put(network.getIp(), network);\n\n // connection line between isp and backbone(this)\n HakdSprite mapIcon = getMapIcon();\n HakdSprite networkMapIcon = network.getMapIcon();\n Vector2 v1 = new Vector2(mapIcon.getX() + (mapIcon.getWidth() / 2), mapIcon.getY() + (mapIcon.getHeight() / 2));\n Vector2 v2 = new Vector2(networkMapIcon.getX() + (networkMapIcon.getWidth() / 2), networkMapIcon.getY() + (networkMapIcon.getHeight() / 2));\n network.setMapParentLine(new Line(v1, v2));\n }\n\n public void unregister() {\n\n }\n\n public enum IspName {\n /*\n * these are just some names I came up with, they are in no way\n * referencing real companies, infinity LTD. for now I will use the\n * greek alphabet until I think of company names\n */\n Alpha(), Beta(), Gamma(), Delta(), Epsilon(), Zeta(), Eta(), Theta(), Iota(), Kappa(), Lambda(), Mu(), Nu(),\n Xi(), Omnicron(), Pi(), Rho(), Sigma(), Tau(), Upsilon(), Phi(), Chi(), Psi(), Omega();\n\n\t\t/*\n * public int price; // I think I can use gooeyFiber(70, 99), maybe name\n\t\t * all fiber isp's after liquids public int level;\n\t\t */\n\n IspName(/* , int price in $, int level 0-00 */) {\n // this.price = price;\n // this.level = level;\n }\n }\n\n public HashMap<String, Network> getIpChildNetworkHashMap() {\n return ipChildNetworkHashMap;\n }\n}", "public class Network {\n String ip = \"\";\n int level; // 0-7, 0 for player because you start with almost nothing\n Character owner; // owner, company, player\n Stance stance; // TODO move this to npc class\n NetworkType type;\n City city;\n\n // provider connection info\n int speed; // in MB/s (megabytes per second)\n Network parent; // parent network\n\n // children device\n final Map<String, Device> devices = new HashMap<String, Device>();\n int deviceLimit; // The maximum allowable devices on the network, also the amount to generate is based on this value. This must be less than 255\n\n // gui stuff\n private HakdSprite mapIcon;\n Line mapParentLine;\n Vector2 pos; // holds the position of the center of the sprite\n\n public static final int backboneRegionSize = 2000; // diameter of the circle\n public static final int ispRegionSize = 200; // diameter of the circle\n public static final int networkRegionSize = 100;\n IpRegion ipRegion; // where the network is in the world, it helps find an ip\n\n Internet internet;\n\n public Network() {\n }\n\n /**\n * Removes a device from the network, as well as disposes it, removing any\n * connections.\n */\n public final void removeDevice(Device device) {\n devices.remove(device.getIp());\n device.dispose();\n\n if (owner instanceof Player) {\n device.getTile().setObject(null);\n ((Player) owner).getRoom().removeDevice(device);\n }\n }\n\n /**\n * Registers a device on the network.\n */\n public final boolean addDevice(Device device) {\n String ip = assignIp();\n\n if (devices.size() >= deviceLimit || ip == null) {\n return false;\n }\n\n devices.put(ip, device);\n\n device.setIp(ip);\n device.setNetwork(this);\n\n if (owner instanceof Player) {\n ((Player) owner).getRoom().addDevice(device);\n }\n return true;\n }\n\n /**\n * Assigns an ip to a device. Note: This will return null if there are 255\n */\n private String assignIp() {\n short[] deviceIp = null;\n short[] ip = Internet.ipFromString(this.ip);\n\n if (devices.size() > 255) {\n return null;\n }\n\n for (short i = 2; i < 256; i++) {\n deviceIp = new short[]{ip[0], ip[1], ip[2], i};\n if (getDevice(Internet.ipToString(deviceIp)) == null) {\n break;\n }\n }\n return Internet.ipToString(deviceIp);\n }\n\n /**\n * Finds the device with the given ip connected to the dns.\n */\n public final Device getDevice(String ip) {\n return devices.get(ip);\n }\n\n void placeNetwork(float regionSize) {\n float iconWidth = mapIcon.getWidth() / 2;\n float iconHeight = mapIcon.getHeight() / 2;\n Circle c = new Circle(city.getPosition().x, city.getPosition().y, 1);\n Vector2 v = new Vector2();\n\n l1:\n for (int i = (int) ((city.getDensity() + 1) / 2 * 2500); i < 5000; i += 250) {\n c.setRadius(i / 2);\n\n for (int k = 0; k < 50; k++) {\n float random = (float) (Math.random() * 2 - 1);\n v.x = (float) ((Math.random() * i) - i / 2) + iconWidth;\n v.y = (float) ((Math.random() * i) - i / 2) + iconHeight;\n v.add(city.getPosition());\n\n if (c.contains(v)) {\n double land = Noise.getLand().getValue(v.x, 0, v.y);\n double density = Noise.DENSITY.getValue(v.x, 0, v.y);\n if (land > 0 && density >= random) {\n break;\n }\n }\n\n if (k >= 50) {\n continue l1;\n }\n }\n pos = v;\n mapIcon.setPosition(v.x - iconWidth, v.y - iconHeight);\n\n if (v.dst2(city.getPosition()) <= City.height * City.height) {\n continue;\n }\n\n if (internet.getNetworkMap() == null || internet.getNetworkMap().isEmpty()) {\n break;\n }\n\n int j = 0;\n for (Network n : internet.getNetworkMap().values()) {\n j++;\n if (v.dst2(n.getMapIcon().getX(), n.getMapIcon().getY()) <= regionSize * regionSize && n != this) {\n continue l1;\n } else if (j >= internet.getNetworkMap().size()) {\n break l1;\n }\n }\n }\n }\n\n /**\n * These define how to generate a network.\n */\n public enum NetworkType {\n PLAYER(0, IpRegion.PRIVATE), BUSINESS(0, IpRegion.BUSINESS), TEST(0, IpRegion.none),\n ISP(0, IpRegion.BUSINESS), NPC(0, IpRegion.PRIVATE), BACKBONE(0, IpRegion.BUSINESS),\n EDUCATION(0, IpRegion.EDUCATION), BANK(0, IpRegion.BUSINESS), MILITARY(0, IpRegion.MILITARY),\n GOVERNMENT(0, IpRegion.GOVERNMENT), RESEARCH(0, IpRegion.GOVERNMENT);\n\n public final float noiseLevel;\n public final IpRegion ipRegion;\n\n NetworkType(float noiseLevel, IpRegion ipRegion) {\n this.noiseLevel = noiseLevel;\n this.ipRegion = ipRegion;\n }\n }\n\n public enum Stance {\n FRIENDLY, NEUTRAL, ENEMY // TODO do I want to give the network or the npc a stance?\n }\n\n public enum IpRegion {\n BUSINESS(1, 56), PRIVATE(57, 126), EDUCATION(173, 182), GOVERNMENT(214, 220), MILITARY(220, 255),\n none(1, 255);\n\n public final int min; // min backbone ip range\n public final int max; // max ip range\n\n IpRegion(int min, int max) {\n this.min = min;\n this.max = max;\n }\n }\n\n public int getLevel() {\n return level;\n }\n\n public void setLevel(int level) {\n this.level = level;\n }\n\n public game.gameplay.Character getOwner() {\n return owner;\n }\n\n public void setOwner(Character owner) {\n this.owner = owner;\n }\n\n public Stance getStance() {\n return stance;\n }\n\n public void setStance(Stance stance) {\n this.stance = stance;\n }\n\n public IpRegion getRegion() {\n return ipRegion;\n }\n\n public void setRegion(IpRegion ipRegion) {\n this.ipRegion = ipRegion;\n }\n\n public NetworkType getType() {\n return type;\n }\n\n public void setType(NetworkType type) {\n this.type = type;\n }\n\n public Internet getInternet() {\n return internet;\n }\n\n public void setInternet(Internet internet) {\n this.internet = internet;\n }\n\n public IpRegion getIpRegion() {\n return ipRegion;\n }\n\n public void setIpRegion(IpRegion ipRegion) {\n this.ipRegion = ipRegion;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(String ip) {\n this.ip = ip;\n }\n\n public int getSpeed() {\n return speed;\n }\n\n public void setSpeed(int speed) {\n this.speed = speed;\n }\n\n public Network getParent() {\n return parent;\n }\n\n public void setParent(Network parent) {\n this.parent = parent;\n }\n\n public Map<String, Device> getDevices() {\n return devices;\n }\n\n public int getDeviceLimit() {\n return deviceLimit;\n }\n\n public void setDeviceLimit(int deviceLimit) {\n this.deviceLimit = deviceLimit;\n }\n\n public HakdSprite getMapIcon() {\n return mapIcon;\n }\n\n public void setMapIcon(HakdSprite mapIcon) {\n this.mapIcon = mapIcon;\n mapIcon.setObject(this);\n }\n\n public Line getMapParentLine() {\n return mapParentLine;\n }\n\n public void setMapParentLine(Line mapParentLine) {\n this.mapParentLine = mapParentLine;\n }\n\n public Vector2 getPos() {\n return pos;\n }\n\n public void setPos(Vector2 pos) {\n this.pos = pos;\n }\n\n public City getCity() {\n return city;\n }\n\n public void setCity(City city) {\n this.city = city;\n }\n}" ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import game.gameplay.Character; import game.gameplay.City; import game.gameplay.Player; import gui.Room; import gui.screens.GameScreen; import gui.screens.MapScreen; import networks.InternetProviderNetwork; import networks.Network; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
package game; public class GamePlay { private static final float ROOM_UPDATE_SPEED = 1; private static final float CHARACTERMAP_UPDATE_SPEED = 3; private static final float CHARACTER_UPDATE_SPEED = 1; private final Internet internet; private Player player; private final GameScreen gameScreen; private final HashMap<String, Character> characterMap; private final HashMap<String, City> cityMap; private Thread updateThread; private boolean active; public GamePlay(GameScreen screen, String name) { this.gameScreen = screen; cityMap = new HashMap<String, City>(); characterMap = new HashMap<String, Character>(); makeCities(1f, 4000); makeCities(.4f, 6000); makeCities(.2f, 8000); internet = new Internet(cityMap); makeCompanies(); makeAgencies(); makeHackers(); makePlayer(name); startUpdateThread(); } private void makeCompanies() { } private void makeAgencies() { } private void makeHackers() { } private void makePlayer(String name) { List<City> citiesSuffled = new ArrayList<City>(cityMap.values()); Collections.shuffle(citiesSuffled); City playerCity = null; for (City c : citiesSuffled) { playerCity = c; for (Network n : playerCity.getNetworks().values()) {
if (n instanceof InternetProviderNetwork) {
6
vangj/jbayes
src/test/java/com/github/vangj/jbayes/inf/exact/graph/pptc/blocks/InferenceControlTest.java
[ "public static JoinTree apply(Dag dag) {\n JoinTree joinTree = propagate(initialization(transform(triangulate(moralize(dag)))))\n .setListener(new InferenceControl());\n return joinTree;\n}", "public class Potential {\n\n private final List<PotentialEntry> entries;\n\n public Potential() {\n entries = new ArrayList<>();\n }\n\n /**\n * Finds matching potential entries to the specified one passed in.\n *\n * @param potentialEntry Potential entry.\n * @return List of ootential entries.\n */\n public List<PotentialEntry> match(PotentialEntry potentialEntry) {\n List<PotentialEntry> entries = new ArrayList<>();\n for (PotentialEntry entry : this.entries) {\n if (entry.match(potentialEntry)) {\n entries.add(entry);\n }\n }\n return entries;\n }\n\n public List<PotentialEntry> entries() {\n return entries;\n }\n\n public Potential addEntry(PotentialEntry entry) {\n entries.add(entry);\n return this;\n }\n\n @Override\n public String toString() {\n return entries.stream()\n .map(PotentialEntry::toString)\n .collect(Collectors.joining(System.lineSeparator()));\n }\n}", "public class Evidence {\n\n private final Node node;\n private final Map<String, Double> values;\n private final Type type;\n\n private Evidence(Builder builder) {\n node = builder.node;\n values = builder.values;\n type = builder.type;\n }\n\n /**\n * Converts a map of values to potentials to a map of values to likelihoods.\n *\n * @param map Map.\n * @return Map.\n */\n private static Map<String, Double> convert(Map<String, Potential> map) {\n Map<String, Double> m = new LinkedHashMap<>();\n for (Map.Entry<String, Potential> e : map.entrySet()) {\n m.put(e.getKey(), e.getValue().entries().get(0).getValue());\n }\n return m;\n }\n\n /**\n * Checks to see if the evidence is unobserved. All likelihoods must be 1.\n *\n * @param values Map of values to likelihoods.\n * @return Boolean.\n */\n private static boolean isUnobserved(Map<String, Double> values) {\n int counts = (int) values.entrySet().stream()\n .filter(entry -> (entry.getValue() == 1.0d))\n .count();\n return (counts == values.size());\n }\n\n /**\n * Checks to see if the evidence is observed. Exactly one value must be 1 and all others are 0.\n *\n * @param values Map of values to likelihoods.\n * @return Boolean.\n */\n private static boolean isObserved(Map<String, Double> values) {\n long countOne = values.entrySet().stream()\n .filter(entry -> (entry.getValue() == 1.0d))\n .count();\n long countZero = values.entrySet().stream()\n .filter(entry -> (entry.getValue() == 0.0d))\n .count();\n return (1 == countOne && values.size() - 1 == countZero);\n }\n\n /**\n * Gets the observed value. Should be called only after isObserved returns true.\n *\n * @param values Map of values to likelihoods.\n * @return The value which is observed.\n */\n private static String getObservedValue(Map<String, Double> values) {\n return values.entrySet().stream()\n .filter(entry -> (entry.getValue() == 1.0d))\n .map(Map.Entry::getKey)\n .findFirst().get();\n }\n\n /**\n * Gest a new builder.\n *\n * @return Builder.\n */\n public static Builder newBuilder() {\n return new Builder();\n }\n\n /**\n * Gets the node.\n *\n * @return Node.\n */\n public Node getNode() {\n return node;\n }\n\n /**\n * Gets a map where keys are node's values and the values are likelihoods.\n *\n * @return Map.\n */\n public Map<String, Double> getValues() {\n return values;\n }\n\n /**\n * Gets the type of evidence.\n *\n * @return Type.\n */\n public Type getType() {\n return type;\n }\n\n /**\n * Compares this evidence to the current one and determines the change type.\n *\n * @param potentials Map of potentials.\n * @return Change type.\n */\n public Change compare(Map<String, Potential> potentials) {\n Map<String, Double> that = convert(potentials);\n\n boolean unobservedThat = isUnobserved(that);\n boolean unobservedThis = isUnobserved(values);\n\n if (unobservedThat && unobservedThis) {\n return Change.None;\n }\n\n boolean observedThat = isObserved(that);\n boolean observedThis = isObserved(values);\n\n if (observedThat && observedThis) {\n String s1 = getObservedValue(that);\n String s2 = getObservedValue(values);\n if (s1.equals(s2)) {\n return Change.None;\n } else {\n return Change.Retraction;\n }\n }\n\n if (unobservedThat && observedThis) {\n //FIXME should signal update, but that doesn't work\n return Change.Retraction;\n }\n\n if (observedThat && unobservedThis) {\n return Change.Retraction;\n }\n\n return Change.Retraction;\n }\n\n /**\n * The type of evidence.\n * <ul>\n * <li>virtual: each value lies in the domain [0, 1]</li>\n * <li>finding: each value must be 1 or 0; at least one value must be 1</li>\n * <li>observation: one value is 1 and all others are 0</li>\n * <li>unobserve: all values are 1</li>\n * </ul>\n */\n public enum Type {\n Virtual, Finding, Observation, Unobserve\n }\n\n /**\n * The type of change that the evidence can bring about.\n * <ul>\n * <li>none: nothing changed</li>\n * <li>update: node was unobseved, now it is observed</li>\n * <li>retraction: node was unobserved and now observed, or previous observed value is now\n * not the same as the observed one</li>\n * </ul>\n */\n public enum Change {\n None, Update, Retraction\n }\n\n /**\n * Builder for evidence.\n */\n public static final class Builder {\n\n private final Map<String, Double> values;\n private Node node;\n private Type type = Type.Observation;\n\n private Builder() {\n values = new LinkedHashMap<>();\n }\n\n public Builder node(Node node) {\n this.node = node;\n return this;\n }\n\n public Builder value(String value, Double likelihood) {\n values.put(value, likelihood);\n return this;\n }\n\n public Builder type(Type val) {\n type = val;\n return this;\n }\n\n public Evidence build() {\n if (null == node || null == node.getId() || node.getId().isEmpty()) {\n throw new IllegalArgumentException(\"node/id cannot be null or empty!\");\n }\n validateEvidence();\n return new Evidence(this);\n }\n\n private void validateEvidence() {\n node.getValues().forEach(value -> {\n if (!values.containsKey(value)) {\n values.put(value, 0.0d);\n }\n });\n\n if (Type.Virtual == type) {\n //each likelihood must be in [0, 1]\n double sum = 0.0d;\n for (Double value : values.values()) {\n sum += value;\n }\n for (String k : values.keySet()) {\n double d = values.get(k) / sum;\n values.put(k, d);\n }\n } else if (Type.Finding == type) {\n //each likelihood must be either 0 or 1; there should be at least a value with 1\n for (String k : values.keySet()) {\n double d = values.get(k) > 0.0d ? 1.0d : 0.0d;\n values.put(k, d);\n }\n\n long count = values.entrySet().stream()\n .filter(entry -> entry.getValue() == 1.0d)\n .count();\n\n //if no value has 1, then make them all 1\n if (0 == count) {\n for (String k : values.keySet()) {\n values.put(k, 1.0d);\n }\n }\n } else if (Type.Observation == type) {\n //only 1 likelihood is 1 and others are 0\n String key = values.entrySet().stream()\n .sorted((o1, o2) -> -1 * o1.getValue().compareTo(o2.getValue()))\n .map(Map.Entry::getKey)\n .findFirst().get();\n values.keySet().forEach(k -> {\n if (key.equals(k)) {\n values.put(k, 1.0d);\n } else {\n values.put(k, 0.0d);\n }\n });\n } else if (Type.Unobserve == type) {\n values.keySet().forEach(k -> {\n values.put(k, 1.0d);\n });\n }\n }\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 com.github.vangj.jbayes.inf.exact.graph.pptc.blocks.InferenceControl.apply; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.pptc.Evidence; import com.github.vangj.jbayes.inf.exact.graph.pptc.HuangExample; import com.github.vangj.jbayes.inf.exact.graph.pptc.JoinTree; import java.util.Arrays; import org.junit.Test;
package com.github.vangj.jbayes.inf.exact.graph.pptc.blocks; public class InferenceControlTest extends HuangExample { @Test public void testInference() { JoinTree joinTree = apply(getDag()); joinTree.nodes().forEach(node -> { Potential potential = joinTree.getPotential(node); System.out.println(node); System.out.println(potential); System.out.println("---------------"); });
joinTree.updateEvidence(Evidence.newBuilder()
2
daniel-sc/rocketchat-modern-client
src/test/java/com/github/daniel_sc/rocketchat/modern_client/RocketChatClientIT.java
[ "public class Attachment {\n\t\n\t/**\n\t * The color you want the order on the left side to be, any value background-css supports.\n\t */\n\tpublic String color;\n\t\n\t/**\n\t * The text to display for this attachment, it is different than the message’s text.\n\t */\n\tpublic String text;\n\t\n\t/**\n\t * Displays the time next to the text portion.\n\t * 2016-12-09T16:53:06.761Z\n\t */\n\t@SerializedName(\"ts\")\n\tpublic String iso8601Date = Instant.now().toString();\n\n\t/**\n\t * An image that displays to the left of the text, looks better when this is relatively small.\n\t */\n\tpublic String thumbUrl;\n\t\n\t/**\n\t * Causes the image, audio, and video sections to be hiding when collapsed is true.\n\t */\n\tpublic boolean collapsed = false;\n\t\n\t/**\n\t * Name of the author.\n\t */\n\t@SerializedName(\"author_name\")\n\tpublic String authorName;\n\t\n\t/**\n\t * Providing this makes the author name clickable and points to this link.\n\t */\n\t@SerializedName(\"author_link\")\n\tpublic String authorLink;\n\t\n\t/**\n\t * Displays a tiny icon to the left of the Author’s name.\n\t */\n\t@SerializedName(\"author_icon\")\n\tpublic String authorIcon;\n\t\n\t/**\n\t * Title to display for this attachment, displays under the author.\n\t */\n\tpublic String title;\n\t\n\t/**\n\t * Providing this makes the title clickable, pointing to this link.\n\t */\n\t@SerializedName(\"title_link\")\n\tpublic String titleLink;\n\t\n\t/**\n\t * When this is true, a download icon appears and clicking this saves the link to file.\n\t */\n\t@SerializedName(\"title_link_download\")\n\tpublic boolean titleLinkDownload = true;\n\t\n\t/**\n\t * The image to display, will be \"big\" and easy to see.\n\t */\n\t@SerializedName(\"image_url\")\n\tpublic String imageUrl;\n\t\n\t/**\n\t * Audio file to play, only supports what html audio does.\n\t */\n\t@SerializedName(\"audio_url\")\n\tpublic String audioUrl;\n\t\n\t/**\n\t * Video file to play, only supports what html video does.\n\t */\n\t@SerializedName(\"video_url\")\n\tpublic String videoUrl;\n\t\n\t/**\n\t * An array of Attachment Field Objects.\n\t */\n\tpublic List<AttachmentField> fields;\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Attachment [color=\" + color + \", text=\" + text + \", iso8601Date=\" + iso8601Date + \", thumbUrl=\"\n\t\t\t\t+ thumbUrl + \", collapsed=\" + collapsed + \", authorName=\" + authorName + \", authorLink=\" + authorLink\n\t\t\t\t+ \", authorIcon=\" + authorIcon + \", title=\" + title + \", titleLink=\" + titleLink\n\t\t\t\t+ \", titleLinkDownload=\" + titleLinkDownload + \", imageUrl=\" + imageUrl + \", audioUrl=\" + audioUrl\n\t\t\t\t+ \", videoUrl=\" + videoUrl + \", fields=\" + fields + \"]\";\n\t}\n\t\n}", "public class AttachmentField {\n\t\n\t/**\n\t * Whether this field should be a short field.\t * \n\t */\n\t@SerializedName(\"short\")\n\tpublic final boolean _short;\n\t\n\t/**\n\t * [REQUIRED] The title of this field.\n\t */\n\tpublic final String title;\n\t\n\t/**\n\t * [REQUIRED] The value of this field, displayed underneath the title value.\n\t */\n\tpublic final String value;\n\n\tpublic AttachmentField(String title, String value) {\n\t\tthis(false, title, value);\n\t}\n\t\n\tpublic AttachmentField(boolean _short, String title, String value) {\n\t\tthis._short = _short;\n\t\tthis.title = title;\n\t\tthis.value = value;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AttachmentField [_short=\" + _short + \", title=\" + title + \", value=\" + value + \"]\";\n\t}\t\t\n\n\t\n}", "public class LoginParam {\n public final Map<String, String> user = new HashMap<>();\n public final Map<String, String> password = new HashMap<>();\n\n public LoginParam(String user, String password) {\n this.user.put(\"username\", user);\n this.password.put(\"digest\", getDigest(password));\n this.password.put(\"algorithm\", \"sha-256\");\n }\n\n public static String getDigest(String password) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));\n StringBuilder hexString = new StringBuilder();\n\n for (byte b : hash) {\n String hex = Integer.toHexString(0xff & b);\n if (hex.length() == 1) hexString.append('0');\n hexString.append(hex);\n }\n\n return hexString.toString();\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n}", "public class ChatMessage {\n public String msg;\n public User u;\n public String rid;\n public String _id;\n public DateWrapper editedAt;\n @SerializedName(\"_updatedAt\")\n public DateWrapper updatedAt;\n public DateWrapper ts;\n public User editedBy;\n public Map<String,UserList> reactions;\n\n public ChatMessage(String msg, User u, String rid, DateWrapper editedAt, User editedBy, Map<String,UserList> reactions) {\n this.msg = msg;\n this.u = u;\n this.rid = rid;\n this.editedAt = editedAt;\n this.editedBy = editedBy;\n this.reactions = reactions;\n }\n\n public boolean isModified() {\n return editedAt != null && editedBy != null;\n }\n\n @Override\n public String toString() {\n return \"ChatMessage{\" +\n \"msg='\" + msg + '\\'' +\n \", u=\" + u + '\\'' +\n \", rid=\" + rid + '\\'' +\n \", _id=\" + _id +\n '}';\n }\n}", "public class Permission {\n @SerializedName(\"_id\")\n public String id;\n public List<String> roles;\n @SerializedName(\"_updatedAt\")\n public DateWrapper updatedAt;\n @SerializedName(\"$loki\")\n public Integer loki;\n public MetaData meta;\n\n @Override\n public String toString() {\n return \"Permission{\" +\n \"id='\" + id + '\\'' +\n \", roles=\" + roles +\n \", updatedAt=\" + updatedAt +\n \", loki=\" + loki +\n \", meta=\" + meta +\n '}';\n }\n}", "public class Room {\n @SerializedName(\"_id\")\n public String id;\n public String name;\n public String topic;\n @SerializedName(\"ro\")\n public Boolean readOnly;\n public DateWrapper jitsiTimeout;\n @SerializedName(\"t\")\n public Room.RoomType type;\n @SerializedName(\"u\")\n public User creator;\n\n public enum RoomType {\n /**\n * direct chat\n */\n @SerializedName(\"d\")\n DIRECT_CHAT,\n /**\n * private chat\n */\n @SerializedName(\"p\")\n PRIVATE_CHAT,\n /**\n * chat\n */\n @SerializedName(\"c\")\n CHAT,\n /**\n * live chat\n */\n @SerializedName(\"l\")\n LIVE_CHAT\n }\n\n @Override\n public String toString() {\n return \"Room{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", topic='\" + topic + '\\'' +\n \", readOnly=\" + readOnly +\n \", jitsiTimeout=\" + jitsiTimeout +\n \", type=\" + type +\n \", creator=\" + creator +\n '}';\n }\n}", "public class Subscription {\n public String name;\n /** roomId */\n public String rid;\n public String _id;\n\n @Override\n public String toString() {\n return \"Subscription{\" +\n \"name='\" + name + '\\'' +\n \", rid='\" + rid + '\\'' +\n \", _id='\" + _id + '\\'' +\n '}';\n }\n}", "public class InitialData {\n public Boolean enabled; // true\n public String title; // 'Rocket.Chat'\n public String color; // '#C1272D'\n public Boolean registrationForm; // true\n public User visitor; // undefined\n public List<Trigger> triggers; // []\n public List<Department> departments; // []\n public Boolean allowSwitchingDepartments; // true\n public Boolean online; // true\n public String offlineColor; // '#666666'\n public String offlineMessage; // 'We are not online right now. Please leave us a message:'\n public String offlineSuccessMessage; // ''\n public String offlineUnavailableMessage; // ''\n public Boolean displayOfflineForm; // true\n public Boolean videoCall; // false\n public String offlineTitle; // 'Leave a message'\n public String language; // 'en'\n public Boolean transcript; // false\n public String transcriptMessage; // 'Would you like a copy of this chat emailed?'\n public String conversationFinishedMessage; // 'Conversation finished'\n public Boolean nameFieldRegistrationForm; // true\n public Boolean emailFieldRegistrationForm; // true\n\n @Override\n public String toString() {\n return \"InitialData{\" +\n \"enabled=\" + enabled +\n \", title='\" + title + '\\'' +\n \", color='\" + color + '\\'' +\n \", registrationForm=\" + registrationForm +\n \", visitor=\" + visitor +\n \", triggers=\" + triggers +\n \", departments=\" + departments +\n \", allowSwitchingDepartments=\" + allowSwitchingDepartments +\n \", online=\" + online +\n \", offlineColor='\" + offlineColor + '\\'' +\n \", offlineMessage='\" + offlineMessage + '\\'' +\n \", offlineSuccessMessage='\" + offlineSuccessMessage + '\\'' +\n \", offlineUnavailableMessage='\" + offlineUnavailableMessage + '\\'' +\n \", displayOfflineForm=\" + displayOfflineForm +\n \", videoCall=\" + videoCall +\n \", offlineTitle='\" + offlineTitle + '\\'' +\n \", language='\" + language + '\\'' +\n \", transcript=\" + transcript +\n \", transcriptMessage='\" + transcriptMessage + '\\'' +\n \", conversationFinishedMessage='\" + conversationFinishedMessage + '\\'' +\n \", nameFieldRegistrationForm=\" + nameFieldRegistrationForm +\n \", emailFieldRegistrationForm=\" + emailFieldRegistrationForm +\n '}';\n }\n}", "public class RegisterGuest {\n public String userId;\n public Visitor visitor;\n\n @Override\n public String toString() {\n return \"RegisterGuest{\" +\n \"userId='\" + userId + '\\'' +\n \", visitor=\" + visitor +\n '}';\n }\n}" ]
import com.github.daniel_sc.rocketchat.modern_client.request.Attachment; import com.github.daniel_sc.rocketchat.modern_client.request.AttachmentField; import com.github.daniel_sc.rocketchat.modern_client.request.LoginParam; import com.github.daniel_sc.rocketchat.modern_client.response.ChatMessage; import com.github.daniel_sc.rocketchat.modern_client.response.Permission; import com.github.daniel_sc.rocketchat.modern_client.response.Room; import com.github.daniel_sc.rocketchat.modern_client.response.Subscription; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.InitialData; import com.github.daniel_sc.rocketchat.modern_client.response.livechat.RegisterGuest; import io.reactivex.disposables.Disposable; import io.reactivex.internal.operators.observable.ObservableReplay; import io.reactivex.observables.ConnectableObservable; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import java.util.logging.Logger; import static org.junit.Assert.*;
package com.github.daniel_sc.rocketchat.modern_client; public class RocketChatClientIT { private static final Logger LOG = Logger.getLogger(RocketChatClientIT.class.getName()); private static final String PASSWORD = "testuserrocks"; private static final String USER = "testuserrocks-0"; private static final String URL = "wss://open.rocket.chat:443/websocket"; //private static final String URL = "ws://localhost:3000/websocket"; private static final int DEFAULT_TIMEOUT = 20000; public static final String DEFAULT_ROOM = "privatetestgroup-0"; private RocketChatClient client; @Before public void setUp() { LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1)); // prevent rate limit.. client = new RocketChatClient(URL, new LoginParam(USER, PASSWORD), Executors.newFixedThreadPool(2)); } @After public void tearDown() { // in reality one should use try-with-resource client.close(); } @Test(timeout = DEFAULT_TIMEOUT) public void testGetSubscriptions() { LOG.info("start testGetSubscriptions..");
List<Subscription> subscriptions = client.getSubscriptions().join();
6
cjdaly/fold
net.locosoft.fold.channel.times/src/net/locosoft/fold/channel/times/internal/RefTimesNode.java
[ "public interface IChannel {\n\n\tString getChannelId();\n\n\tString getChannelData(String key, String... params);\n\n\tIChannelItemDetails getChannelItemDetails(String itemLabel, long itemOrdinal);\n\n\tClass<? extends IChannel> getChannelInterface();\n\n}", "public interface IChannelService {\n\n\tIChannel[] getAllChannels();\n\n\tIChannel getChannel(String channelId);\n\n\t<T extends IChannel> T getChannel(Class<T> channelInterface);\n\n\tString getChannelData(String channelId, String key, String... params);\n\n\tIChannelItemDetails getChannelItemDetails(String channelId,\n\t\t\tString channelItemLabel, long channelItemOrdinal);\n\n\tboolean channelSecurity(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException;\n\n\tvoid channelHttp(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException;\n\n}", "public interface ICypher {\n\n\tboolean allowParallelInvocation();\n\n\tvoid allowParallelInvocation(boolean parallelInvocation);\n\n\tString getStatementText();\n\n\tvoid setStatementText(String statementText);\n\n\tJsonObject getRequest();\n\n\tvoid addStatement(String statementText);\n\n\tvoid addParameter(String name, JsonValue value);\n\n\tvoid addParameter(String name, int value);\n\n\tvoid addParameter(String name, long value);\n\n\tvoid addParameter(String name, float value);\n\n\tvoid addParameter(String name, double value);\n\n\tvoid addParameter(String name, boolean value);\n\n\tvoid addParameter(String name, String value);\n\n\tJsonObject getResponse();\n\n\tJsonArray getResultData();\n\n\tJsonArray getResultData(int resultSet);\n\n\tint getResultDataRowCount();\n\n\tint getResultDataRowCount(int resultSet);\n\n\tJsonValue getResultDataRow(int index);\n\n\tJsonValue getResultDataRow(int resultSet, int index);\n\n\tJsonArray getErrors();\n\n\tint getErrorCount();\n}", "public interface INeo4jService {\n\n\tboolean isNeo4jReady();\n\n\tint getNeo4jPID();\n\n\tICypher constructCypher();\n\n\tICypher constructCypher(String statement);\n\n\tvoid invokeCypher(ICypher cypher);\n\n\tvoid invokeCypher(ICypher cypher, boolean logErrors);\n\n}", "public abstract class AbstractNodeSketch implements INodeSketch {\n\n\tprotected long _nodeId = -1;\n\n\tpublic long getNodeId() {\n\t\treturn _nodeId;\n\t}\n\n\tprivate INeo4jService _neo4jService;\n\n\tpublic INeo4jService getNeo4jService() {\n\t\tif (_neo4jService == null) {\n\t\t\t_neo4jService = Neo4jUtil.getNeo4jService();\n\t\t}\n\t\treturn _neo4jService;\n\t}\n\n}", "public interface IChannelItemDetails extends ISketch {\n\n\tString getItemLabel();\n\n\tString getItemKind();\n\n\tlong getTimestamp();\n\n\tlong getOrdinal();\n\n\tJsonObject getJson();\n\n\tString getUrlPath();\n\n\tString[] getDataLines();\n}", "public class OrdinalNode extends AbstractNodeSketch {\n\n\tpublic static String PREFIX_ORDINAL_COUNTER = \"fold_OrdinalCounter_\";\n\tpublic static String PREFIX_ORDINAL_INDEX = \"fold_OrdinalIndex_\";\n\n\tprivate String _ordinalLabel;\n\tprivate CounterPropertyNode _ordinalCounter;\n\n\tpublic OrdinalNode(long nodeId, String ordinalLabel) {\n\t\t_nodeId = nodeId;\n\t\t_ordinalLabel = ordinalLabel;\n\t\t_ordinalCounter = new CounterPropertyNode(nodeId);\n\t}\n\n\tprotected String getOrdinalLabel() {\n\t\treturn _ordinalLabel;\n\t}\n\n\tprotected String getCounterPropertyName() {\n\t\treturn PREFIX_ORDINAL_COUNTER + getOrdinalLabel();\n\t}\n\n\tprotected String getIndexPropertyName() {\n\t\treturn PREFIX_ORDINAL_INDEX + getOrdinalLabel();\n\t}\n\n\tpublic long getLatestOrdinal() {\n\t\treturn _ordinalCounter.getCounter(getCounterPropertyName());\n\t}\n\n\tpublic long getOrdinalIndex(long ordinalNodeId) {\n\t\tPropertyAccessNode props = new PropertyAccessNode(ordinalNodeId);\n\t\treturn props.getLongValue(getIndexPropertyName());\n\t}\n\n\tpublic long getOrdinalIndex(JsonObject jsonNode) {\n\t\treturn jsonNode.getLong(getIndexPropertyName(), -1);\n\t}\n\n\tpublic long nextOrdinalNodeId() {\n\t\tlong ordinalIndex = _ordinalCounter\n\t\t\t\t.incrementCounter(getCounterPropertyName());\n\t\tINeo4jService neo4jService = getNeo4jService();\n\n\t\tif (ordinalIndex == 1) {\n\t\t\tString constraintCypherText = \"CREATE CONSTRAINT ON (ordinal:\"\n\t\t\t\t\t+ getOrdinalLabel() + \") ASSERT ordinal.`\"\n\t\t\t\t\t+ getIndexPropertyName() + \"` IS UNIQUE\";\n\t\t\tICypher constraintCypher = neo4jService\n\t\t\t\t\t.constructCypher(constraintCypherText);\n\t\t\tneo4jService.invokeCypher(constraintCypher);\n\t\t}\n\n\t\tString cypherText = \"CREATE (ordinal:\" + getOrdinalLabel() + \" { `\"\n\t\t\t\t+ getIndexPropertyName() + \"`: {ordinalIndex} })\"\n\t\t\t\t+ \" RETURN ID(ordinal)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"ordinalIndex\", ordinalIndex);\n\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\treturn jsonValue.asLong();\n\t}\n\n\tpublic long getOrdinalNodeId(long ordinalIndex) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\n\t\tString cypherText = \"MATCH (ordinal:\" + getOrdinalLabel() + \" { `\"\n\t\t\t\t+ getIndexPropertyName() + \"`: {ordinalIndex} })\"\n\t\t\t\t+ \" RETURN ID(ordinal)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"ordinalIndex\", ordinalIndex);\n\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue == null)\n\t\t\treturn -1;\n\t\telse\n\t\t\treturn jsonValue.asLong();\n\t}\n\n\tpublic JsonObject getOrdinalNode(long ordinalIndex) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\n\t\tString cypherText = \"MATCH (ordinal:\" + getOrdinalLabel() + \" { `\"\n\t\t\t\t+ getIndexPropertyName() + \"`: {ordinalIndex} })\"\n\t\t\t\t+ \" RETURN ordinal\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"ordinalIndex\", ordinalIndex);\n\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif ((jsonValue == null) || (!jsonValue.isObject()))\n\t\t\treturn null;\n\t\telse\n\t\t\treturn jsonValue.asObject();\n\t}\n\n}" ]
import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.locosoft.fold.channel.IChannel; import net.locosoft.fold.channel.IChannelService; import net.locosoft.fold.neo4j.ICypher; import net.locosoft.fold.neo4j.INeo4jService; import net.locosoft.fold.sketch.AbstractNodeSketch; import net.locosoft.fold.sketch.IChannelItemDetails; import net.locosoft.fold.sketch.pad.neo4j.OrdinalNode; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue;
StringBuilder cypherText = new StringBuilder(); cypherText.append("MATCH (refNode"); if ((refNodeLabel != null) && !"".equals(refNodeLabel)) { cypherText.append(":"); cypherText.append(refNodeLabel); } cypherText.append(")-[:times_Ref]->(timesNode) "); cypherText.append("WHERE ID(timesNode)={timesNodeId} "); if ((refNodeKey != null) && (refNodeValue != null)) { cypherText.append(" AND refNode.`" + refNodeKey + "`={refNodeValue} "); } cypherText.append("RETURN ID(refNode)"); ICypher cypher = neo4jService.constructCypher(cypherText.toString()); cypher.addParameter("timesNodeId", getNodeId()); if ((refNodeKey != null) && (refNodeValue != null)) { cypher.addParameter("refNodeValue", refNodeValue); } neo4jService.invokeCypher(cypher); long[] refIds = new long[cypher.getResultDataRowCount()]; for (int i = 0; i < cypher.getResultDataRowCount(); i++) { JsonValue jsonValue = cypher.getResultDataRow(i); refIds[i] = jsonValue.asLong(); } return refIds; } public JsonObject[] getTimesRefNodes(String refNodeLabel, String refNodeKey, String refNodeValue) { INeo4jService neo4jService = getNeo4jService(); StringBuilder cypherText = new StringBuilder(); cypherText.append("MATCH (refNode"); if ((refNodeLabel != null) && !"".equals(refNodeLabel)) { cypherText.append(":"); cypherText.append(refNodeLabel); } cypherText.append(")-[:times_Ref]->(timesNode) "); cypherText.append("WHERE ID(timesNode)={timesNodeId} "); if ((refNodeKey != null) && (refNodeValue != null)) { cypherText.append(" AND refNode.`" + refNodeKey + "`={refNodeValue} "); } cypherText.append("RETURN refNode"); ICypher cypher = neo4jService.constructCypher(cypherText.toString()); cypher.addParameter("timesNodeId", getNodeId()); if ((refNodeKey != null) && (refNodeValue != null)) { cypher.addParameter("refNodeValue", refNodeValue); } neo4jService.invokeCypher(cypher); JsonObject[] refNodes = new JsonObject[cypher.getResultDataRowCount()]; for (int i = 0; i < cypher.getResultDataRowCount(); i++) { JsonValue jsonValue = cypher.getResultDataRow(i); refNodes[i] = jsonValue.asObject(); } return refNodes; } public JsonObject[] getTimesRefNodes() { INeo4jService neo4jService = getNeo4jService(); StringBuilder cypherText = new StringBuilder(); cypherText.append("MATCH (refNodes)-[:times_Ref]->(timesNode) "); cypherText.append("WHERE ID(timesNode)={timesNodeId} "); cypherText.append("RETURN refNodes"); ICypher cypher = neo4jService.constructCypher(cypherText.toString()); cypher.addParameter("timesNodeId", getNodeId()); neo4jService.invokeCypher(cypher); JsonObject[] jsonNodes = new JsonObject[cypher.getResultDataRowCount()]; for (int i = 0; i < cypher.getResultDataRowCount(); i++) { JsonValue jsonValue = cypher.getResultDataRow(i); jsonNodes[i] = jsonValue.asObject(); } return jsonNodes; } public TreeMap<String, TreeMap<Long, IChannelItemDetails>> populateMinuteMap( IChannelService channelService) { TreeMap<String, TreeMap<Long, IChannelItemDetails>> refNodeMap = new TreeMap<String, TreeMap<Long, IChannelItemDetails>>(); RefTimesNode refNodes = new RefTimesNode(getNodeId()); JsonObject[] jsonNodes = refNodes.getTimesRefNodes(); populateRefNodeMap(channelService, refNodeMap, jsonNodes); return refNodeMap; } private void populateRefNodeMap(IChannelService channelService, TreeMap<String, TreeMap<Long, IChannelItemDetails>> refNodeMap, JsonObject[] jsonNodes) { for (JsonObject jsonNode : jsonNodes) { for (String name : jsonNode.names()) { if (name.startsWith(OrdinalNode.PREFIX_ORDINAL_INDEX)) { addRefNodeMapEntry(channelService, refNodeMap, jsonNode, name); } } } } private Pattern _channelIdPattern = Pattern .compile(OrdinalNode.PREFIX_ORDINAL_INDEX + "([^_]+)_([^_]+)"); private void addRefNodeMapEntry(IChannelService channelService, TreeMap<String, TreeMap<Long, IChannelItemDetails>> refNodeMap, JsonObject jsonNode, String ordinalIndexKeyName) { Matcher matcher = _channelIdPattern.matcher(ordinalIndexKeyName); if (!matcher.find()) return; long channelItemOrdinal = jsonNode.getLong(ordinalIndexKeyName, -1); if (channelItemOrdinal == -1) return; String channelId = matcher.group(1); String channelItemLabel = matcher.group(2);
IChannel channel = channelService.getChannel(channelId);
0
openshopio/openshop.io-android
app/src/main/java/bf/io/openshop/api/GsonRequest.java
[ "public class CONST {\n\n // TODO update this variable\n /**\n * Specific organization ID, received by successful integration.\n */\n public static final int ORGANIZATION_ID = 4;\n /**\n * ID used for simulate empty/null value\n */\n public static final int DEFAULT_EMPTY_ID = -131;\n\n // Volley requests tags\n public static final String SPLASH_REQUESTS_TAG = \"splash_requests\";\n public static final String DRAWER_REQUESTS_TAG = \"drawer_requests\";\n public static final String BANNER_REQUESTS_TAG = \"banner_requests\";\n public static final String CATEGORY_REQUESTS_TAG = \"category_requests\";\n public static final String PRODUCT_REQUESTS_TAG = \"product_requests\";\n public static final String LOGIN_DIALOG_REQUESTS_TAG = \"login_dialog_requests\";\n public static final String ACCOUNT_REQUESTS_TAG = \"account_requests\";\n public static final String CART_REQUESTS_TAG = \"cart_requests\";\n public static final String CART_DISCOUNTS_REQUESTS_TAG = \"cart_discounts_requests\";\n public static final String ORDER_CREATE_REQUESTS_TAG = \"order_create_requests\";\n public static final String DELIVERY_DIALOG_REQUESTS_TAG = \"delivery_dialog_requests\";\n public static final String WISHLIST_REQUESTS_TAG = \"wishlist_requests\";\n public static final String ACCOUNT_EDIT_REQUESTS_TAG = \"account_edit_requests\";\n public static final String SETTINGS_REQUESTS_TAG = \"settings_requests\";\n public static final String UPDATE_CART_ITEM_REQUESTS_TAG = \"update_cart_item_requests\";\n public static final String MAIN_ACTIVITY_REQUESTS_TAG = \"main_activity_requests\";\n public static final String PAGE_REQUESTS_TAG = \"page_requests\";\n public static final String ORDERS_HISTORY_REQUESTS_TAG = \"orders_history_requests\";\n public static final String ORDERS_DETAIL_REQUESTS_TAG = \"orders_detail_requests\";\n\n // Bundle constants\n public static final String BUNDLE_PASS_TARGET = \"target\";\n public static final String BUNDLE_PASS_TITLE = \"title\";\n /**\n * Volley request unknown status code\n */\n public static final int MissingStatusCode = 9999;\n\n /**\n * Possible visibility states of layout parts.\n */\n public enum VISIBLE {\n EMPTY, CONTENT, PROGRESS\n }\n}", "public class MyApplication extends Application {\n public static final String PACKAGE_NAME = MyApplication.class.getPackage().getName();\n\n private static final String TAG = MyApplication.class.getSimpleName();\n\n\n public static String APP_VERSION = \"0.0.0\";\n public static String ANDROID_ID = \"0000000000000000\";\n\n private static MyApplication mInstance;\n\n private RequestQueue mRequestQueue;\n\n\n public static synchronized MyApplication getInstance() {\n return mInstance;\n }\n\n\n /**\n * Method sets app specific language localization by selected shop.\n * Have to be called from every activity.\n *\n * @param lang language code.\n */\n public static void setAppLocale(String lang) {\n Resources res = mInstance.getResources();\n DisplayMetrics dm = res.getDisplayMetrics();\n android.content.res.Configuration conf = res.getConfiguration();\n conf.locale = new Locale(lang);\n Timber.d(\"Setting language: %s\", lang);\n res.updateConfiguration(conf, dm);\n }\n\n /**\n * Method provides defaultRetryPolice.\n * First Attempt = 14+(14*1)= 28s.\n * Second attempt = 28+(28*1)= 56s.\n * then invoke Response.ErrorListener callback.\n *\n * @return DefaultRetryPolicy object\n */\n public static DefaultRetryPolicy getDefaultRetryPolice() {\n return new DefaultRetryPolicy(14000, 2, 1);\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n mInstance = this;\n FacebookSdk.sdkInitialize(this);\n\n if (BuildConfig.DEBUG) {\n Timber.plant(new Timber.DebugTree());\n } else {\n Timber.d(\"Here should come error reporting library initialization and connection.\", TAG);\n // TODO example of implementation custom crash reporting solution - Crashlytics.\n// Fabric.with(this, new Crashlytics());\n// Timber.plant(new CrashReportingTree());\n }\n\n\n try {\n ANDROID_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);\n if (ANDROID_ID == null || ANDROID_ID.isEmpty()) {\n ANDROID_ID = \"0000000000000000\";\n }\n } catch (Exception e) {\n ANDROID_ID = \"0000000000000000\";\n }\n try {\n PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n APP_VERSION = packageInfo.versionName;\n } catch (PackageManager.NameNotFoundException e) {\n // should never happen\n Timber.e(e, \"App versionName not found. WTF?. This should never happen.\");\n }\n }\n\n /**\n * Method check, if internet is available.\n *\n * @return true if internet is available. Else otherwise.\n */\n public boolean isDataConnected() {\n ConnectivityManager connectMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = null;\n if (connectMan != null) {\n activeNetworkInfo = connectMan.getActiveNetworkInfo();\n }\n return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();\n }\n\n public boolean isWiFiConnection() {\n ConnectivityManager connectMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = null;\n if (connectMan != null) {\n activeNetworkInfo = connectMan.getActiveNetworkInfo();\n }\n return activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI;\n }\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n //////////////////////// Volley request ///////////////////////////////////////////////////////////////////////////////////////\n public RequestQueue getRequestQueue() {\n if (mRequestQueue == null) {\n mRequestQueue = Volley.newRequestQueue(this, new OkHttpStack());\n }\n return mRequestQueue;\n }\n\n @VisibleForTesting\n public void setRequestQueue(RequestQueue requestQueue) {\n mRequestQueue = requestQueue;\n }\n\n @VisibleForTesting\n public IdlingResource getCountingIdlingResource() {\n return EspressoIdlingResource.getIdlingResource();\n }\n\n public <T> void addToRequestQueue(Request<T> req, String tag) {\n // set the default tag if tag is empty\n req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);\n getRequestQueue().add(req);\n }\n\n public void cancelPendingRequests(Object tag) {\n if (mRequestQueue != null) {\n mRequestQueue.cancelAll(tag);\n }\n }\n //////////////////////// end of Volley request. ///////////////////////////////////////////////////////////////////////////////\n ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n // TODO example of implementation custom crash reporting solution - Crashlytics.\n// /**\n// * A tree which logs important information for crash reporting.\n// */\n// private static class CrashReportingTree extends Timber.Tree {\n// @Override\n// protected void log(int priority, String tag, String message, Throwable t) {\n// // Define message log priority\n// if (priority <= android.util.Log.VERBOSE) {\n// return;\n// }\n//\n// if (t != null) {\n// if (message != null) logMessage(tag, message);\n// Crashlytics.logException(t);\n// } else {\n// logMessage(tag, message);\n// }\n// }\n//\n// private void logMessage(String tag, String message) {\n// if (tag != null)\n// Crashlytics.log(\"TAG: \" + tag + \". MSG: \" + message);\n// else\n// Crashlytics.log(message);\n// }\n// }\n\n}", "public class Utils {\n\n private static Gson gson;\n\n private Utils() {}\n\n /**\n * Add specific parsing to gson\n *\n * @return new instance of {@link Gson}\n */\n public static Gson getGsonParser() {\n if (gson == null) {\n GsonBuilder gsonBuilder = new GsonBuilder();\n gsonBuilder.registerTypeAdapter(Filters.class, new DeserializerFilters());\n gson = gsonBuilder.create();\n }\n return gson;\n }\n\n /**\n * Generate top layer progress indicator.\n *\n * @param context activity context\n * @param cancelable can be progress layer canceled\n * @return dialog\n */\n public static ProgressDialog generateProgressDialog(Context context, boolean cancelable) {\n ProgressDialog progressDialog = new ProgressDialog(context, R.style.ProgressTheme);\n progressDialog.setMessage(context.getString(R.string.Loading));\n progressDialog.setCancelable(cancelable);\n return progressDialog;\n }\n\n /**\n * Check the device to make sure it has the Google Play Services APK. If\n * it doesn't, display a dialog that allows users to download the APK from\n * the Google Play Store or enable it in the device's system settings.\n */\n public static boolean checkPlayServices(Activity activity) {\n GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();\n int resultCode = apiAvailability.isGooglePlayServicesAvailable(activity);\n if (resultCode != ConnectionResult.SUCCESS) {\n Timber.e(\"Google play services don't working.\");\n if (apiAvailability.isUserResolvableError(resultCode)) {\n apiAvailability.getErrorDialog(activity, resultCode, 9000)\n .show();\n } else {\n Timber.e(\"GCM - This device is not supported.\");\n }\n return false;\n }\n return true;\n }\n\n /**\n * Method converts iso date string to better readable form.\n *\n * @param isoDate input iso date. Example: \"2016-04-13 13:21:04\".\n * @return processed date string.\n */\n public static String parseDate(String isoDate) {\n try {\n String[] parts = isoDate.split(\"-\");\n\n String year = parts[0];\n String month = parts[1];\n\n String dayTemp = parts[2];\n String[] parts2 = dayTemp.split(\" \");\n String day = parts2[0].trim();\n if (day.length() > 2) throw new RuntimeException(\"String with day number unexpected length.\");\n\n return day + \".\" + month + \".\" + year;\n } catch (Exception e) {\n Timber.e(e, \"Parsing order date created failed.\");\n return isoDate;\n }\n }\n\n /**\n * Method replace ordinary {@link URLSpan} with {@link DefensiveURLSpan}.\n *\n * @param spannedText text, where link spans should be replaced.\n * @param activity activity for displaying problems.\n * @return text, where link spans are replaced.\n */\n public static SpannableString safeURLSpanLinks(Spanned spannedText, Activity activity) {\n final SpannableString current = new SpannableString(spannedText);\n final URLSpan[] spans = current.getSpans(0, current.length(), URLSpan.class);\n int start, end;\n\n for (URLSpan span : spans) {\n start = current.getSpanStart(span);\n end = current.getSpanEnd(span);\n current.removeSpan(span);\n current.setSpan(new DefensiveURLSpan(span.getURL(), activity), start, end, 0);\n }\n return current;\n }\n\n public static int dpToPx(Context context, int dp) {\n return Math.round(dp * getPixelScaleFactor(context));\n }\n\n public static int pxToDp(Context context, int px) {\n return Math.round(px / getPixelScaleFactor(context));\n }\n\n private static float getPixelScaleFactor(Context context) {\n DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();\n return displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT;\n }\n\n\n public static Bitmap drawableToBitmap(Drawable drawable) {\n if (drawable instanceof BitmapDrawable)\n return ((BitmapDrawable) drawable).getBitmap();\n\n // We ask for the bounds if they have been set as they would be most\n // correct, then we check we are > 0\n final int width = !drawable.getBounds().isEmpty() ? drawable.getBounds().width() : drawable.getIntrinsicWidth();\n\n final int height = !drawable.getBounds().isEmpty() ? drawable.getBounds().height() : drawable.getIntrinsicHeight();\n\n // Now we check we are > 0\n final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height, Bitmap.Config.ARGB_8888);\n Canvas canvas = new Canvas(bitmap);\n drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n drawable.draw(canvas);\n\n return bitmap;\n }\n\n /**\n * Method calculates the percentage discounts.\n *\n * @param context simple context.\n * @param price Base product price.\n * @param discountPrice Product price after discount.\n * @return percentage discount with percent symbol.\n */\n public static String calculateDiscountPercent(Context context, double price, double discountPrice) {\n int percent;\n if (discountPrice >= price) {\n percent = 0;\n } else {\n percent = (int) Math.round(100 - ((discountPrice / price) * 100));\n }\n return String.format(context.getString(R.string.format_price_discount_percents), percent);\n }\n\n /**\n * Check if textInputLayout contains editText view. If so, then set text value to the view.\n *\n * @param textInputLayout wrapper for the editText view where the text value should be set.\n * @param text text value to display.\n */\n public static void setTextToInputLayout(TextInputLayout textInputLayout, String text) {\n if (textInputLayout != null && textInputLayout.getEditText() != null) {\n textInputLayout.getEditText().setText(text);\n } else {\n Timber.e(\"Setting text to null input wrapper, or without editText\");\n }\n }\n\n /**\n * Check if textInputLayout contains editText view. If so, then return text value of the view.\n *\n * @param textInputLayout wrapper for the editText view.\n * @return text value of the editText view.\n */\n public static String getTextFromInputLayout(TextInputLayout textInputLayout) {\n if (textInputLayout != null && textInputLayout.getEditText() != null) {\n return textInputLayout.getEditText().getText().toString();\n } else {\n return null;\n }\n }\n\n\n /**\n * Method checks if text input layout exist and contains some value.\n * If layout is empty, then show error value under the textInputLayout.\n *\n * @param textInputLayout textInputFiled for check.\n * @param errorValue value displayed when ext input is empty.\n * @return true if everything ok.\n */\n public static boolean checkTextInputLayoutValueRequirement(TextInputLayout textInputLayout, String errorValue) {\n if (textInputLayout != null && textInputLayout.getEditText() != null) {\n String text = Utils.getTextFromInputLayout(textInputLayout);\n if (text == null || text.isEmpty()) {\n textInputLayout.setErrorEnabled(true);\n textInputLayout.setError(errorValue);\n Timber.d(\"Input field %s missing text.\", textInputLayout.getHint());\n return false;\n } else {\n textInputLayout.setErrorEnabled(false);\n Timber.d(\"Input field: %s OK.\", textInputLayout.getHint());\n return true;\n }\n } else {\n Timber.e(new RuntimeException(), \"Checking null input field during order send.\");\n return false;\n }\n }\n\n /**\n * URLSpan which handles bad url format exception.\n */\n private static class DefensiveURLSpan extends URLSpan {\n\n Activity activity;\n\n public DefensiveURLSpan(String url, Activity activity) {\n super(url);\n this.activity = activity;\n }\n\n @Override\n public void onClick(View widget) {\n Uri uri = Uri.parse(getURL());\n Context context = widget.getContext();\n Intent intent = new Intent(Intent.ACTION_VIEW, uri);\n intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());\n try {\n context.startActivity(intent);\n } catch (ActivityNotFoundException e) {\n if (activity != null && !activity.isFinishing()) {\n MsgUtils.showToast(activity, MsgUtils.TOAST_TYPE_MESSAGE, activity.getString(R.string.Link_is_invalid), MsgUtils.ToastLength.SHORT);\n Timber.e(e, \"Invoked invalid web link: %s\", uri);\n }\n }\n }\n }\n}", "public class LoginDialogFragment extends DialogFragment implements FacebookCallback<LoginResult> {\n\n public static final String MSG_RESPONSE = \"response: %s\";\n private CallbackManager callbackManager;\n private LoginDialogInterface loginDialogInterface;\n private ProgressDialog progressDialog;\n private FormState actualFormState = FormState.BASE;\n private LinearLayout loginBaseForm;\n private LinearLayout loginRegistrationForm;\n private LinearLayout loginEmailForm;\n private LinearLayout loginEmailForgottenForm;\n\n private TextInputLayout loginRegistrationEmailWrapper;\n private TextInputLayout loginRegistrationPasswordWrapper;\n private RadioButton loginRegistrationGenderWoman;\n private TextInputLayout loginEmailEmailWrapper;\n private TextInputLayout loginEmailPasswordWrapper;\n private TextInputLayout loginEmailForgottenEmailWrapper;\n\n /**\n * Creates dialog which handles user login, registration and forgotten password function.\n *\n * @param loginDialogInterface listener receiving login/registration results.\n * @return new instance of dialog.\n */\n public static LoginDialogFragment newInstance(LoginDialogInterface loginDialogInterface) {\n LoginDialogFragment frag = new LoginDialogFragment();\n frag.loginDialogInterface = loginDialogInterface;\n return frag;\n }\n\n public static void logoutUser() {\n LoginManager fbManager = LoginManager.getInstance();\n if (fbManager != null) fbManager.logOut();\n SettingsMy.setActiveUser(null);\n MainActivity.updateCartCountNotification();\n MainActivity.invalidateDrawerMenuHeader();\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setStyle(DialogFragment.STYLE_NO_TITLE, R.style.dialogFullscreen);\n progressDialog = Utils.generateProgressDialog(getActivity(), false);\n }\n\n @Override\n public void onStart() {\n super.onStart();\n Dialog d = getDialog();\n if (d != null) {\n int width = ViewGroup.LayoutParams.MATCH_PARENT;\n int height = ViewGroup.LayoutParams.MATCH_PARENT;\n Window window = d.getWindow();\n window.setLayout(width, height);\n window.setWindowAnimations(R.style.dialogFragmentAnimation);\n d.setOnKeyListener(new DialogInterface.OnKeyListener() {\n @Override\n public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {\n if (BuildConfig.DEBUG)\n Timber.d(\"onKey: %d (Back=%d). Event:%d (Down:%d, Up:%d)\", keyCode, KeyEvent.KEYCODE_BACK, event.getAction(),\n KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP);\n if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {\n switch (actualFormState) {\n case REGISTRATION:\n if (event.getAction() == KeyEvent.ACTION_UP) {\n setVisibilityOfRegistrationForm(false);\n }\n return true;\n case FORGOTTEN_PASSWORD:\n if (event.getAction() == KeyEvent.ACTION_UP) {\n setVisibilityOfEmailForgottenForm(false);\n }\n return true;\n case EMAIL:\n if (event.getAction() == KeyEvent.ACTION_UP) {\n setVisibilityOfEmailForm(false);\n }\n return true;\n default:\n return false;\n }\n }\n return false;\n }\n });\n }\n }\n\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n Timber.d(\"%s - OnCreateView\", this.getClass().getSimpleName());\n View view = inflater.inflate(R.layout.dialog_login, container, false);\n callbackManager = CallbackManager.Factory.create();\n\n loginBaseForm = view.findViewById(R.id.login_base_form);\n loginRegistrationForm = view.findViewById(R.id.login_registration_form);\n loginEmailForm = view.findViewById(R.id.login_email_form);\n loginEmailForgottenForm = view.findViewById(R.id.login_email_forgotten_form);\n\n prepareLoginFormNavigation(view);\n prepareInputBoxes(view);\n prepareActionButtons(view);\n return view;\n }\n\n private void prepareInputBoxes(View view) {\n // Registration form\n loginRegistrationEmailWrapper = view.findViewById(R.id.login_registration_email_wrapper);\n loginRegistrationPasswordWrapper = view.findViewById(R.id.login_registration_password_wrapper);\n loginRegistrationGenderWoman = view.findViewById(R.id.login_registration_sex_woman);\n EditText registrationPassword = loginRegistrationPasswordWrapper.getEditText();\n if (registrationPassword != null) {\n registrationPassword.setOnTouchListener(new OnTouchPasswordListener(registrationPassword));\n }\n\n\n // Login email form\n loginEmailEmailWrapper = view.findViewById(R.id.login_email_email_wrapper);\n EditText loginEmail = loginEmailEmailWrapper.getEditText();\n if (loginEmail != null) loginEmail.setText(SettingsMy.getUserEmailHint());\n loginEmailPasswordWrapper = view.findViewById(R.id.login_email_password_wrapper);\n EditText emailPassword = loginEmailPasswordWrapper.getEditText();\n if (emailPassword != null) {\n emailPassword.setOnTouchListener(new OnTouchPasswordListener(emailPassword));\n emailPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEND || actionId == 124) {\n invokeLoginWithEmail();\n return true;\n }\n return false;\n }\n });\n }\n\n loginEmailForgottenEmailWrapper = view.findViewById(R.id.login_email_forgotten_email_wrapper);\n EditText emailForgottenPassword = loginEmailForgottenEmailWrapper.getEditText();\n if (emailForgottenPassword != null)\n emailForgottenPassword.setText(SettingsMy.getUserEmailHint());\n\n // Simple accounts whisperer.\n Account[] accounts = AccountManager.get(getActivity()).getAccounts();\n String[] addresses = new String[accounts.length];\n for (int i = 0; i < accounts.length; i++) {\n addresses[i] = accounts[i].name;\n Timber.e(\"Sets autocompleteEmails: %s\", accounts[i].name);\n }\n\n ArrayAdapter<String> emails = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, addresses);\n AutoCompleteTextView textView = view.findViewById(R.id.login_registration_email_text_auto);\n textView.setAdapter(emails);\n }\n\n private void prepareLoginFormNavigation(View view) {\n // Login email\n Button loginFormEmailButton = view.findViewById(R.id.login_form_email_btn);\n loginFormEmailButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n setVisibilityOfEmailForm(true);\n }\n });\n ImageButton closeEmailBtn = view.findViewById(R.id.login_email_close_button);\n closeEmailBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Slow to display ripple effect\n (new Handler()).postDelayed(new Runnable() {\n @Override\n public void run() {\n setVisibilityOfEmailForm(false);\n }\n }, 200);\n }\n });\n\n // Registration\n TextView loginFormRegistrationButton = view.findViewById(R.id.login_form_registration_btn);\n loginFormRegistrationButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n setVisibilityOfRegistrationForm(true);\n }\n });\n ImageButton closeRegistrationBtn = view.findViewById(R.id.login_registration_close_button);\n closeRegistrationBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Slow to display ripple effect\n (new Handler()).postDelayed(new Runnable() {\n @Override\n public void run() {\n setVisibilityOfRegistrationForm(false);\n }\n }, 200);\n }\n });\n\n // Email forgotten password\n TextView loginEmailFormForgottenButton = view.findViewById(R.id.login_email_forgotten_password);\n loginEmailFormForgottenButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n setVisibilityOfEmailForgottenForm(true);\n }\n });\n ImageButton closeEmailForgottenFormBtn = view.findViewById(R.id.login_email_forgotten_back_button);\n closeEmailForgottenFormBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Slow to display ripple effect\n (new Handler()).postDelayed(new Runnable() {\n @Override\n public void run() {\n setVisibilityOfEmailForgottenForm(false);\n }\n }, 200);\n }\n });\n }\n\n private void prepareActionButtons(View view) {\n TextView loginBaseSkip = view.findViewById(R.id.login_form_skip);\n loginBaseSkip.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n// if (loginDialogInterface != null) loginDialogInterface.skipLogin();\n dismiss();\n }\n });\n\n // FB login\n Button fbLogin = view.findViewById(R.id.login_form_facebook);\n fbLogin.setOnClickListener(new OnSingleClickListener() {\n @Override\n public void onSingleClick(View v) {\n invokeFacebookLogin();\n }\n });\n\n Button emailLogin = view.findViewById(R.id.login_email_confirm);\n emailLogin.setOnClickListener(new OnSingleClickListener() {\n @Override\n public void onSingleClick(View v) {\n invokeLoginWithEmail();\n }\n });\n\n Button registerBtn = view.findViewById(R.id.login_registration_confirm);\n registerBtn.setOnClickListener(new OnSingleClickListener() {\n @Override\n public void onSingleClick(View v) {\n invokeRegisterNewUser();\n }\n });\n\n Button resetPassword = view.findViewById(R.id.login_email_forgotten_confirm);\n resetPassword.setOnClickListener(new OnSingleClickListener() {\n @Override\n public void onSingleClick(View v) {\n invokeResetPassword();\n }\n });\n }\n\n private void invokeFacebookLogin() {\n LoginManager.getInstance().registerCallback(callbackManager, this);\n LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList(\"public_profile\", \"email\"));\n }\n\n private void invokeRegisterNewUser() {\n hideSoftKeyboard();\n if (isRequiredFields(loginRegistrationEmailWrapper, loginRegistrationPasswordWrapper)) {\n// SettingsMy.setUserEmailHint(etRegistrationEmail.getText().toString());\n registerNewUser(loginRegistrationEmailWrapper.getEditText(), loginRegistrationPasswordWrapper.getEditText());\n }\n }\n\n private void registerNewUser(EditText editTextEmail, EditText editTextPassword) {\n SettingsMy.setUserEmailHint(editTextEmail.getText().toString());\n String url = String.format(EndPoints.USER_REGISTER, SettingsMy.getActualNonNullShop(getActivity()).getId());\n progressDialog.show();\n\n // get selected radio button from radioGroup\n JSONObject jo = new JSONObject();\n try {\n jo.put(JsonUtils.TAG_EMAIL, editTextEmail.getText().toString().trim());\n jo.put(JsonUtils.TAG_PASSWORD, editTextPassword.getText().toString().trim());\n jo.put(JsonUtils.TAG_GENDER, loginRegistrationGenderWoman.isChecked() ? \"female\" : \"male\");\n } catch (JSONException e) {\n Timber.e(e, \"Parse new user registration exception\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.SHORT);\n return;\n }\n if (BuildConfig.DEBUG) Timber.d(\"Register new user: %s\", jo.toString());\n\n GsonRequest<User> registerNewUser = new GsonRequest<>(Request.Method.POST, url, jo.toString(), User.class,\n new Response.Listener<User>() {\n @Override\n public void onResponse(@NonNull User response) {\n Timber.d(MSG_RESPONSE, response.toString());\n handleUserLogin(response);\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n if (progressDialog != null) progressDialog.cancel();\n MsgUtils.logAndShowErrorMessage(getActivity(), error);\n }\n });\n registerNewUser.setRetryPolicy(MyApplication.getDefaultRetryPolice());\n registerNewUser.setShouldCache(false);\n MyApplication.getInstance().addToRequestQueue(registerNewUser, CONST.LOGIN_DIALOG_REQUESTS_TAG);\n }\n\n private void invokeLoginWithEmail() {\n hideSoftKeyboard();\n if (isRequiredFields(loginEmailEmailWrapper, loginEmailPasswordWrapper)) {\n logInWithEmail(loginEmailEmailWrapper.getEditText(), loginEmailPasswordWrapper.getEditText());\n }\n }\n\n private void logInWithEmail(EditText editTextEmail, EditText editTextPassword) {\n SettingsMy.setUserEmailHint(editTextEmail.getText().toString());\n String url = String.format(EndPoints.USER_LOGIN_EMAIL, SettingsMy.getActualNonNullShop(getActivity()).getId());\n progressDialog.show();\n\n JSONObject jo;\n try {\n jo = JsonUtils.createUserAuthentication(editTextEmail.getText().toString().trim(), editTextPassword.getText().toString().trim());\n editTextPassword.setText(\"\");\n } catch (JSONException e) {\n Timber.e(e, \"Parse logInWithEmail exception\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.SHORT);\n return;\n }\n if (BuildConfig.DEBUG) Timber.d(\"Login user: %s\", jo.toString());\n\n GsonRequest<User> userLoginEmailRequest = new GsonRequest<>(Request.Method.POST, url, jo.toString(), User.class,\n new Response.Listener<User>() {\n @Override\n public void onResponse(@NonNull User response) {\n Timber.d(MSG_RESPONSE, response.toString());\n handleUserLogin(response);\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n if (progressDialog != null) progressDialog.cancel();\n MsgUtils.logAndShowErrorMessage(getActivity(), error);\n }\n });\n userLoginEmailRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());\n userLoginEmailRequest.setShouldCache(false);\n MyApplication.getInstance().addToRequestQueue(userLoginEmailRequest, CONST.LOGIN_DIALOG_REQUESTS_TAG);\n }\n\n private void handleUserLogin(User user) {\n if (progressDialog != null) progressDialog.cancel();\n SettingsMy.setActiveUser(user);\n\n // Invalidate GCM token for new registration with authorized user.\n SettingsMy.setTokenSentToServer(false);\n if (getActivity() instanceof MainActivity)\n ((MainActivity) getActivity()).registerGcmOnServer();\n\n MainActivity.invalidateDrawerMenuHeader();\n\n if (loginDialogInterface != null) {\n loginDialogInterface.successfulLoginOrRegistration(user);\n } else {\n Timber.e(\"Interface is null\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.SHORT);\n }\n dismiss();\n }\n\n private void invokeResetPassword() {\n EditText emailForgottenPasswordEmail = loginEmailForgottenEmailWrapper.getEditText();\n if (emailForgottenPasswordEmail == null || emailForgottenPasswordEmail.getText().toString().equalsIgnoreCase(\"\")) {\n loginEmailForgottenEmailWrapper.setErrorEnabled(true);\n loginEmailForgottenEmailWrapper.setError(getString(R.string.Required_field));\n } else {\n loginEmailForgottenEmailWrapper.setErrorEnabled(false);\n resetPassword(emailForgottenPasswordEmail);\n }\n }\n\n private void resetPassword(EditText emailOfForgottenPassword) {\n String url = String.format(EndPoints.USER_RESET_PASSWORD, SettingsMy.getActualNonNullShop(getActivity()).getId());\n progressDialog.show();\n\n JSONObject jo = new JSONObject();\n try {\n jo.put(JsonUtils.TAG_EMAIL, emailOfForgottenPassword.getText().toString().trim());\n } catch (JSONException e) {\n Timber.e(e, \"Parse resetPassword exception\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.SHORT);\n return;\n }\n if (BuildConfig.DEBUG) Timber.d(\"Reset password email: %s\", jo.toString());\n\n JsonRequest req = new JsonRequest(Request.Method.POST, url,\n jo, new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n Timber.d(\"Reset password on url success. Response: %s\", response.toString());\n progressDialog.cancel();\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_MESSAGE, getString(R.string.Check_your_email_we_sent_you_an_confirmation_email), MsgUtils.ToastLength.LONG);\n setVisibilityOfEmailForgottenForm(false);\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n if (progressDialog != null) progressDialog.cancel();\n MsgUtils.logAndShowErrorMessage(getActivity(), error);\n }\n });\n req.setRetryPolicy(MyApplication.getDefaultRetryPolice());\n req.setShouldCache(false);\n MyApplication.getInstance().addToRequestQueue(req, CONST.LOGIN_DIALOG_REQUESTS_TAG);\n }\n\n private void hideSoftKeyboard() {\n if (getActivity() != null && getView() != null) {\n InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);\n imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);\n }\n }\n\n private void setVisibilityOfRegistrationForm(boolean setVisible) {\n if (setVisible) {\n actualFormState = FormState.REGISTRATION;\n loginBaseForm.setVisibility(View.INVISIBLE);\n loginRegistrationForm.setVisibility(View.VISIBLE);\n } else {\n actualFormState = FormState.BASE;\n loginBaseForm.setVisibility(View.VISIBLE);\n loginRegistrationForm.setVisibility(View.INVISIBLE);\n hideSoftKeyboard();\n }\n }\n\n private void setVisibilityOfEmailForm(boolean setVisible) {\n if (setVisible) {\n actualFormState = FormState.EMAIL;\n loginBaseForm.setVisibility(View.INVISIBLE);\n loginEmailForm.setVisibility(View.VISIBLE);\n } else {\n actualFormState = FormState.BASE;\n loginBaseForm.setVisibility(View.VISIBLE);\n loginEmailForm.setVisibility(View.INVISIBLE);\n hideSoftKeyboard();\n }\n }\n\n private void setVisibilityOfEmailForgottenForm(boolean setVisible) {\n if (setVisible) {\n actualFormState = FormState.FORGOTTEN_PASSWORD;\n loginEmailForm.setVisibility(View.INVISIBLE);\n loginEmailForgottenForm.setVisibility(View.VISIBLE);\n } else {\n actualFormState = FormState.EMAIL;\n loginEmailForm.setVisibility(View.VISIBLE);\n loginEmailForgottenForm.setVisibility(View.INVISIBLE);\n }\n hideSoftKeyboard();\n }\n\n /**\n * Check if editTexts are valid view and if user set all required fields.\n *\n * @return true if ok.\n */\n private boolean isRequiredFields(TextInputLayout emailWrapper, TextInputLayout passwordWrapper) {\n if (emailWrapper == null || passwordWrapper == null) {\n Timber.e(new RuntimeException(), \"Called isRequiredFields with null parameters.\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.LONG);\n return false;\n } else {\n EditText email = emailWrapper.getEditText();\n EditText password = passwordWrapper.getEditText();\n if (email == null || password == null) {\n Timber.e(new RuntimeException(), \"Called isRequiredFields with null editTexts in wrappers.\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.LONG);\n return false;\n } else {\n boolean isEmail = false;\n boolean isPassword = false;\n\n if (email.getText().toString().equalsIgnoreCase(\"\")) {\n emailWrapper.setErrorEnabled(true);\n emailWrapper.setError(getString(R.string.Required_field));\n } else {\n emailWrapper.setErrorEnabled(false);\n isEmail = true;\n }\n\n if (password.getText().toString().equalsIgnoreCase(\"\")) {\n passwordWrapper.setErrorEnabled(true);\n passwordWrapper.setError(getString(R.string.Required_field));\n } else {\n passwordWrapper.setErrorEnabled(false);\n isPassword = true;\n }\n\n if (isEmail && isPassword) {\n return true;\n } else {\n Timber.e(\"Some fields are required.\");\n return false;\n }\n }\n }\n }\n\n @Override\n public void onStop() {\n super.onStop();\n MyApplication.getInstance().getRequestQueue().cancelAll(CONST.LOGIN_DIALOG_REQUESTS_TAG);\n }\n\n @Override\n public void onDetach() {\n loginDialogInterface = null;\n super.onDetach();\n }\n\n @Override\n public void onSuccess(final LoginResult loginResult) {\n Timber.d(\"FB login success\");\n if (loginResult == null) {\n Timber.e(\"Fb login succeed with null loginResult.\");\n handleNonFatalError(getString(R.string.Facebook_login_failed), true);\n } else {\n Timber.d(\"Result: %s\", loginResult.toString());\n GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),\n new GraphRequest.GraphJSONObjectCallback() {\n @Override\n public void onCompleted(JSONObject object, GraphResponse response) {\n if (response != null && response.getError() == null) {\n verifyUserOnApi(object, loginResult.getAccessToken());\n } else {\n Timber.e(\"Error on receiving user profile information.\");\n if (response != null && response.getError() != null) {\n Timber.e(new RuntimeException(), \"Error: %s\", response.getError().toString());\n }\n handleNonFatalError(getString(R.string.Receiving_facebook_profile_failed), true);\n }\n }\n });\n Bundle parameters = new Bundle();\n parameters.putString(\"fields\", \"id,name,email,gender\");\n request.setParameters(parameters);\n request.executeAsync();\n }\n }\n\n @Override\n public void onCancel() {\n Timber.d(\"Fb login canceled\");\n }\n\n @Override\n public void onError(FacebookException e) {\n Timber.e(e, \"Fb login error\");\n handleNonFatalError(getString(R.string.Facebook_login_failed), false);\n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (callbackManager != null)\n callbackManager.onActivityResult(requestCode, resultCode, data);\n else {\n Timber.d(\"OnActivityResult, null callbackManager object.\");\n }\n }\n\n /**\n * Volley request that sends FB_ID and FB_ACCESS_TOKEN to API\n */\n private void verifyUserOnApi(JSONObject userProfileObject, AccessToken fbAccessToken) {\n String url = String.format(EndPoints.USER_LOGIN_FACEBOOK, SettingsMy.getActualNonNullShop(getActivity()).getId());\n JSONObject jo = new JSONObject();\n try {\n jo.put(JsonUtils.TAG_FB_ID, userProfileObject.getString(\"id\"));\n jo.put(JsonUtils.TAG_FB_ACCESS_TOKEN, fbAccessToken.getToken());\n } catch (JSONException e) {\n Timber.e(e, \"Exception while parsing fb user.\");\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.LONG);\n return;\n }\n\n progressDialog.show();\n GsonRequest<User> verifyFbUser = new GsonRequest<>(Request.Method.POST, url, jo.toString(), User.class,\n new Response.Listener<User>() {\n @Override\n public void onResponse(@NonNull User response) {\n Timber.d(MSG_RESPONSE, response.toString());\n handleUserLogin(response);\n }\n }, new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n if (progressDialog != null) progressDialog.cancel();\n MsgUtils.logAndShowErrorMessage(getActivity(), error);\n LoginDialogFragment.logoutUser();\n }\n }, getFragmentManager(), null);\n verifyFbUser.setRetryPolicy(MyApplication.getDefaultRetryPolice());\n verifyFbUser.setShouldCache(false);\n MyApplication.getInstance().addToRequestQueue(verifyFbUser, CONST.LOGIN_DIALOG_REQUESTS_TAG);\n }\n\n /**\n * Handle errors, when user have identity at least.\n * Show error message to user.\n */\n private void handleNonFatalError(String message, boolean logoutFromFb) {\n if (logoutFromFb) {\n LoginDialogFragment.logoutUser();\n }\n if (getActivity() != null)\n MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_MESSAGE, message, MsgUtils.ToastLength.LONG);\n }\n\n private enum FormState {\n BASE, REGISTRATION, EMAIL, FORGOTTEN_PASSWORD\n }\n}", "public class LoginExpiredDialogFragment extends DialogFragment {\n\n @NonNull\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n Timber.d(\"%s - OnCreateView\", this.getClass().getSimpleName());\n\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.myAlertDialogStyle);\n builder.setTitle(R.string.Oops_login_expired);\n builder.setMessage(R.string.Your_session_has_expired_Please_log_in_again);\n\n builder.setPositiveButton(R.string.Ok, new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n if (getActivity() instanceof MainActivity)\n ((MainActivity) getActivity()).onDrawerBannersSelected();\n dialog.dismiss();\n }\n });\n\n return builder.create();\n }\n}" ]
import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Base64; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.JsonSyntaxException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.Map; import bf.io.openshop.BuildConfig; import bf.io.openshop.CONST; import bf.io.openshop.MyApplication; import bf.io.openshop.utils.Utils; import bf.io.openshop.UX.dialogs.LoginDialogFragment; import bf.io.openshop.UX.dialogs.LoginExpiredDialogFragment; import timber.log.Timber;
package bf.io.openshop.api; /** * Basic request using Gson's reflection. * Usable for authorized and unauthorized requests. * Allowing for an optional {@link String} to be passed in as part of the request body. * * @param <T> object which is serializable from request. */ public class GsonRequest<T> extends Request<T> { /** * Default charset for JSON request. */ private static final String PROTOCOL_CHARSET = "utf-8"; /** * Class of object which is serializable from request. */ private final Class<T> clazz; /** * User token for authorized requests. */ private final String accessToken; private final String requestBody; private final Response.Listener<T> successListener; private String requestUrl; private int requestStatusCode; private FragmentManager fragmentManager; /** * Create a new authorized request. * * @param method The HTTP method to use * @param requestUrl URL to fetch the JSON from * @param requestBody A {@link String} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param clazz Relevant class object, for Gson's reflection * @param successListener Listener to retrieve successful response * @param errorListener Error listener, or null to ignore errors * @param fragmentManager Manager to create re-login dialog on HTTP status 403. Null is allowed. * @param accessToken Token identifying user used for user specific requests. */ public GsonRequest(int method, String requestUrl, String requestBody, Class<T> clazz, Response.Listener<T> successListener, Response.ErrorListener errorListener, FragmentManager fragmentManager, String accessToken) { super(method, requestUrl, errorListener); this.clazz = clazz; this.requestUrl = requestUrl; this.requestBody = requestBody; this.successListener = successListener; this.fragmentManager = fragmentManager; this.accessToken = accessToken; } /** * Create a new unauthorized request. * * @param method The HTTP method to use * @param requestUrl URL to fetch the JSON from * @param requestBody A {@link String} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param clazz Relevant class object, for Gson's reflection * @param successListener Listener to retrieve successful response * @param errorListener Error listener, or null to ignore errors */ public GsonRequest(int method, String requestUrl, String requestBody, Class<T> clazz, Response.Listener<T> successListener, Response.ErrorListener errorListener) { this(method, requestUrl, requestBody, clazz, successListener, errorListener, null, null); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>();
headers.put("Client-Version", MyApplication.APP_VERSION);
1
MiniPa/cjs_ssms
cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/service/master/UserFrontServiceImpl.java
[ "public class UUIDUtil {\n public static String uuid(){\n UUID uuid=UUID.randomUUID();\n String str = uuid.toString();\n String uuidStr=str.replace(\"-\", \"\");\n return uuidStr;\n }\n}", "public class MD5Util {\n\n public static final String DEFAULT_SALT = \"minipa_chengjs\";\n\n /**\n * 指定加密盐\n * @param str\n * @param salt\n * @return\n */\n public static String md5(String str, String salt){\n if (StringUtil.isNullOrEmpty(salt)) {\n salt = DEFAULT_SALT;\n }\n return new Md5Hash(str,salt).toString() ;\n }\n\n /**\n * 采用默认加密盐\n * @param str\n * @return\n */\n public static String md5(String str){\n return new Md5Hash(str,DEFAULT_SALT).toString() ;\n }\n\n public static void main(String[] args) {\n String md5 = md5(\"123456\", DEFAULT_SALT) ;\n System.out.println(md5); // 119d3a4d2dfbca3d23bd1c52a1d6a6e6\n }\n\n}", "public interface UserRolePermissionDao extends Mapper<Country> {\n\n UUser findByLogin(UUser user);\n\n int findAllCount(UUser user);\n\n List<UUser> findHotUser();\n\n List<UUser> findByParams(UUser user, RowBounds rowBound);\n\n List<UUser> findAllByQuery(UUser user);\n\n List<UUser> list(Map<String, Object> map);\n\n Long getTotal(Map<String, Object> map);\n\n UUser findUserByUsername(String username);\n\n Set<String> findRoleNames(String username);\n\n Set<String> findPermissionNames(Set<String> roleNames);\n\n Set<String> findRoleNamesByUserName(@Param(\"userName\")String userName);\n\n Set<String> findPermissionNamesByRoleNames(@Param(\"set\")Set<String> roleNames);\n\n UUser findUserByUserName(@Param(\"userName\")String userName);\n\n}", "public interface UUserMapper extends Mapper<UUser> {\n\n /**\n * 测试通过POJO参数方式获取page\n * @param uuser\n * @return\n */\n List<UUser> gridUsers(UUser uuser);\n\n /**\n * 测试通过Map参数方式获取page\n * @param params\n * @return\n */\n List<Map<String,String>> users(Map<String,String> params);\n\n}", "@Table(name = \"u_user\")\npublic class UUser {\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY, generator = \"SELECT replace(t.uuid,\\\"-\\\",\\\"\\\") FROM (SELECT uuid() uuid FROM dual) t\")\n private String id;\n\n @Column(name = \"username\")\n private String username;\n\n @Column(name = \"password\")\n private String password;\n\n @Column(name = \"description\")\n private String description;\n\n @Column(name = \"discard\")\n private String discard;\n\n @Column(name = \"createtime\")\n private Date createtime;\n\n @Column(name = \"modifytime\")\n private Date modifytime;\n\n /**\n * @return id\n */\n public String getId() {\n return id;\n }\n\n /**\n * @param id\n */\n public void setId(String id) {\n this.id = id == null ? null : id.trim();\n }\n\n /**\n * @return username\n */\n public String getUsername() {\n return username;\n }\n\n /**\n * @param username\n */\n public void setUsername(String username) {\n this.username = username == null ? null : username.trim();\n }\n\n /**\n * @return password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * @param password\n */\n public void setPassword(String password) {\n this.password = password == null ? null : password.trim();\n }\n\n /**\n * @return description\n */\n public String getDescription() {\n return description;\n }\n\n /**\n * @param description\n */\n public void setDescription(String description) {\n this.description = description == null ? null : description.trim();\n }\n\n /**\n * @return discard\n */\n public String getDiscard() {\n return discard;\n }\n\n /**\n * @param discard\n */\n public void setDiscard(String discard) {\n this.discard = discard == null ? null : discard.trim();\n }\n\n /**\n * @return createtime\n */\n public Date getCreatetime() {\n return createtime;\n }\n\n /**\n * @param createtime\n */\n public void setCreatetime(Date createtime) {\n this.createtime = createtime;\n }\n\n /**\n * @return modifytime\n */\n public Date getModifytime() {\n return modifytime;\n }\n\n /**\n * @param modifytime\n */\n public void setModifytime(Date modifytime) {\n this.modifytime = modifytime;\n }\n}", "public class Transactioner {\n\n private static final Logger log = LoggerFactory.getLogger(Transactioner.class);\n\n private TransactionStatus status = null;\n\n private DataSourceTransactionManager transactionManager;\n\n /**\n * 初始化事务对象并开启事务\n * @param transactionManager\n */\n public Transactioner(DataSourceTransactionManager transactionManager) {\n this.transactionManager = transactionManager;\n start(transactionManager);\n }\n\n /**\n * 开启事物\n * @param transactionManager\n */\n public void start(DataSourceTransactionManager transactionManager) {\n DefaultTransactionDefinition def = new DefaultTransactionDefinition();\n /*PROPAGATION_REQUIRES_NEW: 事物隔离级别,开启新事务*/\n def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);\n status = transactionManager.getTransaction(def);\n }\n\n /**\n * 提交事务\n * @param commitOrRollback true-commit, false-rollback\n */\n public void end(boolean commitOrRollback) {\n if (null == status) {\n log.warn(\"事务未开启无法提交\");\n return;\n }\n if (commitOrRollback) {\n transactionManager.commit(status);\n } else {\n transactionManager.rollback(status);\n }\n }\n\n\n}", "public class Page<T> implements Serializable {\n private static final long serialVersionUID = 1L;\n /**\n * 每页显示的数量\n **/\n private int limit;\n /**\n * 总条数\n **/\n private int total;\n /**\n * 当前页数\n **/\n private int pageNo;\n /**\n * 存放集合\n **/\n private List<T> rows = new ArrayList<T>();\n\n public int getOffset() {\n return (pageNo - 1) * limit;\n }\n\n public void setOffset(int offset) {\n }\n\n public void setTotal(int total) {\n this.total = total;\n }\n\n public int getLimit() {\n return limit;\n }\n\n public void setLimit(int limit) {\n this.limit = limit;\n }\n\n\n public List<T> getRows() {\n return rows;\n }\n\n public void setRows(List<T> rows) {\n this.rows = rows;\n }\n\n // 计算总页数\n public int getTotalPages() {\n int totalPages;\n if (total % limit == 0) {\n totalPages = total / limit;\n } else {\n totalPages = (total / limit) + 1;\n }\n return totalPages;\n }\n\n public int getTotal() {\n return total;\n }\n\n public int getOffsets() {\n return (pageNo - 1) * limit;\n }\n\n public int getEndIndex() {\n if (getOffsets() + limit > total) {\n return total;\n } else {\n return getOffsets() + limit;\n }\n }\n\n public int getPageNo() {\n return pageNo;\n }\n\n public void setPageNo(int pageNo) {\n this.pageNo = pageNo;\n }\n}" ]
import com.chengjs.cjsssmsweb.common.util.UUIDUtil; import com.chengjs.cjsssmsweb.common.util.codec.MD5Util; import com.chengjs.cjsssmsweb.mybatis.mapper.dao.UserRolePermissionDao; import com.chengjs.cjsssmsweb.mybatis.mapper.master.UUserMapper; import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser; import com.chengjs.cjsssmsweb.util.Transactioner; import com.chengjs.cjsssmsweb.util.page.Page; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Set;
package com.chengjs.cjsssmsweb.service.master; /** * IUserServiceImpl: * author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/8/29 */ @Service public class UserFrontServiceImpl implements IUserFrontService{ @Autowired private DataSourceTransactionManager transactionManager; /*========================== userMapper ==========================*/ @Autowired
private UUserMapper userMapper;
3
pinfake/pes6j
src/pes6j/servers/Tools.java
[ "public class Db implements Serializable {\n\tprivate Connection conn;\n\tprivate Statement stmt;\n\tprivate ResultSet rset;\n\tprivate Properties properties;\n\tprivate int dbType = -1;\n\tprivate int isolationLevel;\n\n\tpublic static int ISO_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;\n\n\tpublic static final String DbTypeNames[] = new String[] {\n\t\t\t\"MYSQL\", \"POSTGRES\" //$NON-NLS-1$ //$NON-NLS-2$\n\t};\n\n\tpublic static final int TYPE_MYSQL = 0;\n\tpublic static final int TYPE_POSTGRES = 1;\n\n\tpublic Db(Properties prop) {\n\t\tthis.properties = prop;\n\n\t\tString type = properties.getProperty(\"db-type\"); //$NON-NLS-1$\n\n\t\tif (type == null) {\n\t\t\tdbType = -1;\n\t\t\treturn;\n\t\t}\n\n\t\tif (type.toUpperCase().equals(DbTypeNames[TYPE_POSTGRES])) {\n\t\t\tdbType = TYPE_POSTGRES;\n\t\t}\n\t\tif (type.toUpperCase().equals(DbTypeNames[TYPE_MYSQL])) {\n\t\t\tdbType = TYPE_MYSQL;\n\t\t}\n\t}\n\n\tpublic void connect() throws SQLException {\n\t\tswitch (dbType) {\n\t\tcase TYPE_POSTGRES:\n\t\t\tconnect_postgres();\n\t\t\tbreak;\n\t\tcase TYPE_MYSQL:\n\t\t\tconnect_mysql();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Incorrect database type, check the properties file\"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$\n\t\t}\n\t}\n\n\tpublic int getDbType() {\n\t\treturn (dbType);\n\t}\n\n\tprivate void connect_postgres() throws SQLException {\n\t\ttry {\n\t\t\tClass.forName(\"org.postgresql.Driver\"); //$NON-NLS-1$\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tthrow new SQLException(ex.getMessage());\n\t\t}\n\n\t\t// Connect to the Database\n\n\t\t// conn = DriverManager.getConnection\n\t\t// (\"jdbc:oracle:thin:@localhost:1521:rinol\", \"rinoluser\", \"rinoluser\");\n\t\tif (conn == null || conn.isClosed()) {\n\t\t\tconn = DriverManager.getConnection(\"jdbc:postgresql://\" //$NON-NLS-1$\n\t\t\t\t\t+ properties.getProperty(\"db-host\") //$NON-NLS-1$\n\t\t\t\t\t+ \"/\" //$NON-NLS-1$\n\t\t\t\t\t+ properties.getProperty(\"db-name\"), //$NON-NLS-1$\n\t\t\t\t\tproperties.getProperty(\"db-username\"), //$NON-NLS-1$\n\t\t\t\t\tproperties.getProperty(\"db-password\")); //$NON-NLS-1$\n\t\t\tisolationLevel = conn.getTransactionIsolation();\n\t\t}\n\t}\n\t\n\tprivate void connect_mysql() throws SQLException {\n\n\n\t\t// Connect to the Database\n\n\t\t// conn = DriverManager.getConnection\n\t\t// (\"jdbc:oracle:thin:@localhost:1521:rinol\", \"rinoluser\", \"rinoluser\");\n\t\tif (conn == null || conn.isClosed()) {\n\t\t\tconn =\n\t\t\t\tDriverManager.getConnection(\"jdbc:mysql://\"+properties.getProperty(\"db-host\")+\"/\"+\n\t\t\t\t\t\tproperties.getProperty(\"db-name\")+\"?\" +\n\t\t\t\t\"user=\"+properties.getProperty(\"db-username\")+\n\t\t\t\t\"&password=\"+properties.getProperty(\"db-password\"));\n\t\t\tisolationLevel = conn.getTransactionIsolation();\n\t\t}\n\t}\n\n\tpublic void disconnect() throws SQLException {\n\t\tconn.close();\n\t}\n\n\tpublic String parseSQL(String raw) {\n\t\tString parsed = \"\"; //$NON-NLS-1$\n\n\t\treturn (parsed);\n\t}\n\n\tpublic PreparedStatement prepareStatement(String query ) throws SQLException {\n\t\tPreparedStatement ps = conn.prepareStatement(query/*, Statement.RETURN_GENERATED_KEYS*/);\n\t\tps.clearParameters();\n\t\tps.setEscapeProcessing(true);\n\t\t\n\t\treturn( ps );\n\t}\n\n\tpublic String getInsertStatement(String table, Row r) {\n\t\tString column, columns, values;\n\t\tString query = \"insert into \" + table + \" (\"; //$NON-NLS-1$ //$NON-NLS-2$\n\t\tEnumeration keys = r.keys();\n\t\tcolumns = \"\"; //$NON-NLS-1$\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tcolumn = (String) keys.nextElement();\n\t\t\tif (columns.length() > 0)\n\t\t\t\tcolumns += \",\"; //$NON-NLS-1$\n\t\t\tcolumns += column;\n\t\t}\n\t\tquery += columns + \") values (\"; //$NON-NLS-1$\n\t\tvalues = \"\"; //$NON-NLS-1$\n\t\tfor (int i = 0; i < r.getColumnCount(); i++) {\n\t\t\tif (values.length() > 0)\n\t\t\t\tvalues += \",\"; //$NON-NLS-1$\n\t\t\tvalues += \"?\"; //$NON-NLS-1$\n\t\t}\n\t\tquery += values + \")\"; //$NON-NLS-1$\n\t\treturn query;\n\t}\n\n\tpublic void setStatementValues(Row r) throws SQLException {\n\t\tEnumeration keys = r.keys();\n\t\tString column;\n\t\tint i = 1;\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tcolumn = (String) keys.nextElement();\n\t\t\tsetStatementValue(null, i++, r.getObject(column));\n\t\t}\n\t}\n\n\tpublic void setStatementValue(PreparedStatement stmt, int idx, Object value) throws SQLException {\n\t\t// Codigo para parsear aqui...\n\t\tString encoded;\n\t\t// System.out.println(\"Poniendo idx \" + idx + \"=\" + value.toString() );\n\t\tif (value instanceof String) {\n\t\t\t((String) value).replaceAll(\"'\", \"''\"); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t}\n\n\t\t/*\n\t\t * Esto es para evitar petes de nullazos en bases de datos oracle 8i\n\t\t */\n\t\t// if( value == null ) value = new String( \"\" );\n\t\ttry {\n\n\t\t\tstmt.setObject(idx, value);\n\t\t} catch (SQLException e) {\n\t\t\tSystem.err.println(\"excep\" + e.getMessage()); //$NON-NLS-1$\n\t\t\te.printStackTrace();\n\t\t\tthrow e;\n\t\t}\n\n\t}\n\n\tpublic void setStatementValues( Object[] values, PreparedStatement stmt) throws SQLException {\n\t\tfor (int i = 1; i <= values.length; i++) {\n\t\t\t// System.out.println( i-1 + \" -> \" + values[i-1] ); //$NON-NLS-1$\n\t\t\tsetStatementValue(stmt, i, values[i - 1]);\n\t\t}\n\t}\n\n\tpublic void closeStatement(PreparedStatement stmt) throws SQLException {\n\t\tstmt.close();\n\t}\n\n\tpublic int executeUpdate(PreparedStatement stmt) throws SQLException {\n\t\treturn stmt.executeUpdate();\n\t}\n\t\n\tpublic Table getKeys(PreparedStatement stmt) throws SQLException {\n\t\tResultSet rset = stmt.getGeneratedKeys(); \n\t\treturn( getResults( rset ));\n\t}\n\n\tpublic Table executeQuery(PreparedStatement stmt) throws SQLException {\n\t\tTable t;\n\t\tResultSet rset = stmt.executeQuery();\n\t\tt = getResults(rset);\n\t\trset.close();\n\t\treturn (t);\n\t}\n\n\tprivate Table getResults(ResultSet rset) throws SQLException {\n\t\tTable ret = new Table();\n\n\t\tResultSetMetaData rsmeta = rset.getMetaData();\n\n\t\twhile (rset.next()) {\n\t\t\tRow info = new Row();\n\t\t\tfor (int i = 1; i <= rsmeta.getColumnCount(); i++) {\n\t\t\t\tswitch (rsmeta.getColumnType(i)) {\n\t\t\t\tcase Types.FLOAT:\n\t\t\t\tcase Types.DOUBLE:\n\t\t\t\t\tinfo.setFloat(rsmeta.getColumnName(i).toLowerCase(), rset\n\t\t\t\t\t\t\t.getFloat(i));\n\t\t\t\t\tbreak;\n\t\n\t\t\t\tcase Types.INTEGER:\n\t\t\t\tcase Types.NUMERIC:\n\t\t\t\tcase Types.BIGINT:\n\n\t\t\t\t\tinfo.setLong(rsmeta.getColumnName(i).toLowerCase(), rset\n\t\t\t\t\t\t\t.getLong(i));\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase Types.BINARY:\n\t\t\t\tcase Types.VARBINARY:\n\t\t\t\t\tinfo.setBytes(rsmeta.getColumnName(i).toLowerCase(), rset\n\t\t\t\t\t\t\t.getBytes(i));\n\t\t\t\t\tbreak;\n\t\t\t\tcase Types.VARCHAR:\n\t\t\t\tdefault:\n\t\t\t\t\tinfo.set(rsmeta.getColumnName(i).toLowerCase(), rset\n\t\t\t\t\t\t\t.getString(i));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tret.put(info);\n\t\t}\n\t\treturn (ret);\n\t}\n\n\tpublic Table executeQuery(String query) throws SQLException {\n\t\tTable ret;\n\n\t\tStatement stmt = conn.createStatement();\n\t\t// stmt.setEscapeProcessing( true );\n\t\tResultSet rset = stmt.executeQuery(query);\n\t\tret = getResults(rset);\n\t\trset.close();\n\t\tstmt.close();\n\t\treturn (ret);\n\t}\n\n\tpublic int executeUpdate(String query) throws SQLException {\n\t\tint ret = 0;\n\t\tStatement stmt = conn.createStatement();\n\t\tstmt.setEscapeProcessing(true);\n\t\tstmt.executeUpdate(query);\n\t\tResultSet tmp = stmt.getGeneratedKeys();\n\t\tif (tmp.next()) {\n\t\t\t// Retrieve the auto generated key(s).\n\t\t\tret = tmp.getInt(1);\n\t\t}\n\t\tstmt.close();\n\t\treturn ret;\n\t}\n\n\tpublic void commit() throws SQLException {\n\t\tconn.commit();\n\t}\n\n\tpublic void rollback() throws SQLException {\n\t\tconn.rollback();\n\t}\n\n\tpublic void setAutoCommit(boolean value) throws SQLException {\n\t\tconn.setAutoCommit(value);\n\t}\n\n\tpublic void changeIsolation(int value) throws SQLException {\n\t\tconn.setTransactionIsolation(value);\n\t}\n\n\tpublic void restoreIsolation() throws SQLException {\n\t\tconn.setTransactionIsolation(isolationLevel);\n\t}\n\n\t/**\n\t * Permite saber si la conexi�n est� abierta\n\t * \n\t * @return - true si lo esta y false en otro caso.\n\t */\n\tpublic boolean isConnected() {\n\t\ttry {\n\t\t\treturn !conn.isClosed();\n\t\t} catch (SQLException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n}", "public class Table extends AbstractTableModel implements Serializable {\n\tVector table;\n\tprivate int num_cols = 0;\n\n\tpublic static final int SUFFICIENT = 1;\n\tpublic static final int REQUIRED = 2;\n\t/**\n\t * La coincidencia tiene que ser exacta. No vale con un substring\n\t */\n\tpublic static final int REQUIRED_EXACT = 4;\n\tpublic static final int DATE_RANGE = 3;\n\n\t/*\n\t * Nuevo tipo para filtrado: ANY_EXACT, se toman los elementos de la cadena\n\t * a buscar rompiendo por el caracter \",\", si alguno de los identificadores\n\t * coincide exactamente el filtro toma el elemento como v�lido.\n\t */\n\n\tpublic static final int ANY_EXACT = 5;\n\n\t/*\n\t * Coincidencia exacta para valores numericos\n\t */\n\n\tpublic static final int REQUIRED_NUMERICAL = 6;\n\n\t/*\n\t * Coincidencia de condici�n numerica, se debe especificar en una cadena el\n\t * caracter de condici�n, espacio y el n�mero, ejemplos: > 20, < 20, = 20,\n\t * solo funciona con campos tipo float.\n\t */\n\tpublic static final int NUMERICAL_CONDITION = 7;\n\n\t/*\n\t * La cadena debe empezar por el termino de busqueda\n\t */\n\tpublic static final int REQUIRED_BEGINS_WITH = 8;\n\n\tpublic Table() {\n\t\ttable = new Vector();\n\t}\n\n\tpublic void put(Row row) {\n\t\tif (row == null)\n\t\t\treturn;\n\t\ttable.add(row);\n\t\tif (table.size() > 1)\n\t\t\tupdateColumnCount(row);\n\t}\n\n\tpublic void set(int idx, Row row) {\n\t\ttable.set(idx, row);\n\t\tif (table.size() > 1)\n\t\t\tupdateColumnCount(row);\n\t}\n\n\tpublic void put(int idx, Row row) {\n\t\tif (row == null)\n\t\t\treturn;\n\t\ttable.add(idx, row);\n\t\tupdateColumnCount(row);\n\t}\n\n\tpublic Row get(int idx) {\n\t\treturn ((Row) table.elementAt(idx));\n\t}\n\n\tpublic String get(int idx, String key) {\n\t\treturn (get(idx).get(key));\n\t}\n\n\tpublic int getInt(int idx, String key) {\n\t\treturn (get(idx).getInt(key));\n\t}\n\n\tpublic long getLong(int idx, String key) {\n\t\treturn (get(idx).getLong(key));\n\t}\n\n\tpublic Object getObject(int idx, String key) {\n\t\treturn (get(idx).getObject(key));\n\t}\n\n\tpublic float getFloat(int idx, String key) {\n\t\treturn (get(idx).getFloat(key));\n\t}\n\n\tpublic int size() {\n\t\treturn table.size();\n\t}\n\n\tpublic void clear() {\n\t\ttable.clear();\n\t}\n\n\tpublic void copyContents(Table dest) {\n\t\tdest.clear();\n\t\tEnumeration e = table.elements();\n\t\twhile (e.hasMoreElements()) {\n\t\t\tdest.put((Row) e.nextElement());\n\t\t}\n\t}\n\n\tpublic void sort(Comparator c) {\n\t\tCollections.sort(table, c);\n\t}\n\n\tpublic Vector getVector() {\n\t\treturn (table);\n\t}\n\n\tpublic void addAll(Table tbl) {\n\t\tif (tbl == null)\n\t\t\treturn;\n\t\ttable.addAll(tbl.getVector());\n\t}\n\n\tpublic Table filter(String[] fields, String[] strings, int[] types) {\n\t\tTable ret = new Table();\n\t\tboolean doit = false;\n\n\t\tif (fields == null || strings == null || types == null) {\n\t\t\tcopyContents(ret);\n\t\t\treturn (ret);\n\t\t}\n\n\t\tfor (int i = 0; i < strings.length; i++)\n\t\t\tstrings[i] = strings[i].toUpperCase();\n\n\t\tboolean found;\n\t\tboolean haysuf = false;\n\n\t\tfor (int i = 0; i < table.size(); i++) {\n\t\t\tdoit = true;\n\t\t\tfound = false;\n\t\t\tfor (int j = 0; j < fields.length; j++) {\n\t\t\t\tif (types[j] == DATE_RANGE) {\n\t\t\t\t\tif (strings[j].equals(\"\")) //$NON-NLS-1$\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tlong tmp = getLong(i, fields[j]);\n\t\t\t\t\tStringTokenizer tok = new StringTokenizer(strings[j]);\n\t\t\t\t\tlong d1 = Long.parseLong(tok.nextToken());\n\t\t\t\t\tlong d2 = Long.parseLong(tok.nextToken());\n\t\t\t\t\tif (tmp < d1 || tmp > d2) {\n\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (types[j] == NUMERICAL_CONDITION) {\n\t\t\t\t\tif (strings[j].equals(\"\")) //$NON-NLS-1$\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfloat tmp = getFloat(i, fields[j]);\n\t\t\t\t\tStringTokenizer tok = new StringTokenizer(strings[j]);\n\t\t\t\t\tString condicion = tok.nextToken();\n\t\t\t\t\tfloat valor = Float.parseFloat(tok.nextToken());\n\t\t\t\t\tif (condicion.trim().equals(\"\"))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (condicion.equals(\">\")) {\n\t\t\t\t\t\tif (tmp <= valor) {\n\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (condicion.equals(\"<\")) {\n\t\t\t\t\t\tif (tmp >= valor) {\n\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (condicion.equals(\"=\")) {\n\t\t\t\t\t\tif (tmp != valor) {\n\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (types[j] == REQUIRED_NUMERICAL) {\n\t\t\t\t\tif (strings[j].equals(\"\")) //$NON-NLS-1$\n\t\t\t\t\t\t// Cambio octubre de 2006\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tlong value = getLong(i, fields[j]);\n\t\t\t\t\tlong num = Long.parseLong(strings[j]);\n\t\t\t\t\tif (num != value) {\n\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tString tmp = get(i, fields[j]).toUpperCase();\n\n\t\t\t\t\tif (types[j] == REQUIRED) {\n\t\t\t\t\t\tif (tmp.indexOf(strings[j]) == -1) {\n\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (types[j] == REQUIRED_EXACT) {\n\t\t\t\t\t\t// A�adimos la condici�n de que el elemento a comparar\n\t\t\t\t\t\t// no sea vac�o\n\t\t\t\t\t\t// de esa manera cuando el elemento no se ha\n\t\t\t\t\t\t// especificado\n\t\t\t\t\t\t// la comparaci�n devuelve true\n\t\t\t\t\t\tif (!strings[j].equals(\"\") && !tmp.equals(strings[j])) { //$NON-NLS-1$\n\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (types[j] == REQUIRED_BEGINS_WITH) {\n\t\t\t\t\t\t// A�adimos la condici�n de que el elemento a comparar\n\t\t\t\t\t\t// no sea vac�o\n\t\t\t\t\t\t// de esa manera cuando el elemento no se ha\n\t\t\t\t\t\t// especificado\n\t\t\t\t\t\t// la comparaci�n devuelve true\n\t\t\t\t\t\tif (!strings[j].equals(\"\") && !tmp.startsWith(strings[j])) { //$NON-NLS-1$\n\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (types[j] == ANY_EXACT) {\n\t\t\t\t\t\tif (!strings[j].equals(\"\")) { //$NON-NLS-1$\n\t\t\t\t\t\t\tString[] tokens = strings[j].split(\",\"); //$NON-NLS-1$\n\t\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\t\tfor (int k = 0; k < tokens.length; k++) {\n\t\t\t\t\t\t\t\tif (!tokens[k].equals(tmp)) {\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (count == tokens.length)\n\t\t\t\t\t\t\t\tdoit = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (types[j] == SUFFICIENT) {\n\t\t\t\t\t\thaysuf = true;\n\t\t\t\t\t\tif (tmp.indexOf(strings[j]) != -1)\n\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found && haysuf)\n\t\t\t\tdoit = false;\n\t\t\tif (doit)\n\t\t\t\tret.put(get(i));\n\t\t}\n\t\treturn (ret);\n\t}\n\n\tpublic void remove(String field, String value) {\n\t\tfor (int i = 0; i < size(); i++) {\n\t\t\tif (get(i, field).equals(value)) {\n\t\t\t\ttable.remove(i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void remove(int idx) {\n\t\ttable.remove(idx);\n\t}\n\n\tpublic void move(int srcidx, int toidx) {\n\t\tif (srcidx == toidx)\n\t\t\treturn;\n\n\t\ttable.insertElementAt(table.get(srcidx), toidx);\n\n\t\tif (toidx < srcidx)\n\t\t\ttable.remove(srcidx + 1);\n\t\telse\n\t\t\ttable.remove(srcidx);\n\t}\n\n\t// Solo filas de datos, no incluye la cabecera\n\n\tpublic int getRowCount() {\n\t\treturn (table.size());\n\t}\n\n\tpublic int getColumnCount() {\n\t\tif (table.size() > 0) {\n\t\t\tRow tmp = get(0);\n\t\t\treturn (tmp.getColumnCount());\n\t\t} else\n\t\t\treturn (0);\n\t}\n\n\tpublic String getColumnName(int i) {\n\t\treturn get(0).getColumnName(i);\n\t}\n\n\tpublic Object getValueAt(int row, int column) {\n\t\treturn (get(row).get(column));\n\t}\n\n\tpublic int search(String key, String value) {\n\t\tfor (int i = 0; i < size(); i++) {\n\t\t\tif (get(i, key).equals(value))\n\t\t\t\treturn (i);\n\t\t}\n\t\treturn (-1);\n\t}\n\n\tpublic int search(String[] keys, String[] values) {\n\t\tfor (int i = 0; i < size(); i++) {\n\t\t\tboolean found = true;\n\t\t\tfor (int j = 0; j < keys.length; j++) {\n\t\t\t\tif (!get(i, keys[j]).equals(values[j]))\n\t\t\t\t\tfound = false;\n\t\t\t}\n\t\t\tif (found)\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic int search(String[] keys, Object[] values) {\n\t\tfor (int i = 0; i < size(); i++) {\n\t\t\tboolean found = true;\n\t\t\tfor (int j = 0; j < keys.length; j++) {\n\t\t\t\tif (values[j] instanceof Integer)\n\t\t\t\t\tif (getInt(i, keys[j]) != ((Integer) values[j]).intValue())\n\t\t\t\t\t\tfound = false;\n\t\t\t\tif (values[j] instanceof String)\n\t\t\t\t\tif (!get(i, keys[j]).equals(values[j]))\n\t\t\t\t\t\tfound = false;\n\t\t\t}\n\t\t\tif (found)\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic void dump() {\n\t\tfor (int i = 0; i < size(); i++) {\n\t\t\tSystem.out.println(i + \": \");\n\t\t\tget(i).dump();\n\t\t}\n\t}\n\n\t/**\n\t * A�ade a la tabla actual las columnas de otra tabla usando index como\n\t * campo clave.\n\t * \n\t * �nicamente se a�aden las columnas que no existen en la tabla actual.\n\t * \n\t * @param t -\n\t * tabla cuyas columnas se quieren a�adir\n\t * @param index -\n\t * campo clave. Debe ser un objeto comparable\n\t * \n\t */\n\tpublic void merge(Table t, String index) throws IllegalArgumentException {\n\t\t// System.out.println(\"entro en merge. Tengo \" + size() + \" filas y t\n\t\t// tiene \" + t.size() + \" filas\");\n\n\t\tif (t == null || t.size() < 1)\n\t\t\treturn;\n\n\t\t// System.out.println(\"t columns=\" + t.get(0).getHash().toString() );\n\t\tif (!t.get(0).getHash().containsKey(index))\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"la tabla pasada no tiene el campo clave \" + index);\n\n\t\tfor (int i = 0; i < this.table.size(); i++) {\n\t\t\t// System.out.println(\"i=\" + i + \", index=\" + index + \", valor=\" +\n\t\t\t// get(i, index) );\n\t\t\tfor (int j = 0; j < t.size(); j++) {\n\t\t\t\t// System.out.println(\"j=\" + j + \", index=\" + index + \", valor=\"\n\t\t\t\t// + t.get(j, index) );\n\t\t\t\tif (getObject(i, index).equals(t.getObject(j, index))) {\n\t\t\t\t\t// System.out.println(\"coinciden: \" + t.get(j, index) + \"=\"\n\t\t\t\t\t// + get(i, index) );\n\t\t\t\t\tRow r = get(i);\n\t\t\t\t\tr.merge(t.get(j));\n\t\t\t\t\tset(i, r);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * A�ade a la tabla actual las columnas de otra tabla usando como �ndice las\n\t * columnas indicadas\n\t * \n\t * \n\t * �nicamente se a�aden las columnas que no existen en la tabla actual.\n\t * \n\t * @param t -\n\t * tabla cuyas columnas se quieren a�adir\n\t * @param index -\n\t * campos claves. Debe ser un objeto comparable\n\t * \n\t */\n\tpublic void merge(Table t, String[] indexes)\n\t\t\tthrows IllegalArgumentException {\n\t\t// System.out.println(\"entro en merge. Tengo \" + size() + \" filas y t\n\t\t// tiene \" + t.size() + \" filas\");\n\n\t\tif (t == null || t.size() < 1)\n\t\t\treturn;\n\n\t\t// System.out.println(\"t columns=\" + t.get(0).getHash().toString() );\n\t\t// System.out.println(\"self columns=\" + get(0).getHash().toString() );\n\t\tfor (int i = 0; i < indexes.length; i++)\n\t\t\tif (!t.get(0).getHash().containsKey(indexes[i]))\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"la tabla pasada no contiene el campo clave \"\n\t\t\t\t\t\t\t\t+ indexes[i]);\n\n\t\tfor (int i = 0; i < indexes.length; i++)\n\t\t\tif (!get(0).getHash().containsKey(indexes[i]))\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"no tengo el campo clave especificado: \" + indexes[i]);\n\n\t\tfor (int i = 0; i < this.table.size(); i++) {\n\t\t\tfor (int j = 0; j < t.size(); j++) {\n\t\t\t\tboolean coinciden = true;\n\t\t\t\tfor (int h = 0; h < indexes.length; h++) {\n\t\t\t\t\t// System.out.println(\"mirando si \" + getObject(i,\n\t\t\t\t\t// indexes[h]) + \"=\" + t.getObject(j, indexes[h] ) );\n\t\t\t\t\tcoinciden &= getObject(i, indexes[h]).equals(\n\t\t\t\t\t\t\tt.getObject(j, indexes[h]));\n\t\t\t\t}\n\t\t\t\tif (coinciden) {\n\t\t\t\t\tget(i).dump();\n\t\t\t\t\tt.get(j).dump();\n\t\t\t\t\tRow r = get(i);\n\t\t\t\t\tr.merge(t.get(j));\n\t\t\t\t\tset(i, r);\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * DEBUG System.out.println(\"Resultado:\");\n\t\t * \n\t\t * for(int i=0; i < getRowCount(); i++) { for(int j=0; j <\n\t\t * getColumnCount(); j++ ) { System.out.print(\"i=\" + i + \", j=\" + j +\n\t\t * \":\" + get(i).get(j).toString() + \" \" ); } System.out.println(); }\n\t\t */\n\t}\n\n\t/**\n\t * Si se a�ade una nueva fila a la tabla hay que comprobar si eso aumenta el\n\t * n�mero de columnas. En caso afirmativo se tocan todas las filas\n\t * existentes a�adiendo elementos a cero en las nuevas columnas.\n\t * \n\t * \n\t * @param r -\n\t * nueva Row\n\t */\n\tprivate void updateColumnCount(Row r) {\n\t\tif (r.getColumnCount() > num_cols) {\n\t\t\tnum_cols = r.getColumnCount(); // Actualizamos ya el n�mero de\n\t\t\t\t\t\t\t\t\t\t\t// columnas\n\t\t\t// para que al llamar a set no entremos en un bucle largo, doloroso\n\t\t\t// e innecesario\n\n\t\t\tfor (int f = 0; f < getRowCount(); f++) {\n\t\t\t\tRow fila = get(f);\n\n\t\t\t\tif (fila.getColumnCount() == num_cols) {\n\t\t\t\t\tfor (int c = num_cols; c < r.getColumnCount(); c++) {\n\t\t\t\t\t\tObject obj = new String(\"\");\n\t\t\t\t\t\tif (r.getObject(r.getColumnName(c)) instanceof Float)\n\t\t\t\t\t\t\tobj = new Float(0);\n\t\t\t\t\t\tif (r.getObject(r.getColumnName(c)) instanceof Integer)\n\t\t\t\t\t\t\tobj = new Integer(0);\n\t\t\t\t\t\tif (r.getObject(r.getColumnName(c)) instanceof Long)\n\t\t\t\t\t\t\tobj = new Long(0);\n\n\t\t\t\t\t\tfila.setObject(r.getColumnName(c), obj);\n\t\t\t\t\t}\n\t\t\t\t\tset(f, fila);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n}", "public class ChannelInfo {\n\tbyte type;\n\tString name;\n\tPlayerList playerList;\n\tRoomList roomList;\n\tString continent;\n\tint id;\n\t\n\tpublic static byte TYPE_MENU = (byte) 0x1F;\n\tpublic static byte TYPE_PC_CHANNEL = (byte) 0x5F;\n\tpublic static byte TYPE_COMMON_FRIENDLY = (byte) 0x3F; \n\tpublic static byte TYPE_PS2_CHANNEL = (byte) 0X9F;\n\n\tpublic ChannelInfo(byte type, String name, String continentCode ) {\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t\tthis.playerList = new PlayerList();\n\t\tthis.roomList = new RoomList();\n\t\tthis.continent = continentCode;\n\t}\n\n\tpublic void setId( int id ) {\n\t\tthis.id = id;\n\t}\n\t\n\tpublic int getId() {\n\t\treturn( this.id );\n\t}\n\t\n\tpublic String getName() {\n\t\treturn (name);\n\t}\n\n\tpublic byte getType() {\n\t\treturn (type);\n\t}\n\t\n\tpublic PlayerList getPlayerList() {\n\t\treturn( playerList );\n\t}\n\t\n\tpublic RoomList getRoomList() {\n\t\treturn( roomList );\n\t}\n\t\n\tpublic boolean inContinentList( String countryCode ) {\n\t\tif( continent == null ) return true;\n\t\treturn( continent.indexOf( countryCode ) != -1 );\n\t}\n}", "public class DataCdKeyAndPass {\n\tbyte[] data;\n\n\tpublic DataCdKeyAndPass(byte[] data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic byte[] getCdKey() {\n\t\tbyte[] ret = new byte[32];\n\t\tSystem.arraycopy(data, 0, ret, 0, 32);\n\t\treturn (ret);\n\t}\n}", "public class DataCrtPlayer {\n\tbyte[] data;\n\n\tpublic DataCrtPlayer(byte[] data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic int getPos() {\n\t\treturn (data[0]);\n\t}\n\n\tpublic String getName() {\n\n\t\tString name = null;\n\t\ttry {\n\t\t\tname = new String(data, 1, Util.strlen(data, 1), \"UTF-8\");\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn (name);\n\t}\n}", "public class GroupInfo {\n\tlong id;\n\tString name;\n\tString comment;\n\tlong position;\n\tlong points;\n\tint victories;\n\tint defeats;\n\tint draws;\n\tint matches;\n\tint slots;\n\tlong level;\n\tlong leaderId;\n\tint recruiting;\n\tint numPlayers;\n\t\n\n\n\tString recruitComment;\n\tString leaderName;\n\t\n\tPlayerInfo[] players;\n\n\tpublic GroupInfo(long id, String name) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.players = new PlayerInfo[0];\n\t\tthis.comment = \"\";\n\t}\n\n\tpublic void setNumPlayers(int numPlayers) {\n\t\tthis.numPlayers = numPlayers;\n\t}\n\t\n\tpublic int getRecruiting() {\n\t\treturn recruiting;\n\t}\n\n\tpublic void setRecruiting(int recruiting) {\n\t\tthis.recruiting = recruiting;\n\t}\n\n\tpublic String getRecruitComment() {\n\t\treturn recruitComment;\n\t}\n\n\tpublic void setRecruitComment(String recruitComment) {\n\t\tthis.recruitComment = recruitComment;\n\t}\n\n//\tpublic int getNumPlayers() {\n//\t\treturn (players.length );\n//\t}\n\t\n\tpublic int getNumPlayers() {\n\t\treturn( this.numPlayers );\n\t}\n\t\n\tpublic long[] getPlayerIds() {\n\t\tlong[] pids = new long[players.length];\n\t\tfor( int i = 0; i < players.length; i++ ) {\n\t\t\tpids[i] = players[i].getId();\n\t\t}\n\t\treturn( pids );\n\t}\n\n\tpublic void setLeaderId(long pid) {\n\t\tthis.leaderId = pid;\n\t}\n\t\n\tpublic void setLeaderName( String name ) {\n\t\tthis.leaderName = name;\n\t}\n\n\tpublic long getLeaderId( ) {\n\t\treturn( this.leaderId );\n\t}\n\t\n\tpublic String getLeaderName() {\n\t\treturn( this.leaderName );\n\t}\n\n\tpublic void setSlots(int slots) {\n\t\tthis.slots = slots;\n\t}\n\n\tpublic int getSlots() {\n\t\treturn (slots);\n\t}\n\n\tpublic long getPoints() {\n\t\treturn (points);\n\t}\n\n\tpublic void setPoints(long points) {\n\t\tthis.points = points;\n\t}\n\n\tpublic long getPosition() {\n\t\treturn (position);\n\t}\n\n\tpublic void setPosition(long position) {\n\t\tthis.position = position;\n\t}\n\n\tpublic long getId() {\n\t\treturn (id);\n\t}\n\n\tpublic String getName() {\n\t\treturn (name);\n\t}\n\n\tpublic void setPlayers(PlayerInfo[] players) {\n\t\tthis.players = players;\n\t}\n\n\tpublic void addPlayer(PlayerInfo player) {\n\t\tPlayerInfo newPInfo[] = new PlayerInfo[players.length + 1];\n\t\tSystem.arraycopy(players, 0, newPInfo, 0, players.length);\n\t\tnewPInfo[players.length] = player;\n\t\tplayers = newPInfo;\n\t}\n\t\n\tpublic void removePlayer(long pid) {\n\t\tint idx = 0;\n\t\tPlayerInfo newPlayers[] = new PlayerInfo[players.length - 1];\n\t\tfor( int i = 0; i < players.length; i++ ) {\n\t\t\tif( players[i].getId() != pid ) {\n\t\t\t\tnewPlayers[idx++] = players[i];\n\t\t\t}\n\t\t}\n\t\tplayers = newPlayers;\n\t}\n\n\tpublic PlayerInfo[] getPlayers() {\n\t\treturn (players);\n\t}\n\n\tpublic void setComment(String comment) {\n\t\tthis.comment = comment;\n\t}\n\n\tpublic String getComment() {\n\t\treturn (this.comment);\n\t}\n\n\tpublic int getMatches() {\n\t\treturn matches;\n\t}\n\n\tpublic void setMatches(int matches) {\n\t\tthis.matches = matches;\n\t}\n\n\tpublic long getLevel() {\n\t\treturn level;\n\t}\n\n\tpublic void setLevel(long level) {\n\t\tthis.level = level;\n\t}\n\n\tpublic int getDraws() {\n\t\treturn draws;\n\t}\n\n\tpublic void setDraws(int draws) {\n\t\tthis.draws = draws;\n\t}\n\n\tpublic int getDefeats() {\n\t\treturn defeats;\n\t}\n\n\tpublic void setDefeats(int defeats) {\n\t\tthis.defeats = defeats;\n\t}\n\n\tpublic int getVictories() {\n\t\treturn victories;\n\t}\n\n\tpublic void setVictories(int victories) {\n\t\tthis.victories = victories;\n\t}\n}", "public class PlayerInfo {\n\tlong id;\n\t\n\tint category;\n\tlong points;\n\tint matchPoints;\n\tint matchesPlayed;\n\tint victories;\n\tint defeats;\n\tint draws;\n\tint winningStreak;\n\tint bestStreak;\n\tint decos;\n\tint division;\n\tStack<Integer> teams;\n\tlong goalsScored;\n\tlong goalsReceived;\n\tlong timePlayed;\n\tlong lastLogin;\n\tlong position;\n\tint oldCategory;\n\tlong oldPoints;\n\tint lang;\n\tint groupMatches;\n\tint groupLevel;\n\tint invitation;\n\tlong gid;\n\tString groupName;\n\tint serverId;\n\tint lobbyId;\n\tString lobbyName;\n\tint lobbyType;\n\t\n\tString name;\n\tString comment;\n\tbyte[] settings;\n\tboolean logged;\n\tint admin;\n\tIpInfo ip;\n\tPESConnection con;\n\t\n//\tpublic PlayerInfo clone() {\n//\t\tPlayerInfo c = new PlayerInfo( id, name );\n//\t\t\n//\t\tc.category = category;\n//\t\tc.points = points;\n//\t\tc.matchPoints = matchPoints;\n//\t\tc.matchesPlayed = matchesPlayed;\n//\t\tc.victories = victories;\n//\t\tc.defeats = defeats;\n//\t\tc.draws = draws;\n//\t\tc.winningStreak = winningStreak;\n//\t\tc.bestStreak = bestStreak;\n//\t\tc.decos = decos;\n//\t\tc.division = division;\n//\t\tc.teams = teams;\n//\t\tc.goalsScored = goalsScored;\n//\t\tc.goalsReceived = goalsReceived;\n//\t\tc.timePlayed = timePlayed;\n//\t\tc.lastLogin = lastLogin;\n//\t\tc.position = position;\n//\t\tc.oldCategory = oldCategory;\n//\t\tc.oldPoints = oldPoints;\n//\t\tc.lang = lang;\n//\t\tc.groupMatches = groupMatches;\n//\t\tc.invitation = invitation;\n//\t\tc.gid = gid;\n//\t\tc.groupName = groupName;\n//\t\tc.serverId = serverId;\n//\t\tc.lobbyId = lobbyId;\n//\t\tc.lobbyName = lobbyName;\n//\t\tc.lobbyType = lobbyType;\n//\t\tc.comment = comment;\n//\n//\t\tc.settings = settings;\n//\t\t//byte[] settings;\n//\t\tc.logged = logged;\n//\t\tc.admin = admin;\n//\t\tc.ip = ip;\n//\t\tc.con = con;\n//\t\t//IpInfo ip;\n//\t\t//PESConnection con;\n//\t\t\n//\t\treturn( c );\n//\t}\n\t\n\tpublic PlayerInfo(long id, String name) {\n\t\tthis.name = name;\n\t\tthis.category = 500;\n\t\tthis.oldCategory = 500;\n\t\tthis.points = 0;\n\t\tthis.oldPoints = 0;\n\t\tthis.matchesPlayed = 0;\n\t\tthis.lang = 0;\n\t\t\n\t\tvictories = 0;\n\t\tdefeats = 0;\n\t\tdraws = 0;\n\t\twinningStreak = 0;\n\t\tbestStreak = 0;\n\t\tdecos = 0;\n\t\tgoalsScored = 0;\n\t\tgoalsReceived = 0;\n\t\ttimePlayed = 0;\n\t\tdivision = 2;\n\t\tinvitation = 0;\n\t\tgid = 0;\n\t\t\n\t\tlastLogin = (new Date()).getTime();\n\t\t\n\t\tteams = new Stack<Integer>();\n\t\t\n\t\tthis.id = id;\n\t\tthis.logged = false;\n\t\tthis.comment = \"\";\n\t\tthis.admin = 0;\n\t\t\n\t\ttry {\n\t\t\tFileInputStream fi = new FileInputStream(\"mis_messages.dec\");\n\t\t\tbyte[] defSettings = new byte[(int) new File(\"mis_messages.dec\")\n\t\t\t\t\t.length()];\n\t\t\tfi.read(defSettings);\n\t\t\tfi.close();\n\t\t\tMessage mes = new Message(defSettings);\n\t\t\tMessageBlockLoginMessagesList mb = new MessageBlockLoginMessagesList(\n\t\t\t\t\tmes);\n\t\t\tthis.settings = mb.getData();\n\t\t} catch (IOException ex) {\n\t\t}\n\t}\n\t\n\tpublic long getGid() {\n\t\treturn gid;\n\t}\n\n\tpublic int getGroupLevel() {\n\t\treturn groupLevel;\n\t}\n\n\tpublic void setGroupLevel(int groupLevel) {\n\t\tthis.groupLevel = groupLevel;\n\t}\n\n\tpublic int getLobbyType() {\n\t\treturn lobbyType;\n\t}\n\n\tpublic void setLobbyType(int lobbyType) {\n\t\tthis.lobbyType = lobbyType;\n\t}\n\n\tpublic int getLobbyId() {\n\t\treturn lobbyId;\n\t}\n\n\tpublic void setLobbyId(int lobbyId) {\n\t\tthis.lobbyId = lobbyId;\n\t}\n\n\tpublic String getLobbyName() {\n\t\treturn lobbyName;\n\t}\n\n\tpublic void setLobbyName(String lobbyName) {\n\t\tthis.lobbyName = lobbyName;\n\t}\n\n\tpublic int getServerId() {\n\t\treturn serverId;\n\t}\n\n\tpublic void setServerId(int serverId) {\n\t\tthis.serverId = serverId;\n\t}\n\n\tpublic void setGid(long gid) {\n\t\tthis.gid = gid;\n\t}\n\t\n\tpublic int getGroupMatches() {\n\t\treturn groupMatches;\n\t}\n\n\tpublic void setGroupMatches(int groupMatches) {\n\t\tthis.groupMatches = groupMatches;\n\t}\n\n\tpublic int getInvitation() {\n\t\treturn invitation;\n\t}\n\n\tpublic String getGroupName() {\n\t\treturn groupName;\n\t}\n\n\tpublic void setGroupName(String groupName) {\n\t\tthis.groupName = groupName;\n\t}\n\n\tpublic void setInvitation(int invitation) {\n\t\tthis.invitation = invitation;\n\t}\n\n\tpublic void setLang( int lang ) {\n\t\tthis.lang = lang;\n\t}\n\t\n\tpublic int getLang( ) {\n\t\treturn( lang );\n\t}\n\t\n\tpublic void setConnection( PESConnection con ) {\n\t\tthis.con = con;\n\t}\n\t\n\tpublic PESConnection getConnection( ) {\n\t\treturn( this.con );\n\t}\n\t\n\tpublic void setIpInfo( IpInfo ipInfo ) {\n\t\tip = ipInfo;\n\t}\n\t\n\tpublic IpInfo getIpInfo( ) {\n\t\treturn( ip );\n\t}\n\n\tpublic synchronized void setAdmin( int value ) {\n\t\tadmin = value;\n\t}\n\t\n\tpublic synchronized int getAdmin( ) {\n\t\treturn( admin );\n\t}\n\t\n\tpublic synchronized boolean isAdmin() {\n\t\treturn( admin == 1 ? true : false );\n\t}\n\t\n\tpublic synchronized void setLoggedIn() {\n\t\tthis.logged = true;\n\t}\n\n\tpublic synchronized void setComment(String comment) {\n\t\tthis.comment = comment;\n\t}\n\n\tpublic synchronized String getComment() {\n\t\treturn (this.comment);\n\t}\n\n\tpublic synchronized boolean isLoggedIn() {\n\t\treturn (this.logged);\n\t}\n\n\tpublic synchronized void setSettings(byte[] data) {\n\t\tif (data != null && data.length > 0)\n\t\t\tthis.settings = data;\n\t}\n\t\n\tpublic synchronized void resetSettings( ) {\n\t\tthis.settings = new byte[0];\n\t}\n\t\n\tpublic synchronized void insertSettings( byte[] data ) {\n\t\tbyte[] newSettings = new byte[this.settings.length + data.length];\n\t\tSystem.arraycopy( this.settings, 0, newSettings, 0, this.settings.length);\n\t\tSystem.arraycopy( data, 0, newSettings, this.settings.length, data.length);\n\t\tthis.settings = newSettings;\n\t}\n\n\tpublic synchronized byte[] getSettings() {\n\t\treturn (this.settings);\n\t}\n\n\tpublic synchronized long getId() {\n\t\treturn (id);\n\t}\n\n\tpublic synchronized String getName() {\n\t\treturn (name);\n\t}\n\n\tpublic int getMatchesPlayed() {\n\t\treturn matchesPlayed;\n\t}\n\n\tpublic void setMatchesPlayed(int matchesPlayed) {\n\t\tthis.matchesPlayed = matchesPlayed;\n\t}\n\n\tpublic long getPoints() {\n\t\treturn points;\n\t}\n\n\tpublic void setPoints(long points) {\n\t\tthis.points = points;\n\t}\n\n\tpublic int getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(int category) {\n\t\tif( category < 0 ) this.category = 0;\n\t\telse this.category = category;\n\t}\n\n\tpublic int getVictories() {\n\t\treturn victories;\n\t}\n\n\tpublic void setVictories(int victories) {\n\t\tthis.victories = victories;\n\t}\n\n\tpublic int getDefeats() {\n\t\treturn defeats;\n\t}\n\n\tpublic void setDefeats(int defeats) {\n\t\tthis.defeats = defeats;\n\t}\n\n\tpublic int getDraws() {\n\t\treturn draws;\n\t}\n\n\tpublic void setDraws(int draws) {\n\t\tthis.draws = draws;\n\t}\n\n\tpublic int getWinningStreak() {\n\t\treturn winningStreak;\n\t}\n\n\tpublic void setWinningStreak(int winningStreak) {\n\t\tthis.winningStreak = winningStreak;\n\t}\n\n\tpublic int getBestStreak() {\n\t\treturn bestStreak;\n\t}\n\n\tpublic void setBestStreak(int bestStreak) {\n\t\tthis.bestStreak = bestStreak;\n\t}\n\n\tpublic int getDecos() {\n\t\treturn decos;\n\t}\n\n\tpublic void setDecos(int decos) {\n\t\tthis.decos = decos;\n\t}\n\n\tpublic long getGoalsScored() {\n\t\treturn goalsScored;\n\t}\n\n\tpublic void setGoalsScored(long goalsScored) {\n\t\tthis.goalsScored = goalsScored;\n\t}\n\n\tpublic long getGoalsReceived() {\n\t\treturn goalsReceived;\n\t}\n\n\tpublic void setGoalsReceived(long goalsReceived) {\n\t\tthis.goalsReceived = goalsReceived;\n\t}\n\n\tpublic long getTimePlayed() {\n\t\treturn timePlayed;\n\t}\n\n\tpublic void setTimePlayed(long timePlayed) {\n\t\tthis.timePlayed = timePlayed;\n\t}\n\n\tpublic int getDivision() {\n\t\treturn division;\n\t}\n\n\tpublic void setDivision(int division) {\n\t\tthis.division = division;\n\t}\n\n\tpublic int getTeam1() {\n\t\tif( teams.size() > 0 ) return( teams.get(0).intValue() );\n\t\telse return 0xFFFF;\n\t}\n\n\tpublic int getTeam2() {\n\t\tif( teams.size() > 1 ) return( teams.get(1).intValue() );\n\t\telse return 0xFFFF;\n\t}\n\n\tpublic int getTeam3() {\n\t\tif( teams.size() > 2 ) return( teams.get(2).intValue() );\n\t\telse return 0xFFFF;\n\t}\n\n\tpublic int getTeam4() {\n\t\tif( teams.size() > 3 ) return( teams.get(3).intValue() );\n\t\telse return 0xFFFF;\n\t}\n\n\tpublic int getTeam5() {\n\t\tif( teams.size() > 4 ) return( teams.get(4).intValue() );\n\t\telse return 0xFFFF;\n\t}\n\n\tpublic void pushTeam( int team ) {\n\t\tif( teams.size() >= 5 )\n\t\t\tteams.remove(0);\n\t\t\n\t\tteams.push(new Integer( team ));\n\t}\n\t\n\tpublic long getLastLogin() {\n\t\treturn lastLogin;\n\t}\n\n\tpublic void setLastLogin(long lastLogin) {\n\t\tthis.lastLogin = lastLogin;\n\t}\n\n\tpublic long getPosition() {\n\t\treturn position;\n\t}\n\n\tpublic void setPosition(long position) {\n\t\tthis.position = position;\n\t}\n\n\tpublic int getOldCategory() {\n\t\treturn oldCategory;\n\t}\n\n\tpublic void setOldCategory(int oldCategory) {\n\t\tif( oldCategory < 0 ) this.oldCategory = 0;\n\t\telse this.oldCategory = oldCategory;\n\t}\n\n\tpublic int getMatchPoints() {\n\t\treturn matchPoints;\n\t}\n\n\tpublic void setMatchPoints(int matchPoints) {\n\t\tthis.matchPoints = matchPoints;\n\t}\n\n\tpublic long getOldPoints() {\n\t\treturn oldPoints;\n\t}\n\n\tpublic void setOldPoints(long oldPoints) {\n\t\tthis.oldPoints = oldPoints;\n\t}\n}", "public class ServerInfo {\n\tint type;\n\tint id;\n\tString name;\n\tString ip;\n\tint port;\n\tint wport;\n\tint numPlayers;\n\n\tpublic ServerInfo(int id, int type, String name, String ip, int port ) {\n\t\tthis.type = type;\n\t\tthis.name = name;\n\t\tthis.ip = ip;\n\t\tthis.port = port;\n\t\tthis.id = id;\n\t\tthis.numPlayers = 0;\n\t\tthis.wport = 0;\n\t}\n\n\tpublic int getWPort() {\n\t\treturn( this.wport );\n\t}\n\t\n\tpublic void setWPort( int wport ) {\n\t\tthis.wport = wport;\n\t}\n\t\n\tpublic int getId() {\n\t\treturn( id );\n\t}\n\t\n\tpublic int getType() {\n\t\treturn (type);\n\t}\n\n\tpublic String getName() {\n\t\treturn (name);\n\t}\n\n\tpublic String getIp() {\n\t\treturn (ip);\n\t}\n\n\tpublic int getPort() {\n\t\treturn (port);\n\t}\n\t\n\tpublic int getNumPlayers() {\n\t\treturn (numPlayers);\n\t}\n\t\n\tpublic void setNumPlayers(int numPlayers) {\n\t\tthis.numPlayers = numPlayers;\n\t}\n}", "public class UserInfo {\n\tString username;\n\tint access;\n\t\n\tpublic UserInfo( String username, int access ) {\n\t\tthis.username = username;\n\t\tthis.access = access;\n\t}\n\t\n\tpublic String getUsername() {\n\t\treturn( username );\n\t}\n\t\n\tpublic int getAccess() {\n\t\treturn( access );\n\t}\n\t\n\tpublic void setUsername( String username ) {\n\t\tthis.username = username;\n\t}\n\t\n\tpublic void setAccess( int access ) {\n\t\tthis.access = access;\n\t}\n}" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import pes6j.database.Db; import pes6j.database.Table; import pes6j.datablocks.ChannelInfo; import pes6j.datablocks.DataCdKeyAndPass; import pes6j.datablocks.DataCrtPlayer; import pes6j.datablocks.GroupInfo; import pes6j.datablocks.PlayerInfo; import pes6j.datablocks.ServerInfo; import pes6j.datablocks.UserInfo;
package pes6j.servers; public class Tools { public static long dbCreatePlayer(Db db, String username, DataCrtPlayer player, byte[] default_settings ) throws SQLException { long pid = 0; PreparedStatement ps; try { //db.setAutoCommit(false); String query = "insert into players (name,settings) values (?,?) returning pid"; ps = db.prepareStatement(query); db.setStatementValues(new Object[] { player.getName(), default_settings }, ps);
Table t = db.executeQuery(ps);
1
googleapis/java-analytics-data
samples/snippets/src/main/java/com/example/analytics/QuickstartSample.java
[ "@BetaApi\n@Generated(\"by gapic-generator-java\")\npublic class BetaAnalyticsDataClient implements BackgroundResource {\n private final BetaAnalyticsDataSettings settings;\n private final BetaAnalyticsDataStub stub;\n\n /** Constructs an instance of BetaAnalyticsDataClient with default settings. */\n public static final BetaAnalyticsDataClient create() throws IOException {\n return create(BetaAnalyticsDataSettings.newBuilder().build());\n }\n\n /**\n * Constructs an instance of BetaAnalyticsDataClient, using the given settings. The channels are\n * created based on the settings passed in, or defaults for any settings that are not set.\n */\n public static final BetaAnalyticsDataClient create(BetaAnalyticsDataSettings settings)\n throws IOException {\n return new BetaAnalyticsDataClient(settings);\n }\n\n /**\n * Constructs an instance of BetaAnalyticsDataClient, using the given stub for making calls. This\n * is for advanced usage - prefer using create(BetaAnalyticsDataSettings).\n */\n @BetaApi(\"A restructuring of stub classes is planned, so this may break in the future\")\n public static final BetaAnalyticsDataClient create(BetaAnalyticsDataStub stub) {\n return new BetaAnalyticsDataClient(stub);\n }\n\n /**\n * Constructs an instance of BetaAnalyticsDataClient, using the given settings. This is protected\n * so that it is easy to make a subclass, but otherwise, the static factory methods should be\n * preferred.\n */\n protected BetaAnalyticsDataClient(BetaAnalyticsDataSettings settings) throws IOException {\n this.settings = settings;\n this.stub = ((BetaAnalyticsDataStubSettings) settings.getStubSettings()).createStub();\n }\n\n @BetaApi(\"A restructuring of stub classes is planned, so this may break in the future\")\n protected BetaAnalyticsDataClient(BetaAnalyticsDataStub stub) {\n this.settings = null;\n this.stub = stub;\n }\n\n public final BetaAnalyticsDataSettings getSettings() {\n return settings;\n }\n\n @BetaApi(\"A restructuring of stub classes is planned, so this may break in the future\")\n public BetaAnalyticsDataStub getStub() {\n return stub;\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns a customized report of your Google Analytics event data. Reports contain statistics\n * derived from data collected by the Google Analytics tracking code. The data returned from the\n * API is as a table with columns for the requested dimensions and metrics. Metrics are individual\n * measurements of user activity on your property, such as active users or event count. Dimensions\n * break down metrics across some common criteria, such as country or event name.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * RunReportRequest request =\n * RunReportRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .addAllDateRanges(new ArrayList<DateRange>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setOffset(-1019779949)\n * .setLimit(102976443)\n * .addAllMetricAggregations(new ArrayList<MetricAggregation>())\n * .addAllOrderBys(new ArrayList<OrderBy>())\n * .setCurrencyCode(\"currencyCode1004773790\")\n * .setCohortSpec(CohortSpec.newBuilder().build())\n * .setKeepEmptyRows(true)\n * .setReturnPropertyQuota(true)\n * .build();\n * RunReportResponse response = betaAnalyticsDataClient.runReport(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final RunReportResponse runReport(RunReportRequest request) {\n return runReportCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns a customized report of your Google Analytics event data. Reports contain statistics\n * derived from data collected by the Google Analytics tracking code. The data returned from the\n * API is as a table with columns for the requested dimensions and metrics. Metrics are individual\n * measurements of user activity on your property, such as active users or event count. Dimensions\n * break down metrics across some common criteria, such as country or event name.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * RunReportRequest request =\n * RunReportRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .addAllDateRanges(new ArrayList<DateRange>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setOffset(-1019779949)\n * .setLimit(102976443)\n * .addAllMetricAggregations(new ArrayList<MetricAggregation>())\n * .addAllOrderBys(new ArrayList<OrderBy>())\n * .setCurrencyCode(\"currencyCode1004773790\")\n * .setCohortSpec(CohortSpec.newBuilder().build())\n * .setKeepEmptyRows(true)\n * .setReturnPropertyQuota(true)\n * .build();\n * ApiFuture<RunReportResponse> future =\n * betaAnalyticsDataClient.runReportCallable().futureCall(request);\n * // Do something.\n * RunReportResponse response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<RunReportRequest, RunReportResponse> runReportCallable() {\n return stub.runReportCallable();\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns a customized pivot report of your Google Analytics event data. Pivot reports are more\n * advanced and expressive formats than regular reports. In a pivot report, dimensions are only\n * visible if they are included in a pivot. Multiple pivots can be specified to further dissect\n * your data.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * RunPivotReportRequest request =\n * RunPivotReportRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .addAllDateRanges(new ArrayList<DateRange>())\n * .addAllPivots(new ArrayList<Pivot>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setCurrencyCode(\"currencyCode1004773790\")\n * .setCohortSpec(CohortSpec.newBuilder().build())\n * .setKeepEmptyRows(true)\n * .setReturnPropertyQuota(true)\n * .build();\n * RunPivotReportResponse response = betaAnalyticsDataClient.runPivotReport(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final RunPivotReportResponse runPivotReport(RunPivotReportRequest request) {\n return runPivotReportCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns a customized pivot report of your Google Analytics event data. Pivot reports are more\n * advanced and expressive formats than regular reports. In a pivot report, dimensions are only\n * visible if they are included in a pivot. Multiple pivots can be specified to further dissect\n * your data.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * RunPivotReportRequest request =\n * RunPivotReportRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .addAllDateRanges(new ArrayList<DateRange>())\n * .addAllPivots(new ArrayList<Pivot>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setCurrencyCode(\"currencyCode1004773790\")\n * .setCohortSpec(CohortSpec.newBuilder().build())\n * .setKeepEmptyRows(true)\n * .setReturnPropertyQuota(true)\n * .build();\n * ApiFuture<RunPivotReportResponse> future =\n * betaAnalyticsDataClient.runPivotReportCallable().futureCall(request);\n * // Do something.\n * RunPivotReportResponse response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<RunPivotReportRequest, RunPivotReportResponse>\n runPivotReportCallable() {\n return stub.runPivotReportCallable();\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns multiple reports in a batch. All reports must be for the same GA4 Property.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * BatchRunReportsRequest request =\n * BatchRunReportsRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllRequests(new ArrayList<RunReportRequest>())\n * .build();\n * BatchRunReportsResponse response = betaAnalyticsDataClient.batchRunReports(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final BatchRunReportsResponse batchRunReports(BatchRunReportsRequest request) {\n return batchRunReportsCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns multiple reports in a batch. All reports must be for the same GA4 Property.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * BatchRunReportsRequest request =\n * BatchRunReportsRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllRequests(new ArrayList<RunReportRequest>())\n * .build();\n * ApiFuture<BatchRunReportsResponse> future =\n * betaAnalyticsDataClient.batchRunReportsCallable().futureCall(request);\n * // Do something.\n * BatchRunReportsResponse response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<BatchRunReportsRequest, BatchRunReportsResponse>\n batchRunReportsCallable() {\n return stub.batchRunReportsCallable();\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns multiple pivot reports in a batch. All reports must be for the same GA4 Property.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * BatchRunPivotReportsRequest request =\n * BatchRunPivotReportsRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllRequests(new ArrayList<RunPivotReportRequest>())\n * .build();\n * BatchRunPivotReportsResponse response = betaAnalyticsDataClient.batchRunPivotReports(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final BatchRunPivotReportsResponse batchRunPivotReports(\n BatchRunPivotReportsRequest request) {\n return batchRunPivotReportsCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns multiple pivot reports in a batch. All reports must be for the same GA4 Property.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * BatchRunPivotReportsRequest request =\n * BatchRunPivotReportsRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllRequests(new ArrayList<RunPivotReportRequest>())\n * .build();\n * ApiFuture<BatchRunPivotReportsResponse> future =\n * betaAnalyticsDataClient.batchRunPivotReportsCallable().futureCall(request);\n * // Do something.\n * BatchRunPivotReportsResponse response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<BatchRunPivotReportsRequest, BatchRunPivotReportsResponse>\n batchRunPivotReportsCallable() {\n return stub.batchRunPivotReportsCallable();\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns metadata for dimensions and metrics available in reporting methods. Used to explore the\n * dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified\n * in the request, and the metadata response includes Custom dimensions and metrics as well as\n * Universal metadata.\n *\n * <p>For example if a custom metric with parameter name `levels_unlocked` is registered to a\n * property, the Metadata response will contain `customEvent:levels_unlocked`. Universal metadata\n * are dimensions and metrics applicable to any property such as `country` and `totalUsers`.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * MetadataName name = MetadataName.of(\"[PROPERTY]\");\n * Metadata response = betaAnalyticsDataClient.getMetadata(name);\n * }\n * }</pre>\n *\n * @param name Required. The resource name of the metadata to retrieve. This name field is\n * specified in the URL path and not URL parameters. Property is a numeric Google Analytics\n * GA4 Property identifier. To learn more, see [where to find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * <p>Example: properties/1234/metadata\n * <p>Set the Property ID to 0 for dimensions and metrics common to all properties. In this\n * special mode, this method will not return custom dimensions and metrics.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final Metadata getMetadata(MetadataName name) {\n GetMetadataRequest request =\n GetMetadataRequest.newBuilder().setName(name == null ? null : name.toString()).build();\n return getMetadata(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns metadata for dimensions and metrics available in reporting methods. Used to explore the\n * dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified\n * in the request, and the metadata response includes Custom dimensions and metrics as well as\n * Universal metadata.\n *\n * <p>For example if a custom metric with parameter name `levels_unlocked` is registered to a\n * property, the Metadata response will contain `customEvent:levels_unlocked`. Universal metadata\n * are dimensions and metrics applicable to any property such as `country` and `totalUsers`.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * String name = MetadataName.of(\"[PROPERTY]\").toString();\n * Metadata response = betaAnalyticsDataClient.getMetadata(name);\n * }\n * }</pre>\n *\n * @param name Required. The resource name of the metadata to retrieve. This name field is\n * specified in the URL path and not URL parameters. Property is a numeric Google Analytics\n * GA4 Property identifier. To learn more, see [where to find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * <p>Example: properties/1234/metadata\n * <p>Set the Property ID to 0 for dimensions and metrics common to all properties. In this\n * special mode, this method will not return custom dimensions and metrics.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final Metadata getMetadata(String name) {\n GetMetadataRequest request = GetMetadataRequest.newBuilder().setName(name).build();\n return getMetadata(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns metadata for dimensions and metrics available in reporting methods. Used to explore the\n * dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified\n * in the request, and the metadata response includes Custom dimensions and metrics as well as\n * Universal metadata.\n *\n * <p>For example if a custom metric with parameter name `levels_unlocked` is registered to a\n * property, the Metadata response will contain `customEvent:levels_unlocked`. Universal metadata\n * are dimensions and metrics applicable to any property such as `country` and `totalUsers`.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * GetMetadataRequest request =\n * GetMetadataRequest.newBuilder().setName(MetadataName.of(\"[PROPERTY]\").toString()).build();\n * Metadata response = betaAnalyticsDataClient.getMetadata(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final Metadata getMetadata(GetMetadataRequest request) {\n return getMetadataCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * Returns metadata for dimensions and metrics available in reporting methods. Used to explore the\n * dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified\n * in the request, and the metadata response includes Custom dimensions and metrics as well as\n * Universal metadata.\n *\n * <p>For example if a custom metric with parameter name `levels_unlocked` is registered to a\n * property, the Metadata response will contain `customEvent:levels_unlocked`. Universal metadata\n * are dimensions and metrics applicable to any property such as `country` and `totalUsers`.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * GetMetadataRequest request =\n * GetMetadataRequest.newBuilder().setName(MetadataName.of(\"[PROPERTY]\").toString()).build();\n * ApiFuture<Metadata> future =\n * betaAnalyticsDataClient.getMetadataCallable().futureCall(request);\n * // Do something.\n * Metadata response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<GetMetadataRequest, Metadata> getMetadataCallable() {\n return stub.getMetadataCallable();\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * The Google Analytics Realtime API returns a customized report of realtime event data for your\n * property. These reports show events and usage from the last 30 minutes.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * RunRealtimeReportRequest request =\n * RunRealtimeReportRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setLimit(102976443)\n * .addAllMetricAggregations(new ArrayList<MetricAggregation>())\n * .addAllOrderBys(new ArrayList<OrderBy>())\n * .setReturnPropertyQuota(true)\n * .addAllMinuteRanges(new ArrayList<MinuteRange>())\n * .build();\n * RunRealtimeReportResponse response = betaAnalyticsDataClient.runRealtimeReport(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final RunRealtimeReportResponse runRealtimeReport(RunRealtimeReportRequest request) {\n return runRealtimeReportCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * The Google Analytics Realtime API returns a customized report of realtime event data for your\n * property. These reports show events and usage from the last 30 minutes.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * RunRealtimeReportRequest request =\n * RunRealtimeReportRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setLimit(102976443)\n * .addAllMetricAggregations(new ArrayList<MetricAggregation>())\n * .addAllOrderBys(new ArrayList<OrderBy>())\n * .setReturnPropertyQuota(true)\n * .addAllMinuteRanges(new ArrayList<MinuteRange>())\n * .build();\n * ApiFuture<RunRealtimeReportResponse> future =\n * betaAnalyticsDataClient.runRealtimeReportCallable().futureCall(request);\n * // Do something.\n * RunRealtimeReportResponse response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<RunRealtimeReportRequest, RunRealtimeReportResponse>\n runRealtimeReportCallable() {\n return stub.runRealtimeReportCallable();\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * This compatibility method lists dimensions and metrics that can be added to a report request\n * and maintain compatibility. This method fails if the request's dimensions and metrics are\n * incompatible.\n *\n * <p>In Google Analytics, reports fail if they request incompatible dimensions and/or metrics; in\n * that case, you will need to remove dimensions and/or metrics from the incompatible report until\n * the report is compatible.\n *\n * <p>The Realtime and Core reports have different compatibility rules. This method checks\n * compatibility for Core reports.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * CheckCompatibilityRequest request =\n * CheckCompatibilityRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setCompatibilityFilter(Compatibility.forNumber(0))\n * .build();\n * CheckCompatibilityResponse response = betaAnalyticsDataClient.checkCompatibility(request);\n * }\n * }</pre>\n *\n * @param request The request object containing all of the parameters for the API call.\n * @throws com.google.api.gax.rpc.ApiException if the remote call fails\n */\n public final CheckCompatibilityResponse checkCompatibility(CheckCompatibilityRequest request) {\n return checkCompatibilityCallable().call(request);\n }\n\n // AUTO-GENERATED DOCUMENTATION AND METHOD.\n /**\n * This compatibility method lists dimensions and metrics that can be added to a report request\n * and maintain compatibility. This method fails if the request's dimensions and metrics are\n * incompatible.\n *\n * <p>In Google Analytics, reports fail if they request incompatible dimensions and/or metrics; in\n * that case, you will need to remove dimensions and/or metrics from the incompatible report until\n * the report is compatible.\n *\n * <p>The Realtime and Core reports have different compatibility rules. This method checks\n * compatibility for Core reports.\n *\n * <p>Sample code:\n *\n * <pre>{@code\n * try (BetaAnalyticsDataClient betaAnalyticsDataClient = BetaAnalyticsDataClient.create()) {\n * CheckCompatibilityRequest request =\n * CheckCompatibilityRequest.newBuilder()\n * .setProperty(\"property-993141291\")\n * .addAllDimensions(new ArrayList<Dimension>())\n * .addAllMetrics(new ArrayList<Metric>())\n * .setDimensionFilter(FilterExpression.newBuilder().build())\n * .setMetricFilter(FilterExpression.newBuilder().build())\n * .setCompatibilityFilter(Compatibility.forNumber(0))\n * .build();\n * ApiFuture<CheckCompatibilityResponse> future =\n * betaAnalyticsDataClient.checkCompatibilityCallable().futureCall(request);\n * // Do something.\n * CheckCompatibilityResponse response = future.get();\n * }\n * }</pre>\n */\n public final UnaryCallable<CheckCompatibilityRequest, CheckCompatibilityResponse>\n checkCompatibilityCallable() {\n return stub.checkCompatibilityCallable();\n }\n\n @Override\n public final void close() {\n stub.close();\n }\n\n @Override\n public void shutdown() {\n stub.shutdown();\n }\n\n @Override\n public boolean isShutdown() {\n return stub.isShutdown();\n }\n\n @Override\n public boolean isTerminated() {\n return stub.isTerminated();\n }\n\n @Override\n public void shutdownNow() {\n stub.shutdownNow();\n }\n\n @Override\n public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {\n return stub.awaitTermination(duration, unit);\n }\n}", "public final class DateRange extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.DateRange)\n DateRangeOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use DateRange.newBuilder() to construct.\n private DateRange(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {\n super(builder);\n }\n\n private DateRange() {\n startDate_ = \"\";\n endDate_ = \"\";\n name_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new DateRange();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private DateRange(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n startDate_ = s;\n break;\n }\n case 18:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n endDate_ = s;\n break;\n }\n case 26:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n name_ = s;\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_DateRange_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_DateRange_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.DateRange.class,\n com.google.analytics.data.v1beta.DateRange.Builder.class);\n }\n\n public static final int START_DATE_FIELD_NUMBER = 1;\n private volatile java.lang.Object startDate_;\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @return The startDate.\n */\n @java.lang.Override\n public java.lang.String getStartDate() {\n java.lang.Object ref = startDate_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n startDate_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @return The bytes for startDate.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getStartDateBytes() {\n java.lang.Object ref = startDate_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n startDate_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int END_DATE_FIELD_NUMBER = 2;\n private volatile java.lang.Object endDate_;\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @return The endDate.\n */\n @java.lang.Override\n public java.lang.String getEndDate() {\n java.lang.Object ref = endDate_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n endDate_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @return The bytes for endDate.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getEndDateBytes() {\n java.lang.Object ref = endDate_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n endDate_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int NAME_FIELD_NUMBER = 3;\n private volatile java.lang.Object name_;\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @return The name.\n */\n @java.lang.Override\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @return The bytes for name.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(startDate_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, startDate_);\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(endDate_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 2, endDate_);\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 3, name_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(startDate_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, startDate_);\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(endDate_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, endDate_);\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, name_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.analytics.data.v1beta.DateRange)) {\n return super.equals(obj);\n }\n com.google.analytics.data.v1beta.DateRange other =\n (com.google.analytics.data.v1beta.DateRange) obj;\n\n if (!getStartDate().equals(other.getStartDate())) return false;\n if (!getEndDate().equals(other.getEndDate())) return false;\n if (!getName().equals(other.getName())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n hash = (37 * hash) + START_DATE_FIELD_NUMBER;\n hash = (53 * hash) + getStartDate().hashCode();\n hash = (37 * hash) + END_DATE_FIELD_NUMBER;\n hash = (53 * hash) + getEndDate().hashCode();\n hash = (37 * hash) + NAME_FIELD_NUMBER;\n hash = (53 * hash) + getName().hashCode();\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(java.nio.ByteBuffer data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.DateRange parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(com.google.analytics.data.v1beta.DateRange prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n * <pre>\n * A contiguous set of days: startDate, startDate + 1, ..., endDate. Requests\n * are allowed up to 4 date ranges.\n * </pre>\n *\n * Protobuf type {@code google.analytics.data.v1beta.DateRange}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>\n implements\n // @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.DateRange)\n com.google.analytics.data.v1beta.DateRangeOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_DateRange_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_DateRange_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.DateRange.class,\n com.google.analytics.data.v1beta.DateRange.Builder.class);\n }\n\n // Construct using com.google.analytics.data.v1beta.DateRange.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n startDate_ = \"\";\n\n endDate_ = \"\";\n\n name_ = \"\";\n\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_DateRange_descriptor;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.DateRange getDefaultInstanceForType() {\n return com.google.analytics.data.v1beta.DateRange.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.DateRange build() {\n com.google.analytics.data.v1beta.DateRange result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.DateRange buildPartial() {\n com.google.analytics.data.v1beta.DateRange result =\n new com.google.analytics.data.v1beta.DateRange(this);\n result.startDate_ = startDate_;\n result.endDate_ = endDate_;\n result.name_ = name_;\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.analytics.data.v1beta.DateRange) {\n return mergeFrom((com.google.analytics.data.v1beta.DateRange) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(com.google.analytics.data.v1beta.DateRange other) {\n if (other == com.google.analytics.data.v1beta.DateRange.getDefaultInstance()) return this;\n if (!other.getStartDate().isEmpty()) {\n startDate_ = other.startDate_;\n onChanged();\n }\n if (!other.getEndDate().isEmpty()) {\n endDate_ = other.endDate_;\n onChanged();\n }\n if (!other.getName().isEmpty()) {\n name_ = other.name_;\n onChanged();\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.analytics.data.v1beta.DateRange parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (com.google.analytics.data.v1beta.DateRange) e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private java.lang.Object startDate_ = \"\";\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @return The startDate.\n */\n public java.lang.String getStartDate() {\n java.lang.Object ref = startDate_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n startDate_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @return The bytes for startDate.\n */\n public com.google.protobuf.ByteString getStartDateBytes() {\n java.lang.Object ref = startDate_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n startDate_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @param value The startDate to set.\n * @return This builder for chaining.\n */\n public Builder setStartDate(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n startDate_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearStartDate() {\n\n startDate_ = getDefaultInstance().getStartDate();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The inclusive start date for the query in the format `YYYY-MM-DD`. Cannot\n * be after `end_date`. The format `NdaysAgo`, `yesterday`, or `today` is also\n * accepted, and in that case, the date is inferred based on the property's\n * reporting time zone.\n * </pre>\n *\n * <code>string start_date = 1;</code>\n *\n * @param value The bytes for startDate to set.\n * @return This builder for chaining.\n */\n public Builder setStartDateBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n startDate_ = value;\n onChanged();\n return this;\n }\n\n private java.lang.Object endDate_ = \"\";\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @return The endDate.\n */\n public java.lang.String getEndDate() {\n java.lang.Object ref = endDate_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n endDate_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @return The bytes for endDate.\n */\n public com.google.protobuf.ByteString getEndDateBytes() {\n java.lang.Object ref = endDate_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n endDate_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @param value The endDate to set.\n * @return This builder for chaining.\n */\n public Builder setEndDate(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n endDate_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearEndDate() {\n\n endDate_ = getDefaultInstance().getEndDate();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The inclusive end date for the query in the format `YYYY-MM-DD`. Cannot\n * be before `start_date`. The format `NdaysAgo`, `yesterday`, or `today` is\n * also accepted, and in that case, the date is inferred based on the\n * property's reporting time zone.\n * </pre>\n *\n * <code>string end_date = 2;</code>\n *\n * @param value The bytes for endDate to set.\n * @return This builder for chaining.\n */\n public Builder setEndDateBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n endDate_ = value;\n onChanged();\n return this;\n }\n\n private java.lang.Object name_ = \"\";\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @return The name.\n */\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @return The bytes for name.\n */\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @param value The name to set.\n * @return This builder for chaining.\n */\n public Builder setName(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n name_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearName() {\n\n name_ = getDefaultInstance().getName();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Assigns a name to this date range. The dimension `dateRange` is valued to\n * this name in a report response. If set, cannot begin with `date_range_` or\n * `RESERVED_`. If not set, date ranges are named by their zero based index in\n * the request: `date_range_0`, `date_range_1`, etc.\n * </pre>\n *\n * <code>string name = 3;</code>\n *\n * @param value The bytes for name to set.\n * @return This builder for chaining.\n */\n public Builder setNameBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n name_ = value;\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.setUnknownFields(unknownFields);\n }\n\n @java.lang.Override\n public final Builder mergeUnknownFields(\n final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.mergeUnknownFields(unknownFields);\n }\n\n // @@protoc_insertion_point(builder_scope:google.analytics.data.v1beta.DateRange)\n }\n\n // @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.DateRange)\n private static final com.google.analytics.data.v1beta.DateRange DEFAULT_INSTANCE;\n\n static {\n DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.DateRange();\n }\n\n public static com.google.analytics.data.v1beta.DateRange getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n private static final com.google.protobuf.Parser<DateRange> PARSER =\n new com.google.protobuf.AbstractParser<DateRange>() {\n @java.lang.Override\n public DateRange parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new DateRange(input, extensionRegistry);\n }\n };\n\n public static com.google.protobuf.Parser<DateRange> parser() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.protobuf.Parser<DateRange> getParserForType() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.DateRange getDefaultInstanceForType() {\n return DEFAULT_INSTANCE;\n }\n}", "public final class Dimension extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.Dimension)\n DimensionOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use Dimension.newBuilder() to construct.\n private Dimension(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {\n super(builder);\n }\n\n private Dimension() {\n name_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new Dimension();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private Dimension(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n name_ = s;\n break;\n }\n case 18:\n {\n com.google.analytics.data.v1beta.DimensionExpression.Builder subBuilder = null;\n if (dimensionExpression_ != null) {\n subBuilder = dimensionExpression_.toBuilder();\n }\n dimensionExpression_ =\n input.readMessage(\n com.google.analytics.data.v1beta.DimensionExpression.parser(),\n extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(dimensionExpression_);\n dimensionExpression_ = subBuilder.buildPartial();\n }\n\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Dimension_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Dimension_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.Dimension.class,\n com.google.analytics.data.v1beta.Dimension.Builder.class);\n }\n\n public static final int NAME_FIELD_NUMBER = 1;\n private volatile java.lang.Object name_;\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The name.\n */\n @java.lang.Override\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The bytes for name.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int DIMENSION_EXPRESSION_FIELD_NUMBER = 2;\n private com.google.analytics.data.v1beta.DimensionExpression dimensionExpression_;\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n *\n * @return Whether the dimensionExpression field is set.\n */\n @java.lang.Override\n public boolean hasDimensionExpression() {\n return dimensionExpression_ != null;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n *\n * @return The dimensionExpression.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionExpression getDimensionExpression() {\n return dimensionExpression_ == null\n ? com.google.analytics.data.v1beta.DimensionExpression.getDefaultInstance()\n : dimensionExpression_;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionExpressionOrBuilder\n getDimensionExpressionOrBuilder() {\n return getDimensionExpression();\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);\n }\n if (dimensionExpression_ != null) {\n output.writeMessage(2, getDimensionExpression());\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);\n }\n if (dimensionExpression_ != null) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getDimensionExpression());\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.analytics.data.v1beta.Dimension)) {\n return super.equals(obj);\n }\n com.google.analytics.data.v1beta.Dimension other =\n (com.google.analytics.data.v1beta.Dimension) obj;\n\n if (!getName().equals(other.getName())) return false;\n if (hasDimensionExpression() != other.hasDimensionExpression()) return false;\n if (hasDimensionExpression()) {\n if (!getDimensionExpression().equals(other.getDimensionExpression())) return false;\n }\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n hash = (37 * hash) + NAME_FIELD_NUMBER;\n hash = (53 * hash) + getName().hashCode();\n if (hasDimensionExpression()) {\n hash = (37 * hash) + DIMENSION_EXPRESSION_FIELD_NUMBER;\n hash = (53 * hash) + getDimensionExpression().hashCode();\n }\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(java.nio.ByteBuffer data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Dimension parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(com.google.analytics.data.v1beta.Dimension prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n * <pre>\n * Dimensions are attributes of your data. For example, the dimension city\n * indicates the city from which an event originates. Dimension values in report\n * responses are strings; for example, city could be \"Paris\" or \"New York\".\n * Requests are allowed up to 9 dimensions.\n * </pre>\n *\n * Protobuf type {@code google.analytics.data.v1beta.Dimension}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>\n implements\n // @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.Dimension)\n com.google.analytics.data.v1beta.DimensionOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Dimension_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Dimension_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.Dimension.class,\n com.google.analytics.data.v1beta.Dimension.Builder.class);\n }\n\n // Construct using com.google.analytics.data.v1beta.Dimension.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n name_ = \"\";\n\n if (dimensionExpressionBuilder_ == null) {\n dimensionExpression_ = null;\n } else {\n dimensionExpression_ = null;\n dimensionExpressionBuilder_ = null;\n }\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Dimension_descriptor;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Dimension getDefaultInstanceForType() {\n return com.google.analytics.data.v1beta.Dimension.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Dimension build() {\n com.google.analytics.data.v1beta.Dimension result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Dimension buildPartial() {\n com.google.analytics.data.v1beta.Dimension result =\n new com.google.analytics.data.v1beta.Dimension(this);\n result.name_ = name_;\n if (dimensionExpressionBuilder_ == null) {\n result.dimensionExpression_ = dimensionExpression_;\n } else {\n result.dimensionExpression_ = dimensionExpressionBuilder_.build();\n }\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.analytics.data.v1beta.Dimension) {\n return mergeFrom((com.google.analytics.data.v1beta.Dimension) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(com.google.analytics.data.v1beta.Dimension other) {\n if (other == com.google.analytics.data.v1beta.Dimension.getDefaultInstance()) return this;\n if (!other.getName().isEmpty()) {\n name_ = other.name_;\n onChanged();\n }\n if (other.hasDimensionExpression()) {\n mergeDimensionExpression(other.getDimensionExpression());\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.analytics.data.v1beta.Dimension parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (com.google.analytics.data.v1beta.Dimension) e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private java.lang.Object name_ = \"\";\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The name.\n */\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The bytes for name.\n */\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @param value The name to set.\n * @return This builder for chaining.\n */\n public Builder setName(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n name_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearName() {\n\n name_ = getDefaultInstance().getName();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The name of the dimension. See the [API\n * Dimensions](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions)\n * for the list of dimension names.\n * If `dimensionExpression` is specified, `name` can be any string that you\n * would like within the allowed character set. For example if a\n * `dimensionExpression` concatenates `country` and `city`, you could call\n * that dimension `countryAndCity`. Dimension names that you choose must match\n * the regular expression `^[a-zA-Z0-9_]$`.\n * Dimensions are referenced by `name` in `dimensionFilter`, `orderBys`,\n * `dimensionExpression`, and `pivots`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @param value The bytes for name to set.\n * @return This builder for chaining.\n */\n public Builder setNameBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n name_ = value;\n onChanged();\n return this;\n }\n\n private com.google.analytics.data.v1beta.DimensionExpression dimensionExpression_;\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionExpression,\n com.google.analytics.data.v1beta.DimensionExpression.Builder,\n com.google.analytics.data.v1beta.DimensionExpressionOrBuilder>\n dimensionExpressionBuilder_;\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n *\n * @return Whether the dimensionExpression field is set.\n */\n public boolean hasDimensionExpression() {\n return dimensionExpressionBuilder_ != null || dimensionExpression_ != null;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n *\n * @return The dimensionExpression.\n */\n public com.google.analytics.data.v1beta.DimensionExpression getDimensionExpression() {\n if (dimensionExpressionBuilder_ == null) {\n return dimensionExpression_ == null\n ? com.google.analytics.data.v1beta.DimensionExpression.getDefaultInstance()\n : dimensionExpression_;\n } else {\n return dimensionExpressionBuilder_.getMessage();\n }\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n public Builder setDimensionExpression(\n com.google.analytics.data.v1beta.DimensionExpression value) {\n if (dimensionExpressionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n dimensionExpression_ = value;\n onChanged();\n } else {\n dimensionExpressionBuilder_.setMessage(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n public Builder setDimensionExpression(\n com.google.analytics.data.v1beta.DimensionExpression.Builder builderForValue) {\n if (dimensionExpressionBuilder_ == null) {\n dimensionExpression_ = builderForValue.build();\n onChanged();\n } else {\n dimensionExpressionBuilder_.setMessage(builderForValue.build());\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n public Builder mergeDimensionExpression(\n com.google.analytics.data.v1beta.DimensionExpression value) {\n if (dimensionExpressionBuilder_ == null) {\n if (dimensionExpression_ != null) {\n dimensionExpression_ =\n com.google.analytics.data.v1beta.DimensionExpression.newBuilder(dimensionExpression_)\n .mergeFrom(value)\n .buildPartial();\n } else {\n dimensionExpression_ = value;\n }\n onChanged();\n } else {\n dimensionExpressionBuilder_.mergeFrom(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n public Builder clearDimensionExpression() {\n if (dimensionExpressionBuilder_ == null) {\n dimensionExpression_ = null;\n onChanged();\n } else {\n dimensionExpression_ = null;\n dimensionExpressionBuilder_ = null;\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n public com.google.analytics.data.v1beta.DimensionExpression.Builder\n getDimensionExpressionBuilder() {\n\n onChanged();\n return getDimensionExpressionFieldBuilder().getBuilder();\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n public com.google.analytics.data.v1beta.DimensionExpressionOrBuilder\n getDimensionExpressionOrBuilder() {\n if (dimensionExpressionBuilder_ != null) {\n return dimensionExpressionBuilder_.getMessageOrBuilder();\n } else {\n return dimensionExpression_ == null\n ? com.google.analytics.data.v1beta.DimensionExpression.getDefaultInstance()\n : dimensionExpression_;\n }\n }\n /**\n *\n *\n * <pre>\n * One dimension can be the result of an expression of multiple dimensions.\n * For example, dimension \"country, city\": concatenate(country, \", \", city).\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.DimensionExpression dimension_expression = 2;</code>\n */\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionExpression,\n com.google.analytics.data.v1beta.DimensionExpression.Builder,\n com.google.analytics.data.v1beta.DimensionExpressionOrBuilder>\n getDimensionExpressionFieldBuilder() {\n if (dimensionExpressionBuilder_ == null) {\n dimensionExpressionBuilder_ =\n new com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionExpression,\n com.google.analytics.data.v1beta.DimensionExpression.Builder,\n com.google.analytics.data.v1beta.DimensionExpressionOrBuilder>(\n getDimensionExpression(), getParentForChildren(), isClean());\n dimensionExpression_ = null;\n }\n return dimensionExpressionBuilder_;\n }\n\n @java.lang.Override\n public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.setUnknownFields(unknownFields);\n }\n\n @java.lang.Override\n public final Builder mergeUnknownFields(\n final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.mergeUnknownFields(unknownFields);\n }\n\n // @@protoc_insertion_point(builder_scope:google.analytics.data.v1beta.Dimension)\n }\n\n // @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.Dimension)\n private static final com.google.analytics.data.v1beta.Dimension DEFAULT_INSTANCE;\n\n static {\n DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.Dimension();\n }\n\n public static com.google.analytics.data.v1beta.Dimension getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n private static final com.google.protobuf.Parser<Dimension> PARSER =\n new com.google.protobuf.AbstractParser<Dimension>() {\n @java.lang.Override\n public Dimension parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Dimension(input, extensionRegistry);\n }\n };\n\n public static com.google.protobuf.Parser<Dimension> parser() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.protobuf.Parser<Dimension> getParserForType() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Dimension getDefaultInstanceForType() {\n return DEFAULT_INSTANCE;\n }\n}", "public final class Metric extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.Metric)\n MetricOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use Metric.newBuilder() to construct.\n private Metric(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {\n super(builder);\n }\n\n private Metric() {\n name_ = \"\";\n expression_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new Metric();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private Metric(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n name_ = s;\n break;\n }\n case 18:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n expression_ = s;\n break;\n }\n case 24:\n {\n invisible_ = input.readBool();\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Metric_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Metric_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.Metric.class,\n com.google.analytics.data.v1beta.Metric.Builder.class);\n }\n\n public static final int NAME_FIELD_NUMBER = 1;\n private volatile java.lang.Object name_;\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The name.\n */\n @java.lang.Override\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The bytes for name.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int EXPRESSION_FIELD_NUMBER = 2;\n private volatile java.lang.Object expression_;\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @return The expression.\n */\n @java.lang.Override\n public java.lang.String getExpression() {\n java.lang.Object ref = expression_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n expression_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @return The bytes for expression.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getExpressionBytes() {\n java.lang.Object ref = expression_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n expression_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int INVISIBLE_FIELD_NUMBER = 3;\n private boolean invisible_;\n /**\n *\n *\n * <pre>\n * Indicates if a metric is invisible in the report response. If a metric is\n * invisible, the metric will not produce a column in the response, but can be\n * used in `metricFilter`, `orderBys`, or a metric `expression`.\n * </pre>\n *\n * <code>bool invisible = 3;</code>\n *\n * @return The invisible.\n */\n @java.lang.Override\n public boolean getInvisible() {\n return invisible_;\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(expression_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 2, expression_);\n }\n if (invisible_ != false) {\n output.writeBool(3, invisible_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(expression_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, expression_);\n }\n if (invisible_ != false) {\n size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, invisible_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.analytics.data.v1beta.Metric)) {\n return super.equals(obj);\n }\n com.google.analytics.data.v1beta.Metric other = (com.google.analytics.data.v1beta.Metric) obj;\n\n if (!getName().equals(other.getName())) return false;\n if (!getExpression().equals(other.getExpression())) return false;\n if (getInvisible() != other.getInvisible()) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n hash = (37 * hash) + NAME_FIELD_NUMBER;\n hash = (53 * hash) + getName().hashCode();\n hash = (37 * hash) + EXPRESSION_FIELD_NUMBER;\n hash = (53 * hash) + getExpression().hashCode();\n hash = (37 * hash) + INVISIBLE_FIELD_NUMBER;\n hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getInvisible());\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(java.nio.ByteBuffer data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Metric parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(com.google.analytics.data.v1beta.Metric prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n * <pre>\n * The quantitative measurements of a report. For example, the metric\n * `eventCount` is the total number of events. Requests are allowed up to 10\n * metrics.\n * </pre>\n *\n * Protobuf type {@code google.analytics.data.v1beta.Metric}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>\n implements\n // @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.Metric)\n com.google.analytics.data.v1beta.MetricOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Metric_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Metric_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.Metric.class,\n com.google.analytics.data.v1beta.Metric.Builder.class);\n }\n\n // Construct using com.google.analytics.data.v1beta.Metric.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n name_ = \"\";\n\n expression_ = \"\";\n\n invisible_ = false;\n\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Metric_descriptor;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Metric getDefaultInstanceForType() {\n return com.google.analytics.data.v1beta.Metric.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Metric build() {\n com.google.analytics.data.v1beta.Metric result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Metric buildPartial() {\n com.google.analytics.data.v1beta.Metric result =\n new com.google.analytics.data.v1beta.Metric(this);\n result.name_ = name_;\n result.expression_ = expression_;\n result.invisible_ = invisible_;\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.analytics.data.v1beta.Metric) {\n return mergeFrom((com.google.analytics.data.v1beta.Metric) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(com.google.analytics.data.v1beta.Metric other) {\n if (other == com.google.analytics.data.v1beta.Metric.getDefaultInstance()) return this;\n if (!other.getName().isEmpty()) {\n name_ = other.name_;\n onChanged();\n }\n if (!other.getExpression().isEmpty()) {\n expression_ = other.expression_;\n onChanged();\n }\n if (other.getInvisible() != false) {\n setInvisible(other.getInvisible());\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.analytics.data.v1beta.Metric parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (com.google.analytics.data.v1beta.Metric) e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private java.lang.Object name_ = \"\";\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The name.\n */\n public java.lang.String getName() {\n java.lang.Object ref = name_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n name_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return The bytes for name.\n */\n public com.google.protobuf.ByteString getNameBytes() {\n java.lang.Object ref = name_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n name_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @param value The name to set.\n * @return This builder for chaining.\n */\n public Builder setName(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n name_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearName() {\n\n name_ = getDefaultInstance().getName();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The name of the metric. See the [API\n * Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics)\n * for the list of metric names.\n * If `expression` is specified, `name` can be any string that you would like\n * within the allowed character set. For example if `expression` is\n * `screenPageViews/sessions`, you could call that metric's name =\n * `viewsPerSession`. Metric names that you choose must match the regular\n * expression `^[a-zA-Z0-9_]$`.\n * Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric\n * `expression`.\n * </pre>\n *\n * <code>string name = 1;</code>\n *\n * @param value The bytes for name to set.\n * @return This builder for chaining.\n */\n public Builder setNameBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n name_ = value;\n onChanged();\n return this;\n }\n\n private java.lang.Object expression_ = \"\";\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @return The expression.\n */\n public java.lang.String getExpression() {\n java.lang.Object ref = expression_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n expression_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @return The bytes for expression.\n */\n public com.google.protobuf.ByteString getExpressionBytes() {\n java.lang.Object ref = expression_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n expression_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @param value The expression to set.\n * @return This builder for chaining.\n */\n public Builder setExpression(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n expression_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearExpression() {\n\n expression_ = getDefaultInstance().getExpression();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * A mathematical expression for derived metrics. For example, the metric\n * Event count per user is `eventCount/totalUsers`.\n * </pre>\n *\n * <code>string expression = 2;</code>\n *\n * @param value The bytes for expression to set.\n * @return This builder for chaining.\n */\n public Builder setExpressionBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n expression_ = value;\n onChanged();\n return this;\n }\n\n private boolean invisible_;\n /**\n *\n *\n * <pre>\n * Indicates if a metric is invisible in the report response. If a metric is\n * invisible, the metric will not produce a column in the response, but can be\n * used in `metricFilter`, `orderBys`, or a metric `expression`.\n * </pre>\n *\n * <code>bool invisible = 3;</code>\n *\n * @return The invisible.\n */\n @java.lang.Override\n public boolean getInvisible() {\n return invisible_;\n }\n /**\n *\n *\n * <pre>\n * Indicates if a metric is invisible in the report response. If a metric is\n * invisible, the metric will not produce a column in the response, but can be\n * used in `metricFilter`, `orderBys`, or a metric `expression`.\n * </pre>\n *\n * <code>bool invisible = 3;</code>\n *\n * @param value The invisible to set.\n * @return This builder for chaining.\n */\n public Builder setInvisible(boolean value) {\n\n invisible_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Indicates if a metric is invisible in the report response. If a metric is\n * invisible, the metric will not produce a column in the response, but can be\n * used in `metricFilter`, `orderBys`, or a metric `expression`.\n * </pre>\n *\n * <code>bool invisible = 3;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearInvisible() {\n\n invisible_ = false;\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.setUnknownFields(unknownFields);\n }\n\n @java.lang.Override\n public final Builder mergeUnknownFields(\n final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.mergeUnknownFields(unknownFields);\n }\n\n // @@protoc_insertion_point(builder_scope:google.analytics.data.v1beta.Metric)\n }\n\n // @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.Metric)\n private static final com.google.analytics.data.v1beta.Metric DEFAULT_INSTANCE;\n\n static {\n DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.Metric();\n }\n\n public static com.google.analytics.data.v1beta.Metric getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n private static final com.google.protobuf.Parser<Metric> PARSER =\n new com.google.protobuf.AbstractParser<Metric>() {\n @java.lang.Override\n public Metric parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Metric(input, extensionRegistry);\n }\n };\n\n public static com.google.protobuf.Parser<Metric> parser() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.protobuf.Parser<Metric> getParserForType() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Metric getDefaultInstanceForType() {\n return DEFAULT_INSTANCE;\n }\n}", "public final class Row extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.Row)\n RowOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use Row.newBuilder() to construct.\n private Row(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {\n super(builder);\n }\n\n private Row() {\n dimensionValues_ = java.util.Collections.emptyList();\n metricValues_ = java.util.Collections.emptyList();\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new Row();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private Row(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n if (!((mutable_bitField0_ & 0x00000001) != 0)) {\n dimensionValues_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.DimensionValue>();\n mutable_bitField0_ |= 0x00000001;\n }\n dimensionValues_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.DimensionValue.parser(), extensionRegistry));\n break;\n }\n case 18:\n {\n if (!((mutable_bitField0_ & 0x00000002) != 0)) {\n metricValues_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.MetricValue>();\n mutable_bitField0_ |= 0x00000002;\n }\n metricValues_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.MetricValue.parser(), extensionRegistry));\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000001) != 0)) {\n dimensionValues_ = java.util.Collections.unmodifiableList(dimensionValues_);\n }\n if (((mutable_bitField0_ & 0x00000002) != 0)) {\n metricValues_ = java.util.Collections.unmodifiableList(metricValues_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Row_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Row_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.Row.class,\n com.google.analytics.data.v1beta.Row.Builder.class);\n }\n\n public static final int DIMENSION_VALUES_FIELD_NUMBER = 1;\n private java.util.List<com.google.analytics.data.v1beta.DimensionValue> dimensionValues_;\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.DimensionValue> getDimensionValuesList() {\n return dimensionValues_;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.DimensionValueOrBuilder>\n getDimensionValuesOrBuilderList() {\n return dimensionValues_;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n @java.lang.Override\n public int getDimensionValuesCount() {\n return dimensionValues_.size();\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionValue getDimensionValues(int index) {\n return dimensionValues_.get(index);\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionValueOrBuilder getDimensionValuesOrBuilder(\n int index) {\n return dimensionValues_.get(index);\n }\n\n public static final int METRIC_VALUES_FIELD_NUMBER = 2;\n private java.util.List<com.google.analytics.data.v1beta.MetricValue> metricValues_;\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.MetricValue> getMetricValuesList() {\n return metricValues_;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.MetricValueOrBuilder>\n getMetricValuesOrBuilderList() {\n return metricValues_;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n @java.lang.Override\n public int getMetricValuesCount() {\n return metricValues_.size();\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.MetricValue getMetricValues(int index) {\n return metricValues_.get(index);\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.MetricValueOrBuilder getMetricValuesOrBuilder(int index) {\n return metricValues_.get(index);\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n for (int i = 0; i < dimensionValues_.size(); i++) {\n output.writeMessage(1, dimensionValues_.get(i));\n }\n for (int i = 0; i < metricValues_.size(); i++) {\n output.writeMessage(2, metricValues_.get(i));\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n for (int i = 0; i < dimensionValues_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dimensionValues_.get(i));\n }\n for (int i = 0; i < metricValues_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, metricValues_.get(i));\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.analytics.data.v1beta.Row)) {\n return super.equals(obj);\n }\n com.google.analytics.data.v1beta.Row other = (com.google.analytics.data.v1beta.Row) obj;\n\n if (!getDimensionValuesList().equals(other.getDimensionValuesList())) return false;\n if (!getMetricValuesList().equals(other.getMetricValuesList())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n if (getDimensionValuesCount() > 0) {\n hash = (37 * hash) + DIMENSION_VALUES_FIELD_NUMBER;\n hash = (53 * hash) + getDimensionValuesList().hashCode();\n }\n if (getMetricValuesCount() > 0) {\n hash = (37 * hash) + METRIC_VALUES_FIELD_NUMBER;\n hash = (53 * hash) + getMetricValuesList().hashCode();\n }\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(java.nio.ByteBuffer data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Row parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Row parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.Row parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(com.google.analytics.data.v1beta.Row prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n * <pre>\n * Report data for each row.\n * For example if RunReportRequest contains:\n * ```none\n * \"dimensions\": [\n * {\n * \"name\": \"eventName\"\n * },\n * {\n * \"name\": \"countryId\"\n * }\n * ],\n * \"metrics\": [\n * {\n * \"name\": \"eventCount\"\n * }\n * ]\n * ```\n * One row with 'in_app_purchase' as the eventName, 'JP' as the countryId, and\n * 15 as the eventCount, would be:\n * ```none\n * \"dimensionValues\": [\n * {\n * \"value\": \"in_app_purchase\"\n * },\n * {\n * \"value\": \"JP\"\n * }\n * ],\n * \"metricValues\": [\n * {\n * \"value\": \"15\"\n * }\n * ]\n * ```\n * </pre>\n *\n * Protobuf type {@code google.analytics.data.v1beta.Row}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>\n implements\n // @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.Row)\n com.google.analytics.data.v1beta.RowOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Row_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Row_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.Row.class,\n com.google.analytics.data.v1beta.Row.Builder.class);\n }\n\n // Construct using com.google.analytics.data.v1beta.Row.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {\n getDimensionValuesFieldBuilder();\n getMetricValuesFieldBuilder();\n }\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n if (dimensionValuesBuilder_ == null) {\n dimensionValues_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n dimensionValuesBuilder_.clear();\n }\n if (metricValuesBuilder_ == null) {\n metricValues_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000002);\n } else {\n metricValuesBuilder_.clear();\n }\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.analytics.data.v1beta.ReportingApiProto\n .internal_static_google_analytics_data_v1beta_Row_descriptor;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row getDefaultInstanceForType() {\n return com.google.analytics.data.v1beta.Row.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row build() {\n com.google.analytics.data.v1beta.Row result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row buildPartial() {\n com.google.analytics.data.v1beta.Row result = new com.google.analytics.data.v1beta.Row(this);\n int from_bitField0_ = bitField0_;\n if (dimensionValuesBuilder_ == null) {\n if (((bitField0_ & 0x00000001) != 0)) {\n dimensionValues_ = java.util.Collections.unmodifiableList(dimensionValues_);\n bitField0_ = (bitField0_ & ~0x00000001);\n }\n result.dimensionValues_ = dimensionValues_;\n } else {\n result.dimensionValues_ = dimensionValuesBuilder_.build();\n }\n if (metricValuesBuilder_ == null) {\n if (((bitField0_ & 0x00000002) != 0)) {\n metricValues_ = java.util.Collections.unmodifiableList(metricValues_);\n bitField0_ = (bitField0_ & ~0x00000002);\n }\n result.metricValues_ = metricValues_;\n } else {\n result.metricValues_ = metricValuesBuilder_.build();\n }\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.analytics.data.v1beta.Row) {\n return mergeFrom((com.google.analytics.data.v1beta.Row) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(com.google.analytics.data.v1beta.Row other) {\n if (other == com.google.analytics.data.v1beta.Row.getDefaultInstance()) return this;\n if (dimensionValuesBuilder_ == null) {\n if (!other.dimensionValues_.isEmpty()) {\n if (dimensionValues_.isEmpty()) {\n dimensionValues_ = other.dimensionValues_;\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n ensureDimensionValuesIsMutable();\n dimensionValues_.addAll(other.dimensionValues_);\n }\n onChanged();\n }\n } else {\n if (!other.dimensionValues_.isEmpty()) {\n if (dimensionValuesBuilder_.isEmpty()) {\n dimensionValuesBuilder_.dispose();\n dimensionValuesBuilder_ = null;\n dimensionValues_ = other.dimensionValues_;\n bitField0_ = (bitField0_ & ~0x00000001);\n dimensionValuesBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getDimensionValuesFieldBuilder()\n : null;\n } else {\n dimensionValuesBuilder_.addAllMessages(other.dimensionValues_);\n }\n }\n }\n if (metricValuesBuilder_ == null) {\n if (!other.metricValues_.isEmpty()) {\n if (metricValues_.isEmpty()) {\n metricValues_ = other.metricValues_;\n bitField0_ = (bitField0_ & ~0x00000002);\n } else {\n ensureMetricValuesIsMutable();\n metricValues_.addAll(other.metricValues_);\n }\n onChanged();\n }\n } else {\n if (!other.metricValues_.isEmpty()) {\n if (metricValuesBuilder_.isEmpty()) {\n metricValuesBuilder_.dispose();\n metricValuesBuilder_ = null;\n metricValues_ = other.metricValues_;\n bitField0_ = (bitField0_ & ~0x00000002);\n metricValuesBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getMetricValuesFieldBuilder()\n : null;\n } else {\n metricValuesBuilder_.addAllMessages(other.metricValues_);\n }\n }\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.analytics.data.v1beta.Row parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (com.google.analytics.data.v1beta.Row) e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private int bitField0_;\n\n private java.util.List<com.google.analytics.data.v1beta.DimensionValue> dimensionValues_ =\n java.util.Collections.emptyList();\n\n private void ensureDimensionValuesIsMutable() {\n if (!((bitField0_ & 0x00000001) != 0)) {\n dimensionValues_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.DimensionValue>(\n dimensionValues_);\n bitField0_ |= 0x00000001;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionValue,\n com.google.analytics.data.v1beta.DimensionValue.Builder,\n com.google.analytics.data.v1beta.DimensionValueOrBuilder>\n dimensionValuesBuilder_;\n\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.DimensionValue>\n getDimensionValuesList() {\n if (dimensionValuesBuilder_ == null) {\n return java.util.Collections.unmodifiableList(dimensionValues_);\n } else {\n return dimensionValuesBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public int getDimensionValuesCount() {\n if (dimensionValuesBuilder_ == null) {\n return dimensionValues_.size();\n } else {\n return dimensionValuesBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionValue getDimensionValues(int index) {\n if (dimensionValuesBuilder_ == null) {\n return dimensionValues_.get(index);\n } else {\n return dimensionValuesBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder setDimensionValues(\n int index, com.google.analytics.data.v1beta.DimensionValue value) {\n if (dimensionValuesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionValuesIsMutable();\n dimensionValues_.set(index, value);\n onChanged();\n } else {\n dimensionValuesBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder setDimensionValues(\n int index, com.google.analytics.data.v1beta.DimensionValue.Builder builderForValue) {\n if (dimensionValuesBuilder_ == null) {\n ensureDimensionValuesIsMutable();\n dimensionValues_.set(index, builderForValue.build());\n onChanged();\n } else {\n dimensionValuesBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder addDimensionValues(com.google.analytics.data.v1beta.DimensionValue value) {\n if (dimensionValuesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionValuesIsMutable();\n dimensionValues_.add(value);\n onChanged();\n } else {\n dimensionValuesBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder addDimensionValues(\n int index, com.google.analytics.data.v1beta.DimensionValue value) {\n if (dimensionValuesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionValuesIsMutable();\n dimensionValues_.add(index, value);\n onChanged();\n } else {\n dimensionValuesBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder addDimensionValues(\n com.google.analytics.data.v1beta.DimensionValue.Builder builderForValue) {\n if (dimensionValuesBuilder_ == null) {\n ensureDimensionValuesIsMutable();\n dimensionValues_.add(builderForValue.build());\n onChanged();\n } else {\n dimensionValuesBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder addDimensionValues(\n int index, com.google.analytics.data.v1beta.DimensionValue.Builder builderForValue) {\n if (dimensionValuesBuilder_ == null) {\n ensureDimensionValuesIsMutable();\n dimensionValues_.add(index, builderForValue.build());\n onChanged();\n } else {\n dimensionValuesBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder addAllDimensionValues(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.DimensionValue> values) {\n if (dimensionValuesBuilder_ == null) {\n ensureDimensionValuesIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dimensionValues_);\n onChanged();\n } else {\n dimensionValuesBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder clearDimensionValues() {\n if (dimensionValuesBuilder_ == null) {\n dimensionValues_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n onChanged();\n } else {\n dimensionValuesBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public Builder removeDimensionValues(int index) {\n if (dimensionValuesBuilder_ == null) {\n ensureDimensionValuesIsMutable();\n dimensionValues_.remove(index);\n onChanged();\n } else {\n dimensionValuesBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionValue.Builder getDimensionValuesBuilder(\n int index) {\n return getDimensionValuesFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionValueOrBuilder getDimensionValuesOrBuilder(\n int index) {\n if (dimensionValuesBuilder_ == null) {\n return dimensionValues_.get(index);\n } else {\n return dimensionValuesBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.DimensionValueOrBuilder>\n getDimensionValuesOrBuilderList() {\n if (dimensionValuesBuilder_ != null) {\n return dimensionValuesBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(dimensionValues_);\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionValue.Builder addDimensionValuesBuilder() {\n return getDimensionValuesFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.DimensionValue.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionValue.Builder addDimensionValuesBuilder(\n int index) {\n return getDimensionValuesFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.DimensionValue.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * List of requested dimension values. In a PivotReport, dimension_values\n * are only listed for dimensions included in a pivot.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionValue dimension_values = 1;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.DimensionValue.Builder>\n getDimensionValuesBuilderList() {\n return getDimensionValuesFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionValue,\n com.google.analytics.data.v1beta.DimensionValue.Builder,\n com.google.analytics.data.v1beta.DimensionValueOrBuilder>\n getDimensionValuesFieldBuilder() {\n if (dimensionValuesBuilder_ == null) {\n dimensionValuesBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionValue,\n com.google.analytics.data.v1beta.DimensionValue.Builder,\n com.google.analytics.data.v1beta.DimensionValueOrBuilder>(\n dimensionValues_,\n ((bitField0_ & 0x00000001) != 0),\n getParentForChildren(),\n isClean());\n dimensionValues_ = null;\n }\n return dimensionValuesBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.MetricValue> metricValues_ =\n java.util.Collections.emptyList();\n\n private void ensureMetricValuesIsMutable() {\n if (!((bitField0_ & 0x00000002) != 0)) {\n metricValues_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.MetricValue>(metricValues_);\n bitField0_ |= 0x00000002;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.MetricValue,\n com.google.analytics.data.v1beta.MetricValue.Builder,\n com.google.analytics.data.v1beta.MetricValueOrBuilder>\n metricValuesBuilder_;\n\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.MetricValue> getMetricValuesList() {\n if (metricValuesBuilder_ == null) {\n return java.util.Collections.unmodifiableList(metricValues_);\n } else {\n return metricValuesBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public int getMetricValuesCount() {\n if (metricValuesBuilder_ == null) {\n return metricValues_.size();\n } else {\n return metricValuesBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricValue getMetricValues(int index) {\n if (metricValuesBuilder_ == null) {\n return metricValues_.get(index);\n } else {\n return metricValuesBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder setMetricValues(int index, com.google.analytics.data.v1beta.MetricValue value) {\n if (metricValuesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricValuesIsMutable();\n metricValues_.set(index, value);\n onChanged();\n } else {\n metricValuesBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder setMetricValues(\n int index, com.google.analytics.data.v1beta.MetricValue.Builder builderForValue) {\n if (metricValuesBuilder_ == null) {\n ensureMetricValuesIsMutable();\n metricValues_.set(index, builderForValue.build());\n onChanged();\n } else {\n metricValuesBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder addMetricValues(com.google.analytics.data.v1beta.MetricValue value) {\n if (metricValuesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricValuesIsMutable();\n metricValues_.add(value);\n onChanged();\n } else {\n metricValuesBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder addMetricValues(int index, com.google.analytics.data.v1beta.MetricValue value) {\n if (metricValuesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricValuesIsMutable();\n metricValues_.add(index, value);\n onChanged();\n } else {\n metricValuesBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder addMetricValues(\n com.google.analytics.data.v1beta.MetricValue.Builder builderForValue) {\n if (metricValuesBuilder_ == null) {\n ensureMetricValuesIsMutable();\n metricValues_.add(builderForValue.build());\n onChanged();\n } else {\n metricValuesBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder addMetricValues(\n int index, com.google.analytics.data.v1beta.MetricValue.Builder builderForValue) {\n if (metricValuesBuilder_ == null) {\n ensureMetricValuesIsMutable();\n metricValues_.add(index, builderForValue.build());\n onChanged();\n } else {\n metricValuesBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder addAllMetricValues(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.MetricValue> values) {\n if (metricValuesBuilder_ == null) {\n ensureMetricValuesIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, metricValues_);\n onChanged();\n } else {\n metricValuesBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder clearMetricValues() {\n if (metricValuesBuilder_ == null) {\n metricValues_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000002);\n onChanged();\n } else {\n metricValuesBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public Builder removeMetricValues(int index) {\n if (metricValuesBuilder_ == null) {\n ensureMetricValuesIsMutable();\n metricValues_.remove(index);\n onChanged();\n } else {\n metricValuesBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricValue.Builder getMetricValuesBuilder(int index) {\n return getMetricValuesFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricValueOrBuilder getMetricValuesOrBuilder(\n int index) {\n if (metricValuesBuilder_ == null) {\n return metricValues_.get(index);\n } else {\n return metricValuesBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.MetricValueOrBuilder>\n getMetricValuesOrBuilderList() {\n if (metricValuesBuilder_ != null) {\n return metricValuesBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(metricValues_);\n }\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricValue.Builder addMetricValuesBuilder() {\n return getMetricValuesFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.MetricValue.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricValue.Builder addMetricValuesBuilder(int index) {\n return getMetricValuesFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.MetricValue.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * List of requested visible metric values.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricValue metric_values = 2;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.MetricValue.Builder>\n getMetricValuesBuilderList() {\n return getMetricValuesFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.MetricValue,\n com.google.analytics.data.v1beta.MetricValue.Builder,\n com.google.analytics.data.v1beta.MetricValueOrBuilder>\n getMetricValuesFieldBuilder() {\n if (metricValuesBuilder_ == null) {\n metricValuesBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.MetricValue,\n com.google.analytics.data.v1beta.MetricValue.Builder,\n com.google.analytics.data.v1beta.MetricValueOrBuilder>(\n metricValues_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean());\n metricValues_ = null;\n }\n return metricValuesBuilder_;\n }\n\n @java.lang.Override\n public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.setUnknownFields(unknownFields);\n }\n\n @java.lang.Override\n public final Builder mergeUnknownFields(\n final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.mergeUnknownFields(unknownFields);\n }\n\n // @@protoc_insertion_point(builder_scope:google.analytics.data.v1beta.Row)\n }\n\n // @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.Row)\n private static final com.google.analytics.data.v1beta.Row DEFAULT_INSTANCE;\n\n static {\n DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.Row();\n }\n\n public static com.google.analytics.data.v1beta.Row getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n private static final com.google.protobuf.Parser<Row> PARSER =\n new com.google.protobuf.AbstractParser<Row>() {\n @java.lang.Override\n public Row parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Row(input, extensionRegistry);\n }\n };\n\n public static com.google.protobuf.Parser<Row> parser() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.protobuf.Parser<Row> getParserForType() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row getDefaultInstanceForType() {\n return DEFAULT_INSTANCE;\n }\n}", "public final class RunReportRequest extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.RunReportRequest)\n RunReportRequestOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use RunReportRequest.newBuilder() to construct.\n private RunReportRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {\n super(builder);\n }\n\n private RunReportRequest() {\n property_ = \"\";\n dimensions_ = java.util.Collections.emptyList();\n metrics_ = java.util.Collections.emptyList();\n dateRanges_ = java.util.Collections.emptyList();\n metricAggregations_ = java.util.Collections.emptyList();\n orderBys_ = java.util.Collections.emptyList();\n currencyCode_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new RunReportRequest();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private RunReportRequest(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n property_ = s;\n break;\n }\n case 18:\n {\n if (!((mutable_bitField0_ & 0x00000001) != 0)) {\n dimensions_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Dimension>();\n mutable_bitField0_ |= 0x00000001;\n }\n dimensions_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.Dimension.parser(), extensionRegistry));\n break;\n }\n case 26:\n {\n if (!((mutable_bitField0_ & 0x00000002) != 0)) {\n metrics_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Metric>();\n mutable_bitField0_ |= 0x00000002;\n }\n metrics_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.Metric.parser(), extensionRegistry));\n break;\n }\n case 34:\n {\n if (!((mutable_bitField0_ & 0x00000004) != 0)) {\n dateRanges_ = new java.util.ArrayList<com.google.analytics.data.v1beta.DateRange>();\n mutable_bitField0_ |= 0x00000004;\n }\n dateRanges_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.DateRange.parser(), extensionRegistry));\n break;\n }\n case 42:\n {\n com.google.analytics.data.v1beta.FilterExpression.Builder subBuilder = null;\n if (dimensionFilter_ != null) {\n subBuilder = dimensionFilter_.toBuilder();\n }\n dimensionFilter_ =\n input.readMessage(\n com.google.analytics.data.v1beta.FilterExpression.parser(),\n extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(dimensionFilter_);\n dimensionFilter_ = subBuilder.buildPartial();\n }\n\n break;\n }\n case 50:\n {\n com.google.analytics.data.v1beta.FilterExpression.Builder subBuilder = null;\n if (metricFilter_ != null) {\n subBuilder = metricFilter_.toBuilder();\n }\n metricFilter_ =\n input.readMessage(\n com.google.analytics.data.v1beta.FilterExpression.parser(),\n extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(metricFilter_);\n metricFilter_ = subBuilder.buildPartial();\n }\n\n break;\n }\n case 56:\n {\n offset_ = input.readInt64();\n break;\n }\n case 64:\n {\n limit_ = input.readInt64();\n break;\n }\n case 72:\n {\n int rawValue = input.readEnum();\n if (!((mutable_bitField0_ & 0x00000008) != 0)) {\n metricAggregations_ = new java.util.ArrayList<java.lang.Integer>();\n mutable_bitField0_ |= 0x00000008;\n }\n metricAggregations_.add(rawValue);\n break;\n }\n case 74:\n {\n int length = input.readRawVarint32();\n int oldLimit = input.pushLimit(length);\n while (input.getBytesUntilLimit() > 0) {\n int rawValue = input.readEnum();\n if (!((mutable_bitField0_ & 0x00000008) != 0)) {\n metricAggregations_ = new java.util.ArrayList<java.lang.Integer>();\n mutable_bitField0_ |= 0x00000008;\n }\n metricAggregations_.add(rawValue);\n }\n input.popLimit(oldLimit);\n break;\n }\n case 82:\n {\n if (!((mutable_bitField0_ & 0x00000010) != 0)) {\n orderBys_ = new java.util.ArrayList<com.google.analytics.data.v1beta.OrderBy>();\n mutable_bitField0_ |= 0x00000010;\n }\n orderBys_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.OrderBy.parser(), extensionRegistry));\n break;\n }\n case 90:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n currencyCode_ = s;\n break;\n }\n case 98:\n {\n com.google.analytics.data.v1beta.CohortSpec.Builder subBuilder = null;\n if (cohortSpec_ != null) {\n subBuilder = cohortSpec_.toBuilder();\n }\n cohortSpec_ =\n input.readMessage(\n com.google.analytics.data.v1beta.CohortSpec.parser(), extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(cohortSpec_);\n cohortSpec_ = subBuilder.buildPartial();\n }\n\n break;\n }\n case 104:\n {\n keepEmptyRows_ = input.readBool();\n break;\n }\n case 112:\n {\n returnPropertyQuota_ = input.readBool();\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000001) != 0)) {\n dimensions_ = java.util.Collections.unmodifiableList(dimensions_);\n }\n if (((mutable_bitField0_ & 0x00000002) != 0)) {\n metrics_ = java.util.Collections.unmodifiableList(metrics_);\n }\n if (((mutable_bitField0_ & 0x00000004) != 0)) {\n dateRanges_ = java.util.Collections.unmodifiableList(dateRanges_);\n }\n if (((mutable_bitField0_ & 0x00000008) != 0)) {\n metricAggregations_ = java.util.Collections.unmodifiableList(metricAggregations_);\n }\n if (((mutable_bitField0_ & 0x00000010) != 0)) {\n orderBys_ = java.util.Collections.unmodifiableList(orderBys_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.RunReportRequest.class,\n com.google.analytics.data.v1beta.RunReportRequest.Builder.class);\n }\n\n public static final int PROPERTY_FIELD_NUMBER = 1;\n private volatile java.lang.Object property_;\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @return The property.\n */\n @java.lang.Override\n public java.lang.String getProperty() {\n java.lang.Object ref = property_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n property_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @return The bytes for property.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getPropertyBytes() {\n java.lang.Object ref = property_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n property_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int DIMENSIONS_FIELD_NUMBER = 2;\n private java.util.List<com.google.analytics.data.v1beta.Dimension> dimensions_;\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.Dimension> getDimensionsList() {\n return dimensions_;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.DimensionOrBuilder>\n getDimensionsOrBuilderList() {\n return dimensions_;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n @java.lang.Override\n public int getDimensionsCount() {\n return dimensions_.size();\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.Dimension getDimensions(int index) {\n return dimensions_.get(index);\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionOrBuilder getDimensionsOrBuilder(int index) {\n return dimensions_.get(index);\n }\n\n public static final int METRICS_FIELD_NUMBER = 3;\n private java.util.List<com.google.analytics.data.v1beta.Metric> metrics_;\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.Metric> getMetricsList() {\n return metrics_;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.MetricOrBuilder>\n getMetricsOrBuilderList() {\n return metrics_;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n @java.lang.Override\n public int getMetricsCount() {\n return metrics_.size();\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.Metric getMetrics(int index) {\n return metrics_.get(index);\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.MetricOrBuilder getMetricsOrBuilder(int index) {\n return metrics_.get(index);\n }\n\n public static final int DATE_RANGES_FIELD_NUMBER = 4;\n private java.util.List<com.google.analytics.data.v1beta.DateRange> dateRanges_;\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.DateRange> getDateRangesList() {\n return dateRanges_;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.DateRangeOrBuilder>\n getDateRangesOrBuilderList() {\n return dateRanges_;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n @java.lang.Override\n public int getDateRangesCount() {\n return dateRanges_.size();\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DateRange getDateRanges(int index) {\n return dateRanges_.get(index);\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DateRangeOrBuilder getDateRangesOrBuilder(int index) {\n return dateRanges_.get(index);\n }\n\n public static final int DIMENSION_FILTER_FIELD_NUMBER = 5;\n private com.google.analytics.data.v1beta.FilterExpression dimensionFilter_;\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n *\n * @return Whether the dimensionFilter field is set.\n */\n @java.lang.Override\n public boolean hasDimensionFilter() {\n return dimensionFilter_ != null;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n *\n * @return The dimensionFilter.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.FilterExpression getDimensionFilter() {\n return dimensionFilter_ == null\n ? com.google.analytics.data.v1beta.FilterExpression.getDefaultInstance()\n : dimensionFilter_;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.FilterExpressionOrBuilder getDimensionFilterOrBuilder() {\n return getDimensionFilter();\n }\n\n public static final int METRIC_FILTER_FIELD_NUMBER = 6;\n private com.google.analytics.data.v1beta.FilterExpression metricFilter_;\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n *\n * @return Whether the metricFilter field is set.\n */\n @java.lang.Override\n public boolean hasMetricFilter() {\n return metricFilter_ != null;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n *\n * @return The metricFilter.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.FilterExpression getMetricFilter() {\n return metricFilter_ == null\n ? com.google.analytics.data.v1beta.FilterExpression.getDefaultInstance()\n : metricFilter_;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.FilterExpressionOrBuilder getMetricFilterOrBuilder() {\n return getMetricFilter();\n }\n\n public static final int OFFSET_FIELD_NUMBER = 7;\n private long offset_;\n /**\n *\n *\n * <pre>\n * The row count of the start row. The first row is counted as row 0.\n * When paging, the first request does not specify offset; or equivalently,\n * sets offset to 0; the first request returns the first `limit` of rows. The\n * second request sets offset to the `limit` of the first request; the second\n * request returns the second `limit` of rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 offset = 7;</code>\n *\n * @return The offset.\n */\n @java.lang.Override\n public long getOffset() {\n return offset_;\n }\n\n public static final int LIMIT_FIELD_NUMBER = 8;\n private long limit_;\n /**\n *\n *\n * <pre>\n * The number of rows to return. If unspecified, 10,000 rows are returned. The\n * API returns a maximum of 100,000 rows per request, no matter how many you\n * ask for. `limit` must be positive.\n * The API can also return fewer rows than the requested `limit`, if there\n * aren't as many dimension values as the `limit`. For instance, there are\n * fewer than 300 possible values for the dimension `country`, so when\n * reporting on only `country`, you can't get more than 300 rows, even if you\n * set `limit` to a higher value.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 limit = 8;</code>\n *\n * @return The limit.\n */\n @java.lang.Override\n public long getLimit() {\n return limit_;\n }\n\n public static final int METRIC_AGGREGATIONS_FIELD_NUMBER = 9;\n private java.util.List<java.lang.Integer> metricAggregations_;\n private static final com.google.protobuf.Internal.ListAdapter.Converter<\n java.lang.Integer, com.google.analytics.data.v1beta.MetricAggregation>\n metricAggregations_converter_ =\n new com.google.protobuf.Internal.ListAdapter.Converter<\n java.lang.Integer, com.google.analytics.data.v1beta.MetricAggregation>() {\n public com.google.analytics.data.v1beta.MetricAggregation convert(\n java.lang.Integer from) {\n @SuppressWarnings(\"deprecation\")\n com.google.analytics.data.v1beta.MetricAggregation result =\n com.google.analytics.data.v1beta.MetricAggregation.valueOf(from);\n return result == null\n ? com.google.analytics.data.v1beta.MetricAggregation.UNRECOGNIZED\n : result;\n }\n };\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;</code>\n *\n * @return A list containing the metricAggregations.\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.MetricAggregation>\n getMetricAggregationsList() {\n return new com.google.protobuf.Internal.ListAdapter<\n java.lang.Integer, com.google.analytics.data.v1beta.MetricAggregation>(\n metricAggregations_, metricAggregations_converter_);\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;</code>\n *\n * @return The count of metricAggregations.\n */\n @java.lang.Override\n public int getMetricAggregationsCount() {\n return metricAggregations_.size();\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;</code>\n *\n * @param index The index of the element to return.\n * @return The metricAggregations at the given index.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.MetricAggregation getMetricAggregations(int index) {\n return metricAggregations_converter_.convert(metricAggregations_.get(index));\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;</code>\n *\n * @return A list containing the enum numeric values on the wire for metricAggregations.\n */\n @java.lang.Override\n public java.util.List<java.lang.Integer> getMetricAggregationsValueList() {\n return metricAggregations_;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;</code>\n *\n * @param index The index of the value to return.\n * @return The enum numeric value on the wire of metricAggregations at the given index.\n */\n @java.lang.Override\n public int getMetricAggregationsValue(int index) {\n return metricAggregations_.get(index);\n }\n\n private int metricAggregationsMemoizedSerializedSize;\n\n public static final int ORDER_BYS_FIELD_NUMBER = 10;\n private java.util.List<com.google.analytics.data.v1beta.OrderBy> orderBys_;\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.OrderBy> getOrderBysList() {\n return orderBys_;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.OrderByOrBuilder>\n getOrderBysOrBuilderList() {\n return orderBys_;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n @java.lang.Override\n public int getOrderBysCount() {\n return orderBys_.size();\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.OrderBy getOrderBys(int index) {\n return orderBys_.get(index);\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.OrderByOrBuilder getOrderBysOrBuilder(int index) {\n return orderBys_.get(index);\n }\n\n public static final int CURRENCY_CODE_FIELD_NUMBER = 11;\n private volatile java.lang.Object currencyCode_;\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @return The currencyCode.\n */\n @java.lang.Override\n public java.lang.String getCurrencyCode() {\n java.lang.Object ref = currencyCode_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n currencyCode_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @return The bytes for currencyCode.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getCurrencyCodeBytes() {\n java.lang.Object ref = currencyCode_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n currencyCode_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n public static final int COHORT_SPEC_FIELD_NUMBER = 12;\n private com.google.analytics.data.v1beta.CohortSpec cohortSpec_;\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n *\n * @return Whether the cohortSpec field is set.\n */\n @java.lang.Override\n public boolean hasCohortSpec() {\n return cohortSpec_ != null;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n *\n * @return The cohortSpec.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.CohortSpec getCohortSpec() {\n return cohortSpec_ == null\n ? com.google.analytics.data.v1beta.CohortSpec.getDefaultInstance()\n : cohortSpec_;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.CohortSpecOrBuilder getCohortSpecOrBuilder() {\n return getCohortSpec();\n }\n\n public static final int KEEP_EMPTY_ROWS_FIELD_NUMBER = 13;\n private boolean keepEmptyRows_;\n /**\n *\n *\n * <pre>\n * If false or unspecified, each row with all metrics equal to 0 will not be\n * returned. If true, these rows will be returned if they are not separately\n * removed by a filter.\n * </pre>\n *\n * <code>bool keep_empty_rows = 13;</code>\n *\n * @return The keepEmptyRows.\n */\n @java.lang.Override\n public boolean getKeepEmptyRows() {\n return keepEmptyRows_;\n }\n\n public static final int RETURN_PROPERTY_QUOTA_FIELD_NUMBER = 14;\n private boolean returnPropertyQuota_;\n /**\n *\n *\n * <pre>\n * Toggles whether to return the current state of this Analytics Property's\n * quota. Quota is returned in [PropertyQuota](#PropertyQuota).\n * </pre>\n *\n * <code>bool return_property_quota = 14;</code>\n *\n * @return The returnPropertyQuota.\n */\n @java.lang.Override\n public boolean getReturnPropertyQuota() {\n return returnPropertyQuota_;\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n getSerializedSize();\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(property_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 1, property_);\n }\n for (int i = 0; i < dimensions_.size(); i++) {\n output.writeMessage(2, dimensions_.get(i));\n }\n for (int i = 0; i < metrics_.size(); i++) {\n output.writeMessage(3, metrics_.get(i));\n }\n for (int i = 0; i < dateRanges_.size(); i++) {\n output.writeMessage(4, dateRanges_.get(i));\n }\n if (dimensionFilter_ != null) {\n output.writeMessage(5, getDimensionFilter());\n }\n if (metricFilter_ != null) {\n output.writeMessage(6, getMetricFilter());\n }\n if (offset_ != 0L) {\n output.writeInt64(7, offset_);\n }\n if (limit_ != 0L) {\n output.writeInt64(8, limit_);\n }\n if (getMetricAggregationsList().size() > 0) {\n output.writeUInt32NoTag(74);\n output.writeUInt32NoTag(metricAggregationsMemoizedSerializedSize);\n }\n for (int i = 0; i < metricAggregations_.size(); i++) {\n output.writeEnumNoTag(metricAggregations_.get(i));\n }\n for (int i = 0; i < orderBys_.size(); i++) {\n output.writeMessage(10, orderBys_.get(i));\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(currencyCode_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 11, currencyCode_);\n }\n if (cohortSpec_ != null) {\n output.writeMessage(12, getCohortSpec());\n }\n if (keepEmptyRows_ != false) {\n output.writeBool(13, keepEmptyRows_);\n }\n if (returnPropertyQuota_ != false) {\n output.writeBool(14, returnPropertyQuota_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(property_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, property_);\n }\n for (int i = 0; i < dimensions_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, dimensions_.get(i));\n }\n for (int i = 0; i < metrics_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, metrics_.get(i));\n }\n for (int i = 0; i < dateRanges_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, dateRanges_.get(i));\n }\n if (dimensionFilter_ != null) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getDimensionFilter());\n }\n if (metricFilter_ != null) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, getMetricFilter());\n }\n if (offset_ != 0L) {\n size += com.google.protobuf.CodedOutputStream.computeInt64Size(7, offset_);\n }\n if (limit_ != 0L) {\n size += com.google.protobuf.CodedOutputStream.computeInt64Size(8, limit_);\n }\n {\n int dataSize = 0;\n for (int i = 0; i < metricAggregations_.size(); i++) {\n dataSize +=\n com.google.protobuf.CodedOutputStream.computeEnumSizeNoTag(metricAggregations_.get(i));\n }\n size += dataSize;\n if (!getMetricAggregationsList().isEmpty()) {\n size += 1;\n size += com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(dataSize);\n }\n metricAggregationsMemoizedSerializedSize = dataSize;\n }\n for (int i = 0; i < orderBys_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(10, orderBys_.get(i));\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(currencyCode_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(11, currencyCode_);\n }\n if (cohortSpec_ != null) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(12, getCohortSpec());\n }\n if (keepEmptyRows_ != false) {\n size += com.google.protobuf.CodedOutputStream.computeBoolSize(13, keepEmptyRows_);\n }\n if (returnPropertyQuota_ != false) {\n size += com.google.protobuf.CodedOutputStream.computeBoolSize(14, returnPropertyQuota_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.analytics.data.v1beta.RunReportRequest)) {\n return super.equals(obj);\n }\n com.google.analytics.data.v1beta.RunReportRequest other =\n (com.google.analytics.data.v1beta.RunReportRequest) obj;\n\n if (!getProperty().equals(other.getProperty())) return false;\n if (!getDimensionsList().equals(other.getDimensionsList())) return false;\n if (!getMetricsList().equals(other.getMetricsList())) return false;\n if (!getDateRangesList().equals(other.getDateRangesList())) return false;\n if (hasDimensionFilter() != other.hasDimensionFilter()) return false;\n if (hasDimensionFilter()) {\n if (!getDimensionFilter().equals(other.getDimensionFilter())) return false;\n }\n if (hasMetricFilter() != other.hasMetricFilter()) return false;\n if (hasMetricFilter()) {\n if (!getMetricFilter().equals(other.getMetricFilter())) return false;\n }\n if (getOffset() != other.getOffset()) return false;\n if (getLimit() != other.getLimit()) return false;\n if (!metricAggregations_.equals(other.metricAggregations_)) return false;\n if (!getOrderBysList().equals(other.getOrderBysList())) return false;\n if (!getCurrencyCode().equals(other.getCurrencyCode())) return false;\n if (hasCohortSpec() != other.hasCohortSpec()) return false;\n if (hasCohortSpec()) {\n if (!getCohortSpec().equals(other.getCohortSpec())) return false;\n }\n if (getKeepEmptyRows() != other.getKeepEmptyRows()) return false;\n if (getReturnPropertyQuota() != other.getReturnPropertyQuota()) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n hash = (37 * hash) + PROPERTY_FIELD_NUMBER;\n hash = (53 * hash) + getProperty().hashCode();\n if (getDimensionsCount() > 0) {\n hash = (37 * hash) + DIMENSIONS_FIELD_NUMBER;\n hash = (53 * hash) + getDimensionsList().hashCode();\n }\n if (getMetricsCount() > 0) {\n hash = (37 * hash) + METRICS_FIELD_NUMBER;\n hash = (53 * hash) + getMetricsList().hashCode();\n }\n if (getDateRangesCount() > 0) {\n hash = (37 * hash) + DATE_RANGES_FIELD_NUMBER;\n hash = (53 * hash) + getDateRangesList().hashCode();\n }\n if (hasDimensionFilter()) {\n hash = (37 * hash) + DIMENSION_FILTER_FIELD_NUMBER;\n hash = (53 * hash) + getDimensionFilter().hashCode();\n }\n if (hasMetricFilter()) {\n hash = (37 * hash) + METRIC_FILTER_FIELD_NUMBER;\n hash = (53 * hash) + getMetricFilter().hashCode();\n }\n hash = (37 * hash) + OFFSET_FIELD_NUMBER;\n hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getOffset());\n hash = (37 * hash) + LIMIT_FIELD_NUMBER;\n hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getLimit());\n if (getMetricAggregationsCount() > 0) {\n hash = (37 * hash) + METRIC_AGGREGATIONS_FIELD_NUMBER;\n hash = (53 * hash) + metricAggregations_.hashCode();\n }\n if (getOrderBysCount() > 0) {\n hash = (37 * hash) + ORDER_BYS_FIELD_NUMBER;\n hash = (53 * hash) + getOrderBysList().hashCode();\n }\n hash = (37 * hash) + CURRENCY_CODE_FIELD_NUMBER;\n hash = (53 * hash) + getCurrencyCode().hashCode();\n if (hasCohortSpec()) {\n hash = (37 * hash) + COHORT_SPEC_FIELD_NUMBER;\n hash = (53 * hash) + getCohortSpec().hashCode();\n }\n hash = (37 * hash) + KEEP_EMPTY_ROWS_FIELD_NUMBER;\n hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getKeepEmptyRows());\n hash = (37 * hash) + RETURN_PROPERTY_QUOTA_FIELD_NUMBER;\n hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getReturnPropertyQuota());\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(com.google.analytics.data.v1beta.RunReportRequest prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n * <pre>\n * The request to generate a report.\n * </pre>\n *\n * Protobuf type {@code google.analytics.data.v1beta.RunReportRequest}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>\n implements\n // @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.RunReportRequest)\n com.google.analytics.data.v1beta.RunReportRequestOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportRequest_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportRequest_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.RunReportRequest.class,\n com.google.analytics.data.v1beta.RunReportRequest.Builder.class);\n }\n\n // Construct using com.google.analytics.data.v1beta.RunReportRequest.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {\n getDimensionsFieldBuilder();\n getMetricsFieldBuilder();\n getDateRangesFieldBuilder();\n getOrderBysFieldBuilder();\n }\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n property_ = \"\";\n\n if (dimensionsBuilder_ == null) {\n dimensions_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n dimensionsBuilder_.clear();\n }\n if (metricsBuilder_ == null) {\n metrics_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000002);\n } else {\n metricsBuilder_.clear();\n }\n if (dateRangesBuilder_ == null) {\n dateRanges_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000004);\n } else {\n dateRangesBuilder_.clear();\n }\n if (dimensionFilterBuilder_ == null) {\n dimensionFilter_ = null;\n } else {\n dimensionFilter_ = null;\n dimensionFilterBuilder_ = null;\n }\n if (metricFilterBuilder_ == null) {\n metricFilter_ = null;\n } else {\n metricFilter_ = null;\n metricFilterBuilder_ = null;\n }\n offset_ = 0L;\n\n limit_ = 0L;\n\n metricAggregations_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000008);\n if (orderBysBuilder_ == null) {\n orderBys_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000010);\n } else {\n orderBysBuilder_.clear();\n }\n currencyCode_ = \"\";\n\n if (cohortSpecBuilder_ == null) {\n cohortSpec_ = null;\n } else {\n cohortSpec_ = null;\n cohortSpecBuilder_ = null;\n }\n keepEmptyRows_ = false;\n\n returnPropertyQuota_ = false;\n\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportRequest_descriptor;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportRequest getDefaultInstanceForType() {\n return com.google.analytics.data.v1beta.RunReportRequest.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportRequest build() {\n com.google.analytics.data.v1beta.RunReportRequest result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportRequest buildPartial() {\n com.google.analytics.data.v1beta.RunReportRequest result =\n new com.google.analytics.data.v1beta.RunReportRequest(this);\n int from_bitField0_ = bitField0_;\n result.property_ = property_;\n if (dimensionsBuilder_ == null) {\n if (((bitField0_ & 0x00000001) != 0)) {\n dimensions_ = java.util.Collections.unmodifiableList(dimensions_);\n bitField0_ = (bitField0_ & ~0x00000001);\n }\n result.dimensions_ = dimensions_;\n } else {\n result.dimensions_ = dimensionsBuilder_.build();\n }\n if (metricsBuilder_ == null) {\n if (((bitField0_ & 0x00000002) != 0)) {\n metrics_ = java.util.Collections.unmodifiableList(metrics_);\n bitField0_ = (bitField0_ & ~0x00000002);\n }\n result.metrics_ = metrics_;\n } else {\n result.metrics_ = metricsBuilder_.build();\n }\n if (dateRangesBuilder_ == null) {\n if (((bitField0_ & 0x00000004) != 0)) {\n dateRanges_ = java.util.Collections.unmodifiableList(dateRanges_);\n bitField0_ = (bitField0_ & ~0x00000004);\n }\n result.dateRanges_ = dateRanges_;\n } else {\n result.dateRanges_ = dateRangesBuilder_.build();\n }\n if (dimensionFilterBuilder_ == null) {\n result.dimensionFilter_ = dimensionFilter_;\n } else {\n result.dimensionFilter_ = dimensionFilterBuilder_.build();\n }\n if (metricFilterBuilder_ == null) {\n result.metricFilter_ = metricFilter_;\n } else {\n result.metricFilter_ = metricFilterBuilder_.build();\n }\n result.offset_ = offset_;\n result.limit_ = limit_;\n if (((bitField0_ & 0x00000008) != 0)) {\n metricAggregations_ = java.util.Collections.unmodifiableList(metricAggregations_);\n bitField0_ = (bitField0_ & ~0x00000008);\n }\n result.metricAggregations_ = metricAggregations_;\n if (orderBysBuilder_ == null) {\n if (((bitField0_ & 0x00000010) != 0)) {\n orderBys_ = java.util.Collections.unmodifiableList(orderBys_);\n bitField0_ = (bitField0_ & ~0x00000010);\n }\n result.orderBys_ = orderBys_;\n } else {\n result.orderBys_ = orderBysBuilder_.build();\n }\n result.currencyCode_ = currencyCode_;\n if (cohortSpecBuilder_ == null) {\n result.cohortSpec_ = cohortSpec_;\n } else {\n result.cohortSpec_ = cohortSpecBuilder_.build();\n }\n result.keepEmptyRows_ = keepEmptyRows_;\n result.returnPropertyQuota_ = returnPropertyQuota_;\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.analytics.data.v1beta.RunReportRequest) {\n return mergeFrom((com.google.analytics.data.v1beta.RunReportRequest) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(com.google.analytics.data.v1beta.RunReportRequest other) {\n if (other == com.google.analytics.data.v1beta.RunReportRequest.getDefaultInstance())\n return this;\n if (!other.getProperty().isEmpty()) {\n property_ = other.property_;\n onChanged();\n }\n if (dimensionsBuilder_ == null) {\n if (!other.dimensions_.isEmpty()) {\n if (dimensions_.isEmpty()) {\n dimensions_ = other.dimensions_;\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n ensureDimensionsIsMutable();\n dimensions_.addAll(other.dimensions_);\n }\n onChanged();\n }\n } else {\n if (!other.dimensions_.isEmpty()) {\n if (dimensionsBuilder_.isEmpty()) {\n dimensionsBuilder_.dispose();\n dimensionsBuilder_ = null;\n dimensions_ = other.dimensions_;\n bitField0_ = (bitField0_ & ~0x00000001);\n dimensionsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getDimensionsFieldBuilder()\n : null;\n } else {\n dimensionsBuilder_.addAllMessages(other.dimensions_);\n }\n }\n }\n if (metricsBuilder_ == null) {\n if (!other.metrics_.isEmpty()) {\n if (metrics_.isEmpty()) {\n metrics_ = other.metrics_;\n bitField0_ = (bitField0_ & ~0x00000002);\n } else {\n ensureMetricsIsMutable();\n metrics_.addAll(other.metrics_);\n }\n onChanged();\n }\n } else {\n if (!other.metrics_.isEmpty()) {\n if (metricsBuilder_.isEmpty()) {\n metricsBuilder_.dispose();\n metricsBuilder_ = null;\n metrics_ = other.metrics_;\n bitField0_ = (bitField0_ & ~0x00000002);\n metricsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getMetricsFieldBuilder()\n : null;\n } else {\n metricsBuilder_.addAllMessages(other.metrics_);\n }\n }\n }\n if (dateRangesBuilder_ == null) {\n if (!other.dateRanges_.isEmpty()) {\n if (dateRanges_.isEmpty()) {\n dateRanges_ = other.dateRanges_;\n bitField0_ = (bitField0_ & ~0x00000004);\n } else {\n ensureDateRangesIsMutable();\n dateRanges_.addAll(other.dateRanges_);\n }\n onChanged();\n }\n } else {\n if (!other.dateRanges_.isEmpty()) {\n if (dateRangesBuilder_.isEmpty()) {\n dateRangesBuilder_.dispose();\n dateRangesBuilder_ = null;\n dateRanges_ = other.dateRanges_;\n bitField0_ = (bitField0_ & ~0x00000004);\n dateRangesBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getDateRangesFieldBuilder()\n : null;\n } else {\n dateRangesBuilder_.addAllMessages(other.dateRanges_);\n }\n }\n }\n if (other.hasDimensionFilter()) {\n mergeDimensionFilter(other.getDimensionFilter());\n }\n if (other.hasMetricFilter()) {\n mergeMetricFilter(other.getMetricFilter());\n }\n if (other.getOffset() != 0L) {\n setOffset(other.getOffset());\n }\n if (other.getLimit() != 0L) {\n setLimit(other.getLimit());\n }\n if (!other.metricAggregations_.isEmpty()) {\n if (metricAggregations_.isEmpty()) {\n metricAggregations_ = other.metricAggregations_;\n bitField0_ = (bitField0_ & ~0x00000008);\n } else {\n ensureMetricAggregationsIsMutable();\n metricAggregations_.addAll(other.metricAggregations_);\n }\n onChanged();\n }\n if (orderBysBuilder_ == null) {\n if (!other.orderBys_.isEmpty()) {\n if (orderBys_.isEmpty()) {\n orderBys_ = other.orderBys_;\n bitField0_ = (bitField0_ & ~0x00000010);\n } else {\n ensureOrderBysIsMutable();\n orderBys_.addAll(other.orderBys_);\n }\n onChanged();\n }\n } else {\n if (!other.orderBys_.isEmpty()) {\n if (orderBysBuilder_.isEmpty()) {\n orderBysBuilder_.dispose();\n orderBysBuilder_ = null;\n orderBys_ = other.orderBys_;\n bitField0_ = (bitField0_ & ~0x00000010);\n orderBysBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getOrderBysFieldBuilder()\n : null;\n } else {\n orderBysBuilder_.addAllMessages(other.orderBys_);\n }\n }\n }\n if (!other.getCurrencyCode().isEmpty()) {\n currencyCode_ = other.currencyCode_;\n onChanged();\n }\n if (other.hasCohortSpec()) {\n mergeCohortSpec(other.getCohortSpec());\n }\n if (other.getKeepEmptyRows() != false) {\n setKeepEmptyRows(other.getKeepEmptyRows());\n }\n if (other.getReturnPropertyQuota() != false) {\n setReturnPropertyQuota(other.getReturnPropertyQuota());\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.analytics.data.v1beta.RunReportRequest parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage =\n (com.google.analytics.data.v1beta.RunReportRequest) e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private int bitField0_;\n\n private java.lang.Object property_ = \"\";\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @return The property.\n */\n public java.lang.String getProperty() {\n java.lang.Object ref = property_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n property_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @return The bytes for property.\n */\n public com.google.protobuf.ByteString getPropertyBytes() {\n java.lang.Object ref = property_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n property_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @param value The property to set.\n * @return This builder for chaining.\n */\n public Builder setProperty(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n property_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearProperty() {\n\n property_ = getDefaultInstance().getProperty();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * A Google Analytics GA4 property identifier whose events are tracked.\n * Specified in the URL path and not the body. To learn more, see [where to\n * find your Property\n * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id).\n * Within a batch request, this property should either be unspecified or\n * consistent with the batch-level property.\n * Example: properties/1234\n * </pre>\n *\n * <code>string property = 1;</code>\n *\n * @param value The bytes for property to set.\n * @return This builder for chaining.\n */\n public Builder setPropertyBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n property_ = value;\n onChanged();\n return this;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.Dimension> dimensions_ =\n java.util.Collections.emptyList();\n\n private void ensureDimensionsIsMutable() {\n if (!((bitField0_ & 0x00000001) != 0)) {\n dimensions_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.Dimension>(dimensions_);\n bitField0_ |= 0x00000001;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Dimension,\n com.google.analytics.data.v1beta.Dimension.Builder,\n com.google.analytics.data.v1beta.DimensionOrBuilder>\n dimensionsBuilder_;\n\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Dimension> getDimensionsList() {\n if (dimensionsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(dimensions_);\n } else {\n return dimensionsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public int getDimensionsCount() {\n if (dimensionsBuilder_ == null) {\n return dimensions_.size();\n } else {\n return dimensionsBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public com.google.analytics.data.v1beta.Dimension getDimensions(int index) {\n if (dimensionsBuilder_ == null) {\n return dimensions_.get(index);\n } else {\n return dimensionsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder setDimensions(int index, com.google.analytics.data.v1beta.Dimension value) {\n if (dimensionsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionsIsMutable();\n dimensions_.set(index, value);\n onChanged();\n } else {\n dimensionsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder setDimensions(\n int index, com.google.analytics.data.v1beta.Dimension.Builder builderForValue) {\n if (dimensionsBuilder_ == null) {\n ensureDimensionsIsMutable();\n dimensions_.set(index, builderForValue.build());\n onChanged();\n } else {\n dimensionsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder addDimensions(com.google.analytics.data.v1beta.Dimension value) {\n if (dimensionsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionsIsMutable();\n dimensions_.add(value);\n onChanged();\n } else {\n dimensionsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder addDimensions(int index, com.google.analytics.data.v1beta.Dimension value) {\n if (dimensionsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionsIsMutable();\n dimensions_.add(index, value);\n onChanged();\n } else {\n dimensionsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder addDimensions(\n com.google.analytics.data.v1beta.Dimension.Builder builderForValue) {\n if (dimensionsBuilder_ == null) {\n ensureDimensionsIsMutable();\n dimensions_.add(builderForValue.build());\n onChanged();\n } else {\n dimensionsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder addDimensions(\n int index, com.google.analytics.data.v1beta.Dimension.Builder builderForValue) {\n if (dimensionsBuilder_ == null) {\n ensureDimensionsIsMutable();\n dimensions_.add(index, builderForValue.build());\n onChanged();\n } else {\n dimensionsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder addAllDimensions(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.Dimension> values) {\n if (dimensionsBuilder_ == null) {\n ensureDimensionsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dimensions_);\n onChanged();\n } else {\n dimensionsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder clearDimensions() {\n if (dimensionsBuilder_ == null) {\n dimensions_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n onChanged();\n } else {\n dimensionsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public Builder removeDimensions(int index) {\n if (dimensionsBuilder_ == null) {\n ensureDimensionsIsMutable();\n dimensions_.remove(index);\n onChanged();\n } else {\n dimensionsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public com.google.analytics.data.v1beta.Dimension.Builder getDimensionsBuilder(int index) {\n return getDimensionsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public com.google.analytics.data.v1beta.DimensionOrBuilder getDimensionsOrBuilder(int index) {\n if (dimensionsBuilder_ == null) {\n return dimensions_.get(index);\n } else {\n return dimensionsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.DimensionOrBuilder>\n getDimensionsOrBuilderList() {\n if (dimensionsBuilder_ != null) {\n return dimensionsBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(dimensions_);\n }\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public com.google.analytics.data.v1beta.Dimension.Builder addDimensionsBuilder() {\n return getDimensionsFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.Dimension.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public com.google.analytics.data.v1beta.Dimension.Builder addDimensionsBuilder(int index) {\n return getDimensionsFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.Dimension.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * The dimensions requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Dimension dimensions = 2;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Dimension.Builder>\n getDimensionsBuilderList() {\n return getDimensionsFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Dimension,\n com.google.analytics.data.v1beta.Dimension.Builder,\n com.google.analytics.data.v1beta.DimensionOrBuilder>\n getDimensionsFieldBuilder() {\n if (dimensionsBuilder_ == null) {\n dimensionsBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Dimension,\n com.google.analytics.data.v1beta.Dimension.Builder,\n com.google.analytics.data.v1beta.DimensionOrBuilder>(\n dimensions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());\n dimensions_ = null;\n }\n return dimensionsBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.Metric> metrics_ =\n java.util.Collections.emptyList();\n\n private void ensureMetricsIsMutable() {\n if (!((bitField0_ & 0x00000002) != 0)) {\n metrics_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Metric>(metrics_);\n bitField0_ |= 0x00000002;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Metric,\n com.google.analytics.data.v1beta.Metric.Builder,\n com.google.analytics.data.v1beta.MetricOrBuilder>\n metricsBuilder_;\n\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Metric> getMetricsList() {\n if (metricsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(metrics_);\n } else {\n return metricsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public int getMetricsCount() {\n if (metricsBuilder_ == null) {\n return metrics_.size();\n } else {\n return metricsBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public com.google.analytics.data.v1beta.Metric getMetrics(int index) {\n if (metricsBuilder_ == null) {\n return metrics_.get(index);\n } else {\n return metricsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder setMetrics(int index, com.google.analytics.data.v1beta.Metric value) {\n if (metricsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricsIsMutable();\n metrics_.set(index, value);\n onChanged();\n } else {\n metricsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder setMetrics(\n int index, com.google.analytics.data.v1beta.Metric.Builder builderForValue) {\n if (metricsBuilder_ == null) {\n ensureMetricsIsMutable();\n metrics_.set(index, builderForValue.build());\n onChanged();\n } else {\n metricsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder addMetrics(com.google.analytics.data.v1beta.Metric value) {\n if (metricsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricsIsMutable();\n metrics_.add(value);\n onChanged();\n } else {\n metricsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder addMetrics(int index, com.google.analytics.data.v1beta.Metric value) {\n if (metricsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricsIsMutable();\n metrics_.add(index, value);\n onChanged();\n } else {\n metricsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder addMetrics(com.google.analytics.data.v1beta.Metric.Builder builderForValue) {\n if (metricsBuilder_ == null) {\n ensureMetricsIsMutable();\n metrics_.add(builderForValue.build());\n onChanged();\n } else {\n metricsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder addMetrics(\n int index, com.google.analytics.data.v1beta.Metric.Builder builderForValue) {\n if (metricsBuilder_ == null) {\n ensureMetricsIsMutable();\n metrics_.add(index, builderForValue.build());\n onChanged();\n } else {\n metricsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder addAllMetrics(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.Metric> values) {\n if (metricsBuilder_ == null) {\n ensureMetricsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, metrics_);\n onChanged();\n } else {\n metricsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder clearMetrics() {\n if (metricsBuilder_ == null) {\n metrics_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000002);\n onChanged();\n } else {\n metricsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public Builder removeMetrics(int index) {\n if (metricsBuilder_ == null) {\n ensureMetricsIsMutable();\n metrics_.remove(index);\n onChanged();\n } else {\n metricsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public com.google.analytics.data.v1beta.Metric.Builder getMetricsBuilder(int index) {\n return getMetricsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public com.google.analytics.data.v1beta.MetricOrBuilder getMetricsOrBuilder(int index) {\n if (metricsBuilder_ == null) {\n return metrics_.get(index);\n } else {\n return metricsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.MetricOrBuilder>\n getMetricsOrBuilderList() {\n if (metricsBuilder_ != null) {\n return metricsBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(metrics_);\n }\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public com.google.analytics.data.v1beta.Metric.Builder addMetricsBuilder() {\n return getMetricsFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.Metric.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public com.google.analytics.data.v1beta.Metric.Builder addMetricsBuilder(int index) {\n return getMetricsFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.Metric.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * The metrics requested and displayed.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Metric metrics = 3;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Metric.Builder> getMetricsBuilderList() {\n return getMetricsFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Metric,\n com.google.analytics.data.v1beta.Metric.Builder,\n com.google.analytics.data.v1beta.MetricOrBuilder>\n getMetricsFieldBuilder() {\n if (metricsBuilder_ == null) {\n metricsBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Metric,\n com.google.analytics.data.v1beta.Metric.Builder,\n com.google.analytics.data.v1beta.MetricOrBuilder>(\n metrics_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean());\n metrics_ = null;\n }\n return metricsBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.DateRange> dateRanges_ =\n java.util.Collections.emptyList();\n\n private void ensureDateRangesIsMutable() {\n if (!((bitField0_ & 0x00000004) != 0)) {\n dateRanges_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.DateRange>(dateRanges_);\n bitField0_ |= 0x00000004;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DateRange,\n com.google.analytics.data.v1beta.DateRange.Builder,\n com.google.analytics.data.v1beta.DateRangeOrBuilder>\n dateRangesBuilder_;\n\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.DateRange> getDateRangesList() {\n if (dateRangesBuilder_ == null) {\n return java.util.Collections.unmodifiableList(dateRanges_);\n } else {\n return dateRangesBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public int getDateRangesCount() {\n if (dateRangesBuilder_ == null) {\n return dateRanges_.size();\n } else {\n return dateRangesBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public com.google.analytics.data.v1beta.DateRange getDateRanges(int index) {\n if (dateRangesBuilder_ == null) {\n return dateRanges_.get(index);\n } else {\n return dateRangesBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder setDateRanges(int index, com.google.analytics.data.v1beta.DateRange value) {\n if (dateRangesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDateRangesIsMutable();\n dateRanges_.set(index, value);\n onChanged();\n } else {\n dateRangesBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder setDateRanges(\n int index, com.google.analytics.data.v1beta.DateRange.Builder builderForValue) {\n if (dateRangesBuilder_ == null) {\n ensureDateRangesIsMutable();\n dateRanges_.set(index, builderForValue.build());\n onChanged();\n } else {\n dateRangesBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder addDateRanges(com.google.analytics.data.v1beta.DateRange value) {\n if (dateRangesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDateRangesIsMutable();\n dateRanges_.add(value);\n onChanged();\n } else {\n dateRangesBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder addDateRanges(int index, com.google.analytics.data.v1beta.DateRange value) {\n if (dateRangesBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDateRangesIsMutable();\n dateRanges_.add(index, value);\n onChanged();\n } else {\n dateRangesBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder addDateRanges(\n com.google.analytics.data.v1beta.DateRange.Builder builderForValue) {\n if (dateRangesBuilder_ == null) {\n ensureDateRangesIsMutable();\n dateRanges_.add(builderForValue.build());\n onChanged();\n } else {\n dateRangesBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder addDateRanges(\n int index, com.google.analytics.data.v1beta.DateRange.Builder builderForValue) {\n if (dateRangesBuilder_ == null) {\n ensureDateRangesIsMutable();\n dateRanges_.add(index, builderForValue.build());\n onChanged();\n } else {\n dateRangesBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder addAllDateRanges(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.DateRange> values) {\n if (dateRangesBuilder_ == null) {\n ensureDateRangesIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dateRanges_);\n onChanged();\n } else {\n dateRangesBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder clearDateRanges() {\n if (dateRangesBuilder_ == null) {\n dateRanges_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000004);\n onChanged();\n } else {\n dateRangesBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public Builder removeDateRanges(int index) {\n if (dateRangesBuilder_ == null) {\n ensureDateRangesIsMutable();\n dateRanges_.remove(index);\n onChanged();\n } else {\n dateRangesBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public com.google.analytics.data.v1beta.DateRange.Builder getDateRangesBuilder(int index) {\n return getDateRangesFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public com.google.analytics.data.v1beta.DateRangeOrBuilder getDateRangesOrBuilder(int index) {\n if (dateRangesBuilder_ == null) {\n return dateRanges_.get(index);\n } else {\n return dateRangesBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.DateRangeOrBuilder>\n getDateRangesOrBuilderList() {\n if (dateRangesBuilder_ != null) {\n return dateRangesBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(dateRanges_);\n }\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public com.google.analytics.data.v1beta.DateRange.Builder addDateRangesBuilder() {\n return getDateRangesFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.DateRange.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public com.google.analytics.data.v1beta.DateRange.Builder addDateRangesBuilder(int index) {\n return getDateRangesFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.DateRange.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Date ranges of data to read. If multiple date ranges are requested, each\n * response row will contain a zero based date range index. If two date\n * ranges overlap, the event data for the overlapping days is included in the\n * response rows for both date ranges. In a cohort request, this `dateRanges`\n * must be unspecified.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DateRange date_ranges = 4;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.DateRange.Builder>\n getDateRangesBuilderList() {\n return getDateRangesFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DateRange,\n com.google.analytics.data.v1beta.DateRange.Builder,\n com.google.analytics.data.v1beta.DateRangeOrBuilder>\n getDateRangesFieldBuilder() {\n if (dateRangesBuilder_ == null) {\n dateRangesBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DateRange,\n com.google.analytics.data.v1beta.DateRange.Builder,\n com.google.analytics.data.v1beta.DateRangeOrBuilder>(\n dateRanges_, ((bitField0_ & 0x00000004) != 0), getParentForChildren(), isClean());\n dateRanges_ = null;\n }\n return dateRangesBuilder_;\n }\n\n private com.google.analytics.data.v1beta.FilterExpression dimensionFilter_;\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.FilterExpression,\n com.google.analytics.data.v1beta.FilterExpression.Builder,\n com.google.analytics.data.v1beta.FilterExpressionOrBuilder>\n dimensionFilterBuilder_;\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n *\n * @return Whether the dimensionFilter field is set.\n */\n public boolean hasDimensionFilter() {\n return dimensionFilterBuilder_ != null || dimensionFilter_ != null;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n *\n * @return The dimensionFilter.\n */\n public com.google.analytics.data.v1beta.FilterExpression getDimensionFilter() {\n if (dimensionFilterBuilder_ == null) {\n return dimensionFilter_ == null\n ? com.google.analytics.data.v1beta.FilterExpression.getDefaultInstance()\n : dimensionFilter_;\n } else {\n return dimensionFilterBuilder_.getMessage();\n }\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n public Builder setDimensionFilter(com.google.analytics.data.v1beta.FilterExpression value) {\n if (dimensionFilterBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n dimensionFilter_ = value;\n onChanged();\n } else {\n dimensionFilterBuilder_.setMessage(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n public Builder setDimensionFilter(\n com.google.analytics.data.v1beta.FilterExpression.Builder builderForValue) {\n if (dimensionFilterBuilder_ == null) {\n dimensionFilter_ = builderForValue.build();\n onChanged();\n } else {\n dimensionFilterBuilder_.setMessage(builderForValue.build());\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n public Builder mergeDimensionFilter(com.google.analytics.data.v1beta.FilterExpression value) {\n if (dimensionFilterBuilder_ == null) {\n if (dimensionFilter_ != null) {\n dimensionFilter_ =\n com.google.analytics.data.v1beta.FilterExpression.newBuilder(dimensionFilter_)\n .mergeFrom(value)\n .buildPartial();\n } else {\n dimensionFilter_ = value;\n }\n onChanged();\n } else {\n dimensionFilterBuilder_.mergeFrom(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n public Builder clearDimensionFilter() {\n if (dimensionFilterBuilder_ == null) {\n dimensionFilter_ = null;\n onChanged();\n } else {\n dimensionFilter_ = null;\n dimensionFilterBuilder_ = null;\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n public com.google.analytics.data.v1beta.FilterExpression.Builder getDimensionFilterBuilder() {\n\n onChanged();\n return getDimensionFilterFieldBuilder().getBuilder();\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n public com.google.analytics.data.v1beta.FilterExpressionOrBuilder\n getDimensionFilterOrBuilder() {\n if (dimensionFilterBuilder_ != null) {\n return dimensionFilterBuilder_.getMessageOrBuilder();\n } else {\n return dimensionFilter_ == null\n ? com.google.analytics.data.v1beta.FilterExpression.getDefaultInstance()\n : dimensionFilter_;\n }\n }\n /**\n *\n *\n * <pre>\n * Dimension filters allow you to ask for only specific dimension values in\n * the report. To learn more, see [Fundamentals of Dimension\n * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters)\n * for examples. Metrics cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression dimension_filter = 5;</code>\n */\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.FilterExpression,\n com.google.analytics.data.v1beta.FilterExpression.Builder,\n com.google.analytics.data.v1beta.FilterExpressionOrBuilder>\n getDimensionFilterFieldBuilder() {\n if (dimensionFilterBuilder_ == null) {\n dimensionFilterBuilder_ =\n new com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.FilterExpression,\n com.google.analytics.data.v1beta.FilterExpression.Builder,\n com.google.analytics.data.v1beta.FilterExpressionOrBuilder>(\n getDimensionFilter(), getParentForChildren(), isClean());\n dimensionFilter_ = null;\n }\n return dimensionFilterBuilder_;\n }\n\n private com.google.analytics.data.v1beta.FilterExpression metricFilter_;\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.FilterExpression,\n com.google.analytics.data.v1beta.FilterExpression.Builder,\n com.google.analytics.data.v1beta.FilterExpressionOrBuilder>\n metricFilterBuilder_;\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n *\n * @return Whether the metricFilter field is set.\n */\n public boolean hasMetricFilter() {\n return metricFilterBuilder_ != null || metricFilter_ != null;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n *\n * @return The metricFilter.\n */\n public com.google.analytics.data.v1beta.FilterExpression getMetricFilter() {\n if (metricFilterBuilder_ == null) {\n return metricFilter_ == null\n ? com.google.analytics.data.v1beta.FilterExpression.getDefaultInstance()\n : metricFilter_;\n } else {\n return metricFilterBuilder_.getMessage();\n }\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n public Builder setMetricFilter(com.google.analytics.data.v1beta.FilterExpression value) {\n if (metricFilterBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n metricFilter_ = value;\n onChanged();\n } else {\n metricFilterBuilder_.setMessage(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n public Builder setMetricFilter(\n com.google.analytics.data.v1beta.FilterExpression.Builder builderForValue) {\n if (metricFilterBuilder_ == null) {\n metricFilter_ = builderForValue.build();\n onChanged();\n } else {\n metricFilterBuilder_.setMessage(builderForValue.build());\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n public Builder mergeMetricFilter(com.google.analytics.data.v1beta.FilterExpression value) {\n if (metricFilterBuilder_ == null) {\n if (metricFilter_ != null) {\n metricFilter_ =\n com.google.analytics.data.v1beta.FilterExpression.newBuilder(metricFilter_)\n .mergeFrom(value)\n .buildPartial();\n } else {\n metricFilter_ = value;\n }\n onChanged();\n } else {\n metricFilterBuilder_.mergeFrom(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n public Builder clearMetricFilter() {\n if (metricFilterBuilder_ == null) {\n metricFilter_ = null;\n onChanged();\n } else {\n metricFilter_ = null;\n metricFilterBuilder_ = null;\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n public com.google.analytics.data.v1beta.FilterExpression.Builder getMetricFilterBuilder() {\n\n onChanged();\n return getMetricFilterFieldBuilder().getBuilder();\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n public com.google.analytics.data.v1beta.FilterExpressionOrBuilder getMetricFilterOrBuilder() {\n if (metricFilterBuilder_ != null) {\n return metricFilterBuilder_.getMessageOrBuilder();\n } else {\n return metricFilter_ == null\n ? com.google.analytics.data.v1beta.FilterExpression.getDefaultInstance()\n : metricFilter_;\n }\n }\n /**\n *\n *\n * <pre>\n * The filter clause of metrics. Applied at post aggregation phase, similar to\n * SQL having-clause. Dimensions cannot be used in this filter.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.FilterExpression metric_filter = 6;</code>\n */\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.FilterExpression,\n com.google.analytics.data.v1beta.FilterExpression.Builder,\n com.google.analytics.data.v1beta.FilterExpressionOrBuilder>\n getMetricFilterFieldBuilder() {\n if (metricFilterBuilder_ == null) {\n metricFilterBuilder_ =\n new com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.FilterExpression,\n com.google.analytics.data.v1beta.FilterExpression.Builder,\n com.google.analytics.data.v1beta.FilterExpressionOrBuilder>(\n getMetricFilter(), getParentForChildren(), isClean());\n metricFilter_ = null;\n }\n return metricFilterBuilder_;\n }\n\n private long offset_;\n /**\n *\n *\n * <pre>\n * The row count of the start row. The first row is counted as row 0.\n * When paging, the first request does not specify offset; or equivalently,\n * sets offset to 0; the first request returns the first `limit` of rows. The\n * second request sets offset to the `limit` of the first request; the second\n * request returns the second `limit` of rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 offset = 7;</code>\n *\n * @return The offset.\n */\n @java.lang.Override\n public long getOffset() {\n return offset_;\n }\n /**\n *\n *\n * <pre>\n * The row count of the start row. The first row is counted as row 0.\n * When paging, the first request does not specify offset; or equivalently,\n * sets offset to 0; the first request returns the first `limit` of rows. The\n * second request sets offset to the `limit` of the first request; the second\n * request returns the second `limit` of rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 offset = 7;</code>\n *\n * @param value The offset to set.\n * @return This builder for chaining.\n */\n public Builder setOffset(long value) {\n\n offset_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The row count of the start row. The first row is counted as row 0.\n * When paging, the first request does not specify offset; or equivalently,\n * sets offset to 0; the first request returns the first `limit` of rows. The\n * second request sets offset to the `limit` of the first request; the second\n * request returns the second `limit` of rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 offset = 7;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearOffset() {\n\n offset_ = 0L;\n onChanged();\n return this;\n }\n\n private long limit_;\n /**\n *\n *\n * <pre>\n * The number of rows to return. If unspecified, 10,000 rows are returned. The\n * API returns a maximum of 100,000 rows per request, no matter how many you\n * ask for. `limit` must be positive.\n * The API can also return fewer rows than the requested `limit`, if there\n * aren't as many dimension values as the `limit`. For instance, there are\n * fewer than 300 possible values for the dimension `country`, so when\n * reporting on only `country`, you can't get more than 300 rows, even if you\n * set `limit` to a higher value.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 limit = 8;</code>\n *\n * @return The limit.\n */\n @java.lang.Override\n public long getLimit() {\n return limit_;\n }\n /**\n *\n *\n * <pre>\n * The number of rows to return. If unspecified, 10,000 rows are returned. The\n * API returns a maximum of 100,000 rows per request, no matter how many you\n * ask for. `limit` must be positive.\n * The API can also return fewer rows than the requested `limit`, if there\n * aren't as many dimension values as the `limit`. For instance, there are\n * fewer than 300 possible values for the dimension `country`, so when\n * reporting on only `country`, you can't get more than 300 rows, even if you\n * set `limit` to a higher value.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 limit = 8;</code>\n *\n * @param value The limit to set.\n * @return This builder for chaining.\n */\n public Builder setLimit(long value) {\n\n limit_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The number of rows to return. If unspecified, 10,000 rows are returned. The\n * API returns a maximum of 100,000 rows per request, no matter how many you\n * ask for. `limit` must be positive.\n * The API can also return fewer rows than the requested `limit`, if there\n * aren't as many dimension values as the `limit`. For instance, there are\n * fewer than 300 possible values for the dimension `country`, so when\n * reporting on only `country`, you can't get more than 300 rows, even if you\n * set `limit` to a higher value.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int64 limit = 8;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearLimit() {\n\n limit_ = 0L;\n onChanged();\n return this;\n }\n\n private java.util.List<java.lang.Integer> metricAggregations_ =\n java.util.Collections.emptyList();\n\n private void ensureMetricAggregationsIsMutable() {\n if (!((bitField0_ & 0x00000008) != 0)) {\n metricAggregations_ = new java.util.ArrayList<java.lang.Integer>(metricAggregations_);\n bitField0_ |= 0x00000008;\n }\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @return A list containing the metricAggregations.\n */\n public java.util.List<com.google.analytics.data.v1beta.MetricAggregation>\n getMetricAggregationsList() {\n return new com.google.protobuf.Internal.ListAdapter<\n java.lang.Integer, com.google.analytics.data.v1beta.MetricAggregation>(\n metricAggregations_, metricAggregations_converter_);\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @return The count of metricAggregations.\n */\n public int getMetricAggregationsCount() {\n return metricAggregations_.size();\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param index The index of the element to return.\n * @return The metricAggregations at the given index.\n */\n public com.google.analytics.data.v1beta.MetricAggregation getMetricAggregations(int index) {\n return metricAggregations_converter_.convert(metricAggregations_.get(index));\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param index The index to set the value at.\n * @param value The metricAggregations to set.\n * @return This builder for chaining.\n */\n public Builder setMetricAggregations(\n int index, com.google.analytics.data.v1beta.MetricAggregation value) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricAggregationsIsMutable();\n metricAggregations_.set(index, value.getNumber());\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param value The metricAggregations to add.\n * @return This builder for chaining.\n */\n public Builder addMetricAggregations(com.google.analytics.data.v1beta.MetricAggregation value) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricAggregationsIsMutable();\n metricAggregations_.add(value.getNumber());\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param values The metricAggregations to add.\n * @return This builder for chaining.\n */\n public Builder addAllMetricAggregations(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.MetricAggregation> values) {\n ensureMetricAggregationsIsMutable();\n for (com.google.analytics.data.v1beta.MetricAggregation value : values) {\n metricAggregations_.add(value.getNumber());\n }\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @return This builder for chaining.\n */\n public Builder clearMetricAggregations() {\n metricAggregations_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000008);\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @return A list containing the enum numeric values on the wire for metricAggregations.\n */\n public java.util.List<java.lang.Integer> getMetricAggregationsValueList() {\n return java.util.Collections.unmodifiableList(metricAggregations_);\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param index The index of the value to return.\n * @return The enum numeric value on the wire of metricAggregations at the given index.\n */\n public int getMetricAggregationsValue(int index) {\n return metricAggregations_.get(index);\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param index The index of the value to return.\n * @return The enum numeric value on the wire of metricAggregations at the given index.\n * @return This builder for chaining.\n */\n public Builder setMetricAggregationsValue(int index, int value) {\n ensureMetricAggregationsIsMutable();\n metricAggregations_.set(index, value);\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param value The enum numeric value on the wire for metricAggregations to add.\n * @return This builder for chaining.\n */\n public Builder addMetricAggregationsValue(int value) {\n ensureMetricAggregationsIsMutable();\n metricAggregations_.add(value);\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Aggregation of metrics. Aggregated metric values will be shown in rows\n * where the dimension_values are set to \"RESERVED_(MetricAggregation)\".\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricAggregation metric_aggregations = 9;\n * </code>\n *\n * @param values The enum numeric values on the wire for metricAggregations to add.\n * @return This builder for chaining.\n */\n public Builder addAllMetricAggregationsValue(java.lang.Iterable<java.lang.Integer> values) {\n ensureMetricAggregationsIsMutable();\n for (int value : values) {\n metricAggregations_.add(value);\n }\n onChanged();\n return this;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.OrderBy> orderBys_ =\n java.util.Collections.emptyList();\n\n private void ensureOrderBysIsMutable() {\n if (!((bitField0_ & 0x00000010) != 0)) {\n orderBys_ = new java.util.ArrayList<com.google.analytics.data.v1beta.OrderBy>(orderBys_);\n bitField0_ |= 0x00000010;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.OrderBy,\n com.google.analytics.data.v1beta.OrderBy.Builder,\n com.google.analytics.data.v1beta.OrderByOrBuilder>\n orderBysBuilder_;\n\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.OrderBy> getOrderBysList() {\n if (orderBysBuilder_ == null) {\n return java.util.Collections.unmodifiableList(orderBys_);\n } else {\n return orderBysBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public int getOrderBysCount() {\n if (orderBysBuilder_ == null) {\n return orderBys_.size();\n } else {\n return orderBysBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public com.google.analytics.data.v1beta.OrderBy getOrderBys(int index) {\n if (orderBysBuilder_ == null) {\n return orderBys_.get(index);\n } else {\n return orderBysBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder setOrderBys(int index, com.google.analytics.data.v1beta.OrderBy value) {\n if (orderBysBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureOrderBysIsMutable();\n orderBys_.set(index, value);\n onChanged();\n } else {\n orderBysBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder setOrderBys(\n int index, com.google.analytics.data.v1beta.OrderBy.Builder builderForValue) {\n if (orderBysBuilder_ == null) {\n ensureOrderBysIsMutable();\n orderBys_.set(index, builderForValue.build());\n onChanged();\n } else {\n orderBysBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder addOrderBys(com.google.analytics.data.v1beta.OrderBy value) {\n if (orderBysBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureOrderBysIsMutable();\n orderBys_.add(value);\n onChanged();\n } else {\n orderBysBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder addOrderBys(int index, com.google.analytics.data.v1beta.OrderBy value) {\n if (orderBysBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureOrderBysIsMutable();\n orderBys_.add(index, value);\n onChanged();\n } else {\n orderBysBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder addOrderBys(com.google.analytics.data.v1beta.OrderBy.Builder builderForValue) {\n if (orderBysBuilder_ == null) {\n ensureOrderBysIsMutable();\n orderBys_.add(builderForValue.build());\n onChanged();\n } else {\n orderBysBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder addOrderBys(\n int index, com.google.analytics.data.v1beta.OrderBy.Builder builderForValue) {\n if (orderBysBuilder_ == null) {\n ensureOrderBysIsMutable();\n orderBys_.add(index, builderForValue.build());\n onChanged();\n } else {\n orderBysBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder addAllOrderBys(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.OrderBy> values) {\n if (orderBysBuilder_ == null) {\n ensureOrderBysIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, orderBys_);\n onChanged();\n } else {\n orderBysBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder clearOrderBys() {\n if (orderBysBuilder_ == null) {\n orderBys_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000010);\n onChanged();\n } else {\n orderBysBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public Builder removeOrderBys(int index) {\n if (orderBysBuilder_ == null) {\n ensureOrderBysIsMutable();\n orderBys_.remove(index);\n onChanged();\n } else {\n orderBysBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public com.google.analytics.data.v1beta.OrderBy.Builder getOrderBysBuilder(int index) {\n return getOrderBysFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public com.google.analytics.data.v1beta.OrderByOrBuilder getOrderBysOrBuilder(int index) {\n if (orderBysBuilder_ == null) {\n return orderBys_.get(index);\n } else {\n return orderBysBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.OrderByOrBuilder>\n getOrderBysOrBuilderList() {\n if (orderBysBuilder_ != null) {\n return orderBysBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(orderBys_);\n }\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public com.google.analytics.data.v1beta.OrderBy.Builder addOrderBysBuilder() {\n return getOrderBysFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.OrderBy.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public com.google.analytics.data.v1beta.OrderBy.Builder addOrderBysBuilder(int index) {\n return getOrderBysFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.OrderBy.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Specifies how rows are ordered in the response.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.OrderBy order_bys = 10;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.OrderBy.Builder>\n getOrderBysBuilderList() {\n return getOrderBysFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.OrderBy,\n com.google.analytics.data.v1beta.OrderBy.Builder,\n com.google.analytics.data.v1beta.OrderByOrBuilder>\n getOrderBysFieldBuilder() {\n if (orderBysBuilder_ == null) {\n orderBysBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.OrderBy,\n com.google.analytics.data.v1beta.OrderBy.Builder,\n com.google.analytics.data.v1beta.OrderByOrBuilder>(\n orderBys_, ((bitField0_ & 0x00000010) != 0), getParentForChildren(), isClean());\n orderBys_ = null;\n }\n return orderBysBuilder_;\n }\n\n private java.lang.Object currencyCode_ = \"\";\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @return The currencyCode.\n */\n public java.lang.String getCurrencyCode() {\n java.lang.Object ref = currencyCode_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n currencyCode_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @return The bytes for currencyCode.\n */\n public com.google.protobuf.ByteString getCurrencyCodeBytes() {\n java.lang.Object ref = currencyCode_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n currencyCode_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @param value The currencyCode to set.\n * @return This builder for chaining.\n */\n public Builder setCurrencyCode(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n currencyCode_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearCurrencyCode() {\n\n currencyCode_ = getDefaultInstance().getCurrencyCode();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * A currency code in ISO4217 format, such as \"AED\", \"USD\", \"JPY\".\n * If the field is empty, the report uses the property's default currency.\n * </pre>\n *\n * <code>string currency_code = 11;</code>\n *\n * @param value The bytes for currencyCode to set.\n * @return This builder for chaining.\n */\n public Builder setCurrencyCodeBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n currencyCode_ = value;\n onChanged();\n return this;\n }\n\n private com.google.analytics.data.v1beta.CohortSpec cohortSpec_;\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.CohortSpec,\n com.google.analytics.data.v1beta.CohortSpec.Builder,\n com.google.analytics.data.v1beta.CohortSpecOrBuilder>\n cohortSpecBuilder_;\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n *\n * @return Whether the cohortSpec field is set.\n */\n public boolean hasCohortSpec() {\n return cohortSpecBuilder_ != null || cohortSpec_ != null;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n *\n * @return The cohortSpec.\n */\n public com.google.analytics.data.v1beta.CohortSpec getCohortSpec() {\n if (cohortSpecBuilder_ == null) {\n return cohortSpec_ == null\n ? com.google.analytics.data.v1beta.CohortSpec.getDefaultInstance()\n : cohortSpec_;\n } else {\n return cohortSpecBuilder_.getMessage();\n }\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n public Builder setCohortSpec(com.google.analytics.data.v1beta.CohortSpec value) {\n if (cohortSpecBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n cohortSpec_ = value;\n onChanged();\n } else {\n cohortSpecBuilder_.setMessage(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n public Builder setCohortSpec(\n com.google.analytics.data.v1beta.CohortSpec.Builder builderForValue) {\n if (cohortSpecBuilder_ == null) {\n cohortSpec_ = builderForValue.build();\n onChanged();\n } else {\n cohortSpecBuilder_.setMessage(builderForValue.build());\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n public Builder mergeCohortSpec(com.google.analytics.data.v1beta.CohortSpec value) {\n if (cohortSpecBuilder_ == null) {\n if (cohortSpec_ != null) {\n cohortSpec_ =\n com.google.analytics.data.v1beta.CohortSpec.newBuilder(cohortSpec_)\n .mergeFrom(value)\n .buildPartial();\n } else {\n cohortSpec_ = value;\n }\n onChanged();\n } else {\n cohortSpecBuilder_.mergeFrom(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n public Builder clearCohortSpec() {\n if (cohortSpecBuilder_ == null) {\n cohortSpec_ = null;\n onChanged();\n } else {\n cohortSpec_ = null;\n cohortSpecBuilder_ = null;\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n public com.google.analytics.data.v1beta.CohortSpec.Builder getCohortSpecBuilder() {\n\n onChanged();\n return getCohortSpecFieldBuilder().getBuilder();\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n public com.google.analytics.data.v1beta.CohortSpecOrBuilder getCohortSpecOrBuilder() {\n if (cohortSpecBuilder_ != null) {\n return cohortSpecBuilder_.getMessageOrBuilder();\n } else {\n return cohortSpec_ == null\n ? com.google.analytics.data.v1beta.CohortSpec.getDefaultInstance()\n : cohortSpec_;\n }\n }\n /**\n *\n *\n * <pre>\n * Cohort group associated with this request. If there is a cohort group\n * in the request the 'cohort' dimension must be present.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.CohortSpec cohort_spec = 12;</code>\n */\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.CohortSpec,\n com.google.analytics.data.v1beta.CohortSpec.Builder,\n com.google.analytics.data.v1beta.CohortSpecOrBuilder>\n getCohortSpecFieldBuilder() {\n if (cohortSpecBuilder_ == null) {\n cohortSpecBuilder_ =\n new com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.CohortSpec,\n com.google.analytics.data.v1beta.CohortSpec.Builder,\n com.google.analytics.data.v1beta.CohortSpecOrBuilder>(\n getCohortSpec(), getParentForChildren(), isClean());\n cohortSpec_ = null;\n }\n return cohortSpecBuilder_;\n }\n\n private boolean keepEmptyRows_;\n /**\n *\n *\n * <pre>\n * If false or unspecified, each row with all metrics equal to 0 will not be\n * returned. If true, these rows will be returned if they are not separately\n * removed by a filter.\n * </pre>\n *\n * <code>bool keep_empty_rows = 13;</code>\n *\n * @return The keepEmptyRows.\n */\n @java.lang.Override\n public boolean getKeepEmptyRows() {\n return keepEmptyRows_;\n }\n /**\n *\n *\n * <pre>\n * If false or unspecified, each row with all metrics equal to 0 will not be\n * returned. If true, these rows will be returned if they are not separately\n * removed by a filter.\n * </pre>\n *\n * <code>bool keep_empty_rows = 13;</code>\n *\n * @param value The keepEmptyRows to set.\n * @return This builder for chaining.\n */\n public Builder setKeepEmptyRows(boolean value) {\n\n keepEmptyRows_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * If false or unspecified, each row with all metrics equal to 0 will not be\n * returned. If true, these rows will be returned if they are not separately\n * removed by a filter.\n * </pre>\n *\n * <code>bool keep_empty_rows = 13;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearKeepEmptyRows() {\n\n keepEmptyRows_ = false;\n onChanged();\n return this;\n }\n\n private boolean returnPropertyQuota_;\n /**\n *\n *\n * <pre>\n * Toggles whether to return the current state of this Analytics Property's\n * quota. Quota is returned in [PropertyQuota](#PropertyQuota).\n * </pre>\n *\n * <code>bool return_property_quota = 14;</code>\n *\n * @return The returnPropertyQuota.\n */\n @java.lang.Override\n public boolean getReturnPropertyQuota() {\n return returnPropertyQuota_;\n }\n /**\n *\n *\n * <pre>\n * Toggles whether to return the current state of this Analytics Property's\n * quota. Quota is returned in [PropertyQuota](#PropertyQuota).\n * </pre>\n *\n * <code>bool return_property_quota = 14;</code>\n *\n * @param value The returnPropertyQuota to set.\n * @return This builder for chaining.\n */\n public Builder setReturnPropertyQuota(boolean value) {\n\n returnPropertyQuota_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Toggles whether to return the current state of this Analytics Property's\n * quota. Quota is returned in [PropertyQuota](#PropertyQuota).\n * </pre>\n *\n * <code>bool return_property_quota = 14;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearReturnPropertyQuota() {\n\n returnPropertyQuota_ = false;\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.setUnknownFields(unknownFields);\n }\n\n @java.lang.Override\n public final Builder mergeUnknownFields(\n final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.mergeUnknownFields(unknownFields);\n }\n\n // @@protoc_insertion_point(builder_scope:google.analytics.data.v1beta.RunReportRequest)\n }\n\n // @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.RunReportRequest)\n private static final com.google.analytics.data.v1beta.RunReportRequest DEFAULT_INSTANCE;\n\n static {\n DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.RunReportRequest();\n }\n\n public static com.google.analytics.data.v1beta.RunReportRequest getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n private static final com.google.protobuf.Parser<RunReportRequest> PARSER =\n new com.google.protobuf.AbstractParser<RunReportRequest>() {\n @java.lang.Override\n public RunReportRequest parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new RunReportRequest(input, extensionRegistry);\n }\n };\n\n public static com.google.protobuf.Parser<RunReportRequest> parser() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.protobuf.Parser<RunReportRequest> getParserForType() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportRequest getDefaultInstanceForType() {\n return DEFAULT_INSTANCE;\n }\n}", "public final class RunReportResponse extends com.google.protobuf.GeneratedMessageV3\n implements\n // @@protoc_insertion_point(message_implements:google.analytics.data.v1beta.RunReportResponse)\n RunReportResponseOrBuilder {\n private static final long serialVersionUID = 0L;\n // Use RunReportResponse.newBuilder() to construct.\n private RunReportResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {\n super(builder);\n }\n\n private RunReportResponse() {\n dimensionHeaders_ = java.util.Collections.emptyList();\n metricHeaders_ = java.util.Collections.emptyList();\n rows_ = java.util.Collections.emptyList();\n totals_ = java.util.Collections.emptyList();\n maximums_ = java.util.Collections.emptyList();\n minimums_ = java.util.Collections.emptyList();\n kind_ = \"\";\n }\n\n @java.lang.Override\n @SuppressWarnings({\"unused\"})\n protected java.lang.Object newInstance(UnusedPrivateParameter unused) {\n return new RunReportResponse();\n }\n\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet getUnknownFields() {\n return this.unknownFields;\n }\n\n private RunReportResponse(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n this();\n if (extensionRegistry == null) {\n throw new java.lang.NullPointerException();\n }\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n case 10:\n {\n if (!((mutable_bitField0_ & 0x00000001) != 0)) {\n dimensionHeaders_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.DimensionHeader>();\n mutable_bitField0_ |= 0x00000001;\n }\n dimensionHeaders_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.DimensionHeader.parser(),\n extensionRegistry));\n break;\n }\n case 18:\n {\n if (!((mutable_bitField0_ & 0x00000002) != 0)) {\n metricHeaders_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.MetricHeader>();\n mutable_bitField0_ |= 0x00000002;\n }\n metricHeaders_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.MetricHeader.parser(), extensionRegistry));\n break;\n }\n case 26:\n {\n if (!((mutable_bitField0_ & 0x00000004) != 0)) {\n rows_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>();\n mutable_bitField0_ |= 0x00000004;\n }\n rows_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.Row.parser(), extensionRegistry));\n break;\n }\n case 34:\n {\n if (!((mutable_bitField0_ & 0x00000008) != 0)) {\n totals_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>();\n mutable_bitField0_ |= 0x00000008;\n }\n totals_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.Row.parser(), extensionRegistry));\n break;\n }\n case 42:\n {\n if (!((mutable_bitField0_ & 0x00000010) != 0)) {\n maximums_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>();\n mutable_bitField0_ |= 0x00000010;\n }\n maximums_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.Row.parser(), extensionRegistry));\n break;\n }\n case 50:\n {\n if (!((mutable_bitField0_ & 0x00000020) != 0)) {\n minimums_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>();\n mutable_bitField0_ |= 0x00000020;\n }\n minimums_.add(\n input.readMessage(\n com.google.analytics.data.v1beta.Row.parser(), extensionRegistry));\n break;\n }\n case 56:\n {\n rowCount_ = input.readInt32();\n break;\n }\n case 66:\n {\n com.google.analytics.data.v1beta.ResponseMetaData.Builder subBuilder = null;\n if (metadata_ != null) {\n subBuilder = metadata_.toBuilder();\n }\n metadata_ =\n input.readMessage(\n com.google.analytics.data.v1beta.ResponseMetaData.parser(),\n extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(metadata_);\n metadata_ = subBuilder.buildPartial();\n }\n\n break;\n }\n case 74:\n {\n com.google.analytics.data.v1beta.PropertyQuota.Builder subBuilder = null;\n if (propertyQuota_ != null) {\n subBuilder = propertyQuota_.toBuilder();\n }\n propertyQuota_ =\n input.readMessage(\n com.google.analytics.data.v1beta.PropertyQuota.parser(), extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(propertyQuota_);\n propertyQuota_ = subBuilder.buildPartial();\n }\n\n break;\n }\n case 82:\n {\n java.lang.String s = input.readStringRequireUtf8();\n\n kind_ = s;\n break;\n }\n default:\n {\n if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000001) != 0)) {\n dimensionHeaders_ = java.util.Collections.unmodifiableList(dimensionHeaders_);\n }\n if (((mutable_bitField0_ & 0x00000002) != 0)) {\n metricHeaders_ = java.util.Collections.unmodifiableList(metricHeaders_);\n }\n if (((mutable_bitField0_ & 0x00000004) != 0)) {\n rows_ = java.util.Collections.unmodifiableList(rows_);\n }\n if (((mutable_bitField0_ & 0x00000008) != 0)) {\n totals_ = java.util.Collections.unmodifiableList(totals_);\n }\n if (((mutable_bitField0_ & 0x00000010) != 0)) {\n maximums_ = java.util.Collections.unmodifiableList(maximums_);\n }\n if (((mutable_bitField0_ & 0x00000020) != 0)) {\n minimums_ = java.util.Collections.unmodifiableList(minimums_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportResponse_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportResponse_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.RunReportResponse.class,\n com.google.analytics.data.v1beta.RunReportResponse.Builder.class);\n }\n\n public static final int DIMENSION_HEADERS_FIELD_NUMBER = 1;\n private java.util.List<com.google.analytics.data.v1beta.DimensionHeader> dimensionHeaders_;\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.DimensionHeader>\n getDimensionHeadersList() {\n return dimensionHeaders_;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.DimensionHeaderOrBuilder>\n getDimensionHeadersOrBuilderList() {\n return dimensionHeaders_;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n @java.lang.Override\n public int getDimensionHeadersCount() {\n return dimensionHeaders_.size();\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionHeader getDimensionHeaders(int index) {\n return dimensionHeaders_.get(index);\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.DimensionHeaderOrBuilder getDimensionHeadersOrBuilder(\n int index) {\n return dimensionHeaders_.get(index);\n }\n\n public static final int METRIC_HEADERS_FIELD_NUMBER = 2;\n private java.util.List<com.google.analytics.data.v1beta.MetricHeader> metricHeaders_;\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.MetricHeader> getMetricHeadersList() {\n return metricHeaders_;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.MetricHeaderOrBuilder>\n getMetricHeadersOrBuilderList() {\n return metricHeaders_;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n @java.lang.Override\n public int getMetricHeadersCount() {\n return metricHeaders_.size();\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.MetricHeader getMetricHeaders(int index) {\n return metricHeaders_.get(index);\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.MetricHeaderOrBuilder getMetricHeadersOrBuilder(\n int index) {\n return metricHeaders_.get(index);\n }\n\n public static final int ROWS_FIELD_NUMBER = 3;\n private java.util.List<com.google.analytics.data.v1beta.Row> rows_;\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.Row> getRowsList() {\n return rows_;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getRowsOrBuilderList() {\n return rows_;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n @java.lang.Override\n public int getRowsCount() {\n return rows_.size();\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row getRows(int index) {\n return rows_.get(index);\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.RowOrBuilder getRowsOrBuilder(int index) {\n return rows_.get(index);\n }\n\n public static final int TOTALS_FIELD_NUMBER = 4;\n private java.util.List<com.google.analytics.data.v1beta.Row> totals_;\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.Row> getTotalsList() {\n return totals_;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getTotalsOrBuilderList() {\n return totals_;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n @java.lang.Override\n public int getTotalsCount() {\n return totals_.size();\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row getTotals(int index) {\n return totals_.get(index);\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.RowOrBuilder getTotalsOrBuilder(int index) {\n return totals_.get(index);\n }\n\n public static final int MAXIMUMS_FIELD_NUMBER = 5;\n private java.util.List<com.google.analytics.data.v1beta.Row> maximums_;\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.Row> getMaximumsList() {\n return maximums_;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getMaximumsOrBuilderList() {\n return maximums_;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n @java.lang.Override\n public int getMaximumsCount() {\n return maximums_.size();\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row getMaximums(int index) {\n return maximums_.get(index);\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.RowOrBuilder getMaximumsOrBuilder(int index) {\n return maximums_.get(index);\n }\n\n public static final int MINIMUMS_FIELD_NUMBER = 6;\n private java.util.List<com.google.analytics.data.v1beta.Row> minimums_;\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n @java.lang.Override\n public java.util.List<com.google.analytics.data.v1beta.Row> getMinimumsList() {\n return minimums_;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n @java.lang.Override\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getMinimumsOrBuilderList() {\n return minimums_;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n @java.lang.Override\n public int getMinimumsCount() {\n return minimums_.size();\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.Row getMinimums(int index) {\n return minimums_.get(index);\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.RowOrBuilder getMinimumsOrBuilder(int index) {\n return minimums_.get(index);\n }\n\n public static final int ROW_COUNT_FIELD_NUMBER = 7;\n private int rowCount_;\n /**\n *\n *\n * <pre>\n * The total number of rows in the query result. `rowCount` is independent of\n * the number of rows returned in the response, the `limit` request\n * parameter, and the `offset` request parameter. For example if a query\n * returns 175 rows and includes `limit` of 50 in the API request, the\n * response will contain `rowCount` of 175 but only 50 rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int32 row_count = 7;</code>\n *\n * @return The rowCount.\n */\n @java.lang.Override\n public int getRowCount() {\n return rowCount_;\n }\n\n public static final int METADATA_FIELD_NUMBER = 8;\n private com.google.analytics.data.v1beta.ResponseMetaData metadata_;\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n *\n * @return Whether the metadata field is set.\n */\n @java.lang.Override\n public boolean hasMetadata() {\n return metadata_ != null;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n *\n * @return The metadata.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.ResponseMetaData getMetadata() {\n return metadata_ == null\n ? com.google.analytics.data.v1beta.ResponseMetaData.getDefaultInstance()\n : metadata_;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.ResponseMetaDataOrBuilder getMetadataOrBuilder() {\n return getMetadata();\n }\n\n public static final int PROPERTY_QUOTA_FIELD_NUMBER = 9;\n private com.google.analytics.data.v1beta.PropertyQuota propertyQuota_;\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n *\n * @return Whether the propertyQuota field is set.\n */\n @java.lang.Override\n public boolean hasPropertyQuota() {\n return propertyQuota_ != null;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n *\n * @return The propertyQuota.\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.PropertyQuota getPropertyQuota() {\n return propertyQuota_ == null\n ? com.google.analytics.data.v1beta.PropertyQuota.getDefaultInstance()\n : propertyQuota_;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n @java.lang.Override\n public com.google.analytics.data.v1beta.PropertyQuotaOrBuilder getPropertyQuotaOrBuilder() {\n return getPropertyQuota();\n }\n\n public static final int KIND_FIELD_NUMBER = 10;\n private volatile java.lang.Object kind_;\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @return The kind.\n */\n @java.lang.Override\n public java.lang.String getKind() {\n java.lang.Object ref = kind_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n kind_ = s;\n return s;\n }\n }\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @return The bytes for kind.\n */\n @java.lang.Override\n public com.google.protobuf.ByteString getKindBytes() {\n java.lang.Object ref = kind_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n kind_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n private byte memoizedIsInitialized = -1;\n\n @java.lang.Override\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized == 1) return true;\n if (isInitialized == 0) return false;\n\n memoizedIsInitialized = 1;\n return true;\n }\n\n @java.lang.Override\n public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {\n for (int i = 0; i < dimensionHeaders_.size(); i++) {\n output.writeMessage(1, dimensionHeaders_.get(i));\n }\n for (int i = 0; i < metricHeaders_.size(); i++) {\n output.writeMessage(2, metricHeaders_.get(i));\n }\n for (int i = 0; i < rows_.size(); i++) {\n output.writeMessage(3, rows_.get(i));\n }\n for (int i = 0; i < totals_.size(); i++) {\n output.writeMessage(4, totals_.get(i));\n }\n for (int i = 0; i < maximums_.size(); i++) {\n output.writeMessage(5, maximums_.get(i));\n }\n for (int i = 0; i < minimums_.size(); i++) {\n output.writeMessage(6, minimums_.get(i));\n }\n if (rowCount_ != 0) {\n output.writeInt32(7, rowCount_);\n }\n if (metadata_ != null) {\n output.writeMessage(8, getMetadata());\n }\n if (propertyQuota_ != null) {\n output.writeMessage(9, getPropertyQuota());\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kind_)) {\n com.google.protobuf.GeneratedMessageV3.writeString(output, 10, kind_);\n }\n unknownFields.writeTo(output);\n }\n\n @java.lang.Override\n public int getSerializedSize() {\n int size = memoizedSize;\n if (size != -1) return size;\n\n size = 0;\n for (int i = 0; i < dimensionHeaders_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dimensionHeaders_.get(i));\n }\n for (int i = 0; i < metricHeaders_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, metricHeaders_.get(i));\n }\n for (int i = 0; i < rows_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, rows_.get(i));\n }\n for (int i = 0; i < totals_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, totals_.get(i));\n }\n for (int i = 0; i < maximums_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, maximums_.get(i));\n }\n for (int i = 0; i < minimums_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, minimums_.get(i));\n }\n if (rowCount_ != 0) {\n size += com.google.protobuf.CodedOutputStream.computeInt32Size(7, rowCount_);\n }\n if (metadata_ != null) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(8, getMetadata());\n }\n if (propertyQuota_ != null) {\n size += com.google.protobuf.CodedOutputStream.computeMessageSize(9, getPropertyQuota());\n }\n if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(kind_)) {\n size += com.google.protobuf.GeneratedMessageV3.computeStringSize(10, kind_);\n }\n size += unknownFields.getSerializedSize();\n memoizedSize = size;\n return size;\n }\n\n @java.lang.Override\n public boolean equals(final java.lang.Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof com.google.analytics.data.v1beta.RunReportResponse)) {\n return super.equals(obj);\n }\n com.google.analytics.data.v1beta.RunReportResponse other =\n (com.google.analytics.data.v1beta.RunReportResponse) obj;\n\n if (!getDimensionHeadersList().equals(other.getDimensionHeadersList())) return false;\n if (!getMetricHeadersList().equals(other.getMetricHeadersList())) return false;\n if (!getRowsList().equals(other.getRowsList())) return false;\n if (!getTotalsList().equals(other.getTotalsList())) return false;\n if (!getMaximumsList().equals(other.getMaximumsList())) return false;\n if (!getMinimumsList().equals(other.getMinimumsList())) return false;\n if (getRowCount() != other.getRowCount()) return false;\n if (hasMetadata() != other.hasMetadata()) return false;\n if (hasMetadata()) {\n if (!getMetadata().equals(other.getMetadata())) return false;\n }\n if (hasPropertyQuota() != other.hasPropertyQuota()) return false;\n if (hasPropertyQuota()) {\n if (!getPropertyQuota().equals(other.getPropertyQuota())) return false;\n }\n if (!getKind().equals(other.getKind())) return false;\n if (!unknownFields.equals(other.unknownFields)) return false;\n return true;\n }\n\n @java.lang.Override\n public int hashCode() {\n if (memoizedHashCode != 0) {\n return memoizedHashCode;\n }\n int hash = 41;\n hash = (19 * hash) + getDescriptor().hashCode();\n if (getDimensionHeadersCount() > 0) {\n hash = (37 * hash) + DIMENSION_HEADERS_FIELD_NUMBER;\n hash = (53 * hash) + getDimensionHeadersList().hashCode();\n }\n if (getMetricHeadersCount() > 0) {\n hash = (37 * hash) + METRIC_HEADERS_FIELD_NUMBER;\n hash = (53 * hash) + getMetricHeadersList().hashCode();\n }\n if (getRowsCount() > 0) {\n hash = (37 * hash) + ROWS_FIELD_NUMBER;\n hash = (53 * hash) + getRowsList().hashCode();\n }\n if (getTotalsCount() > 0) {\n hash = (37 * hash) + TOTALS_FIELD_NUMBER;\n hash = (53 * hash) + getTotalsList().hashCode();\n }\n if (getMaximumsCount() > 0) {\n hash = (37 * hash) + MAXIMUMS_FIELD_NUMBER;\n hash = (53 * hash) + getMaximumsList().hashCode();\n }\n if (getMinimumsCount() > 0) {\n hash = (37 * hash) + MINIMUMS_FIELD_NUMBER;\n hash = (53 * hash) + getMinimumsList().hashCode();\n }\n hash = (37 * hash) + ROW_COUNT_FIELD_NUMBER;\n hash = (53 * hash) + getRowCount();\n if (hasMetadata()) {\n hash = (37 * hash) + METADATA_FIELD_NUMBER;\n hash = (53 * hash) + getMetadata().hashCode();\n }\n if (hasPropertyQuota()) {\n hash = (37 * hash) + PROPERTY_QUOTA_FIELD_NUMBER;\n hash = (53 * hash) + getPropertyQuota().hashCode();\n }\n hash = (37 * hash) + KIND_FIELD_NUMBER;\n hash = (53 * hash) + getKind().hashCode();\n hash = (29 * hash) + unknownFields.hashCode();\n memoizedHashCode = hash;\n return hash;\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseDelimitedFrom(\n java.io.InputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseDelimitedFrom(\n java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n com.google.protobuf.CodedInputStream input) throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return com.google.protobuf.GeneratedMessageV3.parseWithIOException(\n PARSER, input, extensionRegistry);\n }\n\n @java.lang.Override\n public Builder newBuilderForType() {\n return newBuilder();\n }\n\n public static Builder newBuilder() {\n return DEFAULT_INSTANCE.toBuilder();\n }\n\n public static Builder newBuilder(com.google.analytics.data.v1beta.RunReportResponse prototype) {\n return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n }\n\n @java.lang.Override\n public Builder toBuilder() {\n return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);\n }\n\n @java.lang.Override\n protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n *\n *\n * <pre>\n * The response report table corresponding to a request.\n * </pre>\n *\n * Protobuf type {@code google.analytics.data.v1beta.RunReportResponse}\n */\n public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>\n implements\n // @@protoc_insertion_point(builder_implements:google.analytics.data.v1beta.RunReportResponse)\n com.google.analytics.data.v1beta.RunReportResponseOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportResponse_descriptor;\n }\n\n @java.lang.Override\n protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportResponse_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n com.google.analytics.data.v1beta.RunReportResponse.class,\n com.google.analytics.data.v1beta.RunReportResponse.Builder.class);\n }\n\n // Construct using com.google.analytics.data.v1beta.RunReportResponse.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {\n getDimensionHeadersFieldBuilder();\n getMetricHeadersFieldBuilder();\n getRowsFieldBuilder();\n getTotalsFieldBuilder();\n getMaximumsFieldBuilder();\n getMinimumsFieldBuilder();\n }\n }\n\n @java.lang.Override\n public Builder clear() {\n super.clear();\n if (dimensionHeadersBuilder_ == null) {\n dimensionHeaders_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n dimensionHeadersBuilder_.clear();\n }\n if (metricHeadersBuilder_ == null) {\n metricHeaders_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000002);\n } else {\n metricHeadersBuilder_.clear();\n }\n if (rowsBuilder_ == null) {\n rows_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000004);\n } else {\n rowsBuilder_.clear();\n }\n if (totalsBuilder_ == null) {\n totals_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000008);\n } else {\n totalsBuilder_.clear();\n }\n if (maximumsBuilder_ == null) {\n maximums_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000010);\n } else {\n maximumsBuilder_.clear();\n }\n if (minimumsBuilder_ == null) {\n minimums_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n minimumsBuilder_.clear();\n }\n rowCount_ = 0;\n\n if (metadataBuilder_ == null) {\n metadata_ = null;\n } else {\n metadata_ = null;\n metadataBuilder_ = null;\n }\n if (propertyQuotaBuilder_ == null) {\n propertyQuota_ = null;\n } else {\n propertyQuota_ = null;\n propertyQuotaBuilder_ = null;\n }\n kind_ = \"\";\n\n return this;\n }\n\n @java.lang.Override\n public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {\n return com.google.analytics.data.v1beta.AnalyticsDataApiProto\n .internal_static_google_analytics_data_v1beta_RunReportResponse_descriptor;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportResponse getDefaultInstanceForType() {\n return com.google.analytics.data.v1beta.RunReportResponse.getDefaultInstance();\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportResponse build() {\n com.google.analytics.data.v1beta.RunReportResponse result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportResponse buildPartial() {\n com.google.analytics.data.v1beta.RunReportResponse result =\n new com.google.analytics.data.v1beta.RunReportResponse(this);\n int from_bitField0_ = bitField0_;\n if (dimensionHeadersBuilder_ == null) {\n if (((bitField0_ & 0x00000001) != 0)) {\n dimensionHeaders_ = java.util.Collections.unmodifiableList(dimensionHeaders_);\n bitField0_ = (bitField0_ & ~0x00000001);\n }\n result.dimensionHeaders_ = dimensionHeaders_;\n } else {\n result.dimensionHeaders_ = dimensionHeadersBuilder_.build();\n }\n if (metricHeadersBuilder_ == null) {\n if (((bitField0_ & 0x00000002) != 0)) {\n metricHeaders_ = java.util.Collections.unmodifiableList(metricHeaders_);\n bitField0_ = (bitField0_ & ~0x00000002);\n }\n result.metricHeaders_ = metricHeaders_;\n } else {\n result.metricHeaders_ = metricHeadersBuilder_.build();\n }\n if (rowsBuilder_ == null) {\n if (((bitField0_ & 0x00000004) != 0)) {\n rows_ = java.util.Collections.unmodifiableList(rows_);\n bitField0_ = (bitField0_ & ~0x00000004);\n }\n result.rows_ = rows_;\n } else {\n result.rows_ = rowsBuilder_.build();\n }\n if (totalsBuilder_ == null) {\n if (((bitField0_ & 0x00000008) != 0)) {\n totals_ = java.util.Collections.unmodifiableList(totals_);\n bitField0_ = (bitField0_ & ~0x00000008);\n }\n result.totals_ = totals_;\n } else {\n result.totals_ = totalsBuilder_.build();\n }\n if (maximumsBuilder_ == null) {\n if (((bitField0_ & 0x00000010) != 0)) {\n maximums_ = java.util.Collections.unmodifiableList(maximums_);\n bitField0_ = (bitField0_ & ~0x00000010);\n }\n result.maximums_ = maximums_;\n } else {\n result.maximums_ = maximumsBuilder_.build();\n }\n if (minimumsBuilder_ == null) {\n if (((bitField0_ & 0x00000020) != 0)) {\n minimums_ = java.util.Collections.unmodifiableList(minimums_);\n bitField0_ = (bitField0_ & ~0x00000020);\n }\n result.minimums_ = minimums_;\n } else {\n result.minimums_ = minimumsBuilder_.build();\n }\n result.rowCount_ = rowCount_;\n if (metadataBuilder_ == null) {\n result.metadata_ = metadata_;\n } else {\n result.metadata_ = metadataBuilder_.build();\n }\n if (propertyQuotaBuilder_ == null) {\n result.propertyQuota_ = propertyQuota_;\n } else {\n result.propertyQuota_ = propertyQuotaBuilder_.build();\n }\n result.kind_ = kind_;\n onBuilt();\n return result;\n }\n\n @java.lang.Override\n public Builder clone() {\n return super.clone();\n }\n\n @java.lang.Override\n public Builder setField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.setField(field, value);\n }\n\n @java.lang.Override\n public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {\n return super.clearField(field);\n }\n\n @java.lang.Override\n public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n return super.clearOneof(oneof);\n }\n\n @java.lang.Override\n public Builder setRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {\n return super.setRepeatedField(field, index, value);\n }\n\n @java.lang.Override\n public Builder addRepeatedField(\n com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {\n return super.addRepeatedField(field, value);\n }\n\n @java.lang.Override\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof com.google.analytics.data.v1beta.RunReportResponse) {\n return mergeFrom((com.google.analytics.data.v1beta.RunReportResponse) other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(com.google.analytics.data.v1beta.RunReportResponse other) {\n if (other == com.google.analytics.data.v1beta.RunReportResponse.getDefaultInstance())\n return this;\n if (dimensionHeadersBuilder_ == null) {\n if (!other.dimensionHeaders_.isEmpty()) {\n if (dimensionHeaders_.isEmpty()) {\n dimensionHeaders_ = other.dimensionHeaders_;\n bitField0_ = (bitField0_ & ~0x00000001);\n } else {\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.addAll(other.dimensionHeaders_);\n }\n onChanged();\n }\n } else {\n if (!other.dimensionHeaders_.isEmpty()) {\n if (dimensionHeadersBuilder_.isEmpty()) {\n dimensionHeadersBuilder_.dispose();\n dimensionHeadersBuilder_ = null;\n dimensionHeaders_ = other.dimensionHeaders_;\n bitField0_ = (bitField0_ & ~0x00000001);\n dimensionHeadersBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getDimensionHeadersFieldBuilder()\n : null;\n } else {\n dimensionHeadersBuilder_.addAllMessages(other.dimensionHeaders_);\n }\n }\n }\n if (metricHeadersBuilder_ == null) {\n if (!other.metricHeaders_.isEmpty()) {\n if (metricHeaders_.isEmpty()) {\n metricHeaders_ = other.metricHeaders_;\n bitField0_ = (bitField0_ & ~0x00000002);\n } else {\n ensureMetricHeadersIsMutable();\n metricHeaders_.addAll(other.metricHeaders_);\n }\n onChanged();\n }\n } else {\n if (!other.metricHeaders_.isEmpty()) {\n if (metricHeadersBuilder_.isEmpty()) {\n metricHeadersBuilder_.dispose();\n metricHeadersBuilder_ = null;\n metricHeaders_ = other.metricHeaders_;\n bitField0_ = (bitField0_ & ~0x00000002);\n metricHeadersBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getMetricHeadersFieldBuilder()\n : null;\n } else {\n metricHeadersBuilder_.addAllMessages(other.metricHeaders_);\n }\n }\n }\n if (rowsBuilder_ == null) {\n if (!other.rows_.isEmpty()) {\n if (rows_.isEmpty()) {\n rows_ = other.rows_;\n bitField0_ = (bitField0_ & ~0x00000004);\n } else {\n ensureRowsIsMutable();\n rows_.addAll(other.rows_);\n }\n onChanged();\n }\n } else {\n if (!other.rows_.isEmpty()) {\n if (rowsBuilder_.isEmpty()) {\n rowsBuilder_.dispose();\n rowsBuilder_ = null;\n rows_ = other.rows_;\n bitField0_ = (bitField0_ & ~0x00000004);\n rowsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getRowsFieldBuilder()\n : null;\n } else {\n rowsBuilder_.addAllMessages(other.rows_);\n }\n }\n }\n if (totalsBuilder_ == null) {\n if (!other.totals_.isEmpty()) {\n if (totals_.isEmpty()) {\n totals_ = other.totals_;\n bitField0_ = (bitField0_ & ~0x00000008);\n } else {\n ensureTotalsIsMutable();\n totals_.addAll(other.totals_);\n }\n onChanged();\n }\n } else {\n if (!other.totals_.isEmpty()) {\n if (totalsBuilder_.isEmpty()) {\n totalsBuilder_.dispose();\n totalsBuilder_ = null;\n totals_ = other.totals_;\n bitField0_ = (bitField0_ & ~0x00000008);\n totalsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getTotalsFieldBuilder()\n : null;\n } else {\n totalsBuilder_.addAllMessages(other.totals_);\n }\n }\n }\n if (maximumsBuilder_ == null) {\n if (!other.maximums_.isEmpty()) {\n if (maximums_.isEmpty()) {\n maximums_ = other.maximums_;\n bitField0_ = (bitField0_ & ~0x00000010);\n } else {\n ensureMaximumsIsMutable();\n maximums_.addAll(other.maximums_);\n }\n onChanged();\n }\n } else {\n if (!other.maximums_.isEmpty()) {\n if (maximumsBuilder_.isEmpty()) {\n maximumsBuilder_.dispose();\n maximumsBuilder_ = null;\n maximums_ = other.maximums_;\n bitField0_ = (bitField0_ & ~0x00000010);\n maximumsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getMaximumsFieldBuilder()\n : null;\n } else {\n maximumsBuilder_.addAllMessages(other.maximums_);\n }\n }\n }\n if (minimumsBuilder_ == null) {\n if (!other.minimums_.isEmpty()) {\n if (minimums_.isEmpty()) {\n minimums_ = other.minimums_;\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n ensureMinimumsIsMutable();\n minimums_.addAll(other.minimums_);\n }\n onChanged();\n }\n } else {\n if (!other.minimums_.isEmpty()) {\n if (minimumsBuilder_.isEmpty()) {\n minimumsBuilder_.dispose();\n minimumsBuilder_ = null;\n minimums_ = other.minimums_;\n bitField0_ = (bitField0_ & ~0x00000020);\n minimumsBuilder_ =\n com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders\n ? getMinimumsFieldBuilder()\n : null;\n } else {\n minimumsBuilder_.addAllMessages(other.minimums_);\n }\n }\n }\n if (other.getRowCount() != 0) {\n setRowCount(other.getRowCount());\n }\n if (other.hasMetadata()) {\n mergeMetadata(other.getMetadata());\n }\n if (other.hasPropertyQuota()) {\n mergePropertyQuota(other.getPropertyQuota());\n }\n if (!other.getKind().isEmpty()) {\n kind_ = other.kind_;\n onChanged();\n }\n this.mergeUnknownFields(other.unknownFields);\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final boolean isInitialized() {\n return true;\n }\n\n @java.lang.Override\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n com.google.analytics.data.v1beta.RunReportResponse parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage =\n (com.google.analytics.data.v1beta.RunReportResponse) e.getUnfinishedMessage();\n throw e.unwrapIOException();\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n\n private int bitField0_;\n\n private java.util.List<com.google.analytics.data.v1beta.DimensionHeader> dimensionHeaders_ =\n java.util.Collections.emptyList();\n\n private void ensureDimensionHeadersIsMutable() {\n if (!((bitField0_ & 0x00000001) != 0)) {\n dimensionHeaders_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.DimensionHeader>(\n dimensionHeaders_);\n bitField0_ |= 0x00000001;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionHeader,\n com.google.analytics.data.v1beta.DimensionHeader.Builder,\n com.google.analytics.data.v1beta.DimensionHeaderOrBuilder>\n dimensionHeadersBuilder_;\n\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.DimensionHeader>\n getDimensionHeadersList() {\n if (dimensionHeadersBuilder_ == null) {\n return java.util.Collections.unmodifiableList(dimensionHeaders_);\n } else {\n return dimensionHeadersBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public int getDimensionHeadersCount() {\n if (dimensionHeadersBuilder_ == null) {\n return dimensionHeaders_.size();\n } else {\n return dimensionHeadersBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionHeader getDimensionHeaders(int index) {\n if (dimensionHeadersBuilder_ == null) {\n return dimensionHeaders_.get(index);\n } else {\n return dimensionHeadersBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder setDimensionHeaders(\n int index, com.google.analytics.data.v1beta.DimensionHeader value) {\n if (dimensionHeadersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.set(index, value);\n onChanged();\n } else {\n dimensionHeadersBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder setDimensionHeaders(\n int index, com.google.analytics.data.v1beta.DimensionHeader.Builder builderForValue) {\n if (dimensionHeadersBuilder_ == null) {\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.set(index, builderForValue.build());\n onChanged();\n } else {\n dimensionHeadersBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder addDimensionHeaders(com.google.analytics.data.v1beta.DimensionHeader value) {\n if (dimensionHeadersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.add(value);\n onChanged();\n } else {\n dimensionHeadersBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder addDimensionHeaders(\n int index, com.google.analytics.data.v1beta.DimensionHeader value) {\n if (dimensionHeadersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.add(index, value);\n onChanged();\n } else {\n dimensionHeadersBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder addDimensionHeaders(\n com.google.analytics.data.v1beta.DimensionHeader.Builder builderForValue) {\n if (dimensionHeadersBuilder_ == null) {\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.add(builderForValue.build());\n onChanged();\n } else {\n dimensionHeadersBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder addDimensionHeaders(\n int index, com.google.analytics.data.v1beta.DimensionHeader.Builder builderForValue) {\n if (dimensionHeadersBuilder_ == null) {\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.add(index, builderForValue.build());\n onChanged();\n } else {\n dimensionHeadersBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder addAllDimensionHeaders(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.DimensionHeader> values) {\n if (dimensionHeadersBuilder_ == null) {\n ensureDimensionHeadersIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dimensionHeaders_);\n onChanged();\n } else {\n dimensionHeadersBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder clearDimensionHeaders() {\n if (dimensionHeadersBuilder_ == null) {\n dimensionHeaders_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000001);\n onChanged();\n } else {\n dimensionHeadersBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public Builder removeDimensionHeaders(int index) {\n if (dimensionHeadersBuilder_ == null) {\n ensureDimensionHeadersIsMutable();\n dimensionHeaders_.remove(index);\n onChanged();\n } else {\n dimensionHeadersBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionHeader.Builder getDimensionHeadersBuilder(\n int index) {\n return getDimensionHeadersFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionHeaderOrBuilder getDimensionHeadersOrBuilder(\n int index) {\n if (dimensionHeadersBuilder_ == null) {\n return dimensionHeaders_.get(index);\n } else {\n return dimensionHeadersBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.DimensionHeaderOrBuilder>\n getDimensionHeadersOrBuilderList() {\n if (dimensionHeadersBuilder_ != null) {\n return dimensionHeadersBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(dimensionHeaders_);\n }\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionHeader.Builder addDimensionHeadersBuilder() {\n return getDimensionHeadersFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.DimensionHeader.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public com.google.analytics.data.v1beta.DimensionHeader.Builder addDimensionHeadersBuilder(\n int index) {\n return getDimensionHeadersFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.DimensionHeader.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Describes dimension columns. The number of DimensionHeaders and ordering of\n * DimensionHeaders matches the dimensions present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.DimensionHeader dimension_headers = 1;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.DimensionHeader.Builder>\n getDimensionHeadersBuilderList() {\n return getDimensionHeadersFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionHeader,\n com.google.analytics.data.v1beta.DimensionHeader.Builder,\n com.google.analytics.data.v1beta.DimensionHeaderOrBuilder>\n getDimensionHeadersFieldBuilder() {\n if (dimensionHeadersBuilder_ == null) {\n dimensionHeadersBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.DimensionHeader,\n com.google.analytics.data.v1beta.DimensionHeader.Builder,\n com.google.analytics.data.v1beta.DimensionHeaderOrBuilder>(\n dimensionHeaders_,\n ((bitField0_ & 0x00000001) != 0),\n getParentForChildren(),\n isClean());\n dimensionHeaders_ = null;\n }\n return dimensionHeadersBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.MetricHeader> metricHeaders_ =\n java.util.Collections.emptyList();\n\n private void ensureMetricHeadersIsMutable() {\n if (!((bitField0_ & 0x00000002) != 0)) {\n metricHeaders_ =\n new java.util.ArrayList<com.google.analytics.data.v1beta.MetricHeader>(metricHeaders_);\n bitField0_ |= 0x00000002;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.MetricHeader,\n com.google.analytics.data.v1beta.MetricHeader.Builder,\n com.google.analytics.data.v1beta.MetricHeaderOrBuilder>\n metricHeadersBuilder_;\n\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.MetricHeader> getMetricHeadersList() {\n if (metricHeadersBuilder_ == null) {\n return java.util.Collections.unmodifiableList(metricHeaders_);\n } else {\n return metricHeadersBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public int getMetricHeadersCount() {\n if (metricHeadersBuilder_ == null) {\n return metricHeaders_.size();\n } else {\n return metricHeadersBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricHeader getMetricHeaders(int index) {\n if (metricHeadersBuilder_ == null) {\n return metricHeaders_.get(index);\n } else {\n return metricHeadersBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder setMetricHeaders(\n int index, com.google.analytics.data.v1beta.MetricHeader value) {\n if (metricHeadersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricHeadersIsMutable();\n metricHeaders_.set(index, value);\n onChanged();\n } else {\n metricHeadersBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder setMetricHeaders(\n int index, com.google.analytics.data.v1beta.MetricHeader.Builder builderForValue) {\n if (metricHeadersBuilder_ == null) {\n ensureMetricHeadersIsMutable();\n metricHeaders_.set(index, builderForValue.build());\n onChanged();\n } else {\n metricHeadersBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder addMetricHeaders(com.google.analytics.data.v1beta.MetricHeader value) {\n if (metricHeadersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricHeadersIsMutable();\n metricHeaders_.add(value);\n onChanged();\n } else {\n metricHeadersBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder addMetricHeaders(\n int index, com.google.analytics.data.v1beta.MetricHeader value) {\n if (metricHeadersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMetricHeadersIsMutable();\n metricHeaders_.add(index, value);\n onChanged();\n } else {\n metricHeadersBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder addMetricHeaders(\n com.google.analytics.data.v1beta.MetricHeader.Builder builderForValue) {\n if (metricHeadersBuilder_ == null) {\n ensureMetricHeadersIsMutable();\n metricHeaders_.add(builderForValue.build());\n onChanged();\n } else {\n metricHeadersBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder addMetricHeaders(\n int index, com.google.analytics.data.v1beta.MetricHeader.Builder builderForValue) {\n if (metricHeadersBuilder_ == null) {\n ensureMetricHeadersIsMutable();\n metricHeaders_.add(index, builderForValue.build());\n onChanged();\n } else {\n metricHeadersBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder addAllMetricHeaders(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.MetricHeader> values) {\n if (metricHeadersBuilder_ == null) {\n ensureMetricHeadersIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, metricHeaders_);\n onChanged();\n } else {\n metricHeadersBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder clearMetricHeaders() {\n if (metricHeadersBuilder_ == null) {\n metricHeaders_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000002);\n onChanged();\n } else {\n metricHeadersBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public Builder removeMetricHeaders(int index) {\n if (metricHeadersBuilder_ == null) {\n ensureMetricHeadersIsMutable();\n metricHeaders_.remove(index);\n onChanged();\n } else {\n metricHeadersBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricHeader.Builder getMetricHeadersBuilder(\n int index) {\n return getMetricHeadersFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricHeaderOrBuilder getMetricHeadersOrBuilder(\n int index) {\n if (metricHeadersBuilder_ == null) {\n return metricHeaders_.get(index);\n } else {\n return metricHeadersBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.MetricHeaderOrBuilder>\n getMetricHeadersOrBuilderList() {\n if (metricHeadersBuilder_ != null) {\n return metricHeadersBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(metricHeaders_);\n }\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricHeader.Builder addMetricHeadersBuilder() {\n return getMetricHeadersFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.MetricHeader.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public com.google.analytics.data.v1beta.MetricHeader.Builder addMetricHeadersBuilder(\n int index) {\n return getMetricHeadersFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.MetricHeader.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Describes metric columns. The number of MetricHeaders and ordering of\n * MetricHeaders matches the metrics present in rows.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.MetricHeader metric_headers = 2;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.MetricHeader.Builder>\n getMetricHeadersBuilderList() {\n return getMetricHeadersFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.MetricHeader,\n com.google.analytics.data.v1beta.MetricHeader.Builder,\n com.google.analytics.data.v1beta.MetricHeaderOrBuilder>\n getMetricHeadersFieldBuilder() {\n if (metricHeadersBuilder_ == null) {\n metricHeadersBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.MetricHeader,\n com.google.analytics.data.v1beta.MetricHeader.Builder,\n com.google.analytics.data.v1beta.MetricHeaderOrBuilder>(\n metricHeaders_,\n ((bitField0_ & 0x00000002) != 0),\n getParentForChildren(),\n isClean());\n metricHeaders_ = null;\n }\n return metricHeadersBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.Row> rows_ =\n java.util.Collections.emptyList();\n\n private void ensureRowsIsMutable() {\n if (!((bitField0_ & 0x00000004) != 0)) {\n rows_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>(rows_);\n bitField0_ |= 0x00000004;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n rowsBuilder_;\n\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row> getRowsList() {\n if (rowsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(rows_);\n } else {\n return rowsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public int getRowsCount() {\n if (rowsBuilder_ == null) {\n return rows_.size();\n } else {\n return rowsBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public com.google.analytics.data.v1beta.Row getRows(int index) {\n if (rowsBuilder_ == null) {\n return rows_.get(index);\n } else {\n return rowsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder setRows(int index, com.google.analytics.data.v1beta.Row value) {\n if (rowsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureRowsIsMutable();\n rows_.set(index, value);\n onChanged();\n } else {\n rowsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder setRows(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (rowsBuilder_ == null) {\n ensureRowsIsMutable();\n rows_.set(index, builderForValue.build());\n onChanged();\n } else {\n rowsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder addRows(com.google.analytics.data.v1beta.Row value) {\n if (rowsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureRowsIsMutable();\n rows_.add(value);\n onChanged();\n } else {\n rowsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder addRows(int index, com.google.analytics.data.v1beta.Row value) {\n if (rowsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureRowsIsMutable();\n rows_.add(index, value);\n onChanged();\n } else {\n rowsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder addRows(com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (rowsBuilder_ == null) {\n ensureRowsIsMutable();\n rows_.add(builderForValue.build());\n onChanged();\n } else {\n rowsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder addRows(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (rowsBuilder_ == null) {\n ensureRowsIsMutable();\n rows_.add(index, builderForValue.build());\n onChanged();\n } else {\n rowsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder addAllRows(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.Row> values) {\n if (rowsBuilder_ == null) {\n ensureRowsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, rows_);\n onChanged();\n } else {\n rowsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder clearRows() {\n if (rowsBuilder_ == null) {\n rows_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000004);\n onChanged();\n } else {\n rowsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public Builder removeRows(int index) {\n if (rowsBuilder_ == null) {\n ensureRowsIsMutable();\n rows_.remove(index);\n onChanged();\n } else {\n rowsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder getRowsBuilder(int index) {\n return getRowsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public com.google.analytics.data.v1beta.RowOrBuilder getRowsOrBuilder(int index) {\n if (rowsBuilder_ == null) {\n return rows_.get(index);\n } else {\n return rowsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getRowsOrBuilderList() {\n if (rowsBuilder_ != null) {\n return rowsBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(rows_);\n }\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addRowsBuilder() {\n return getRowsFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addRowsBuilder(int index) {\n return getRowsFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * Rows of dimension value combinations and metric values in the report.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row rows = 3;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row.Builder> getRowsBuilderList() {\n return getRowsFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n getRowsFieldBuilder() {\n if (rowsBuilder_ == null) {\n rowsBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>(\n rows_, ((bitField0_ & 0x00000004) != 0), getParentForChildren(), isClean());\n rows_ = null;\n }\n return rowsBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.Row> totals_ =\n java.util.Collections.emptyList();\n\n private void ensureTotalsIsMutable() {\n if (!((bitField0_ & 0x00000008) != 0)) {\n totals_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>(totals_);\n bitField0_ |= 0x00000008;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n totalsBuilder_;\n\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row> getTotalsList() {\n if (totalsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(totals_);\n } else {\n return totalsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public int getTotalsCount() {\n if (totalsBuilder_ == null) {\n return totals_.size();\n } else {\n return totalsBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public com.google.analytics.data.v1beta.Row getTotals(int index) {\n if (totalsBuilder_ == null) {\n return totals_.get(index);\n } else {\n return totalsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder setTotals(int index, com.google.analytics.data.v1beta.Row value) {\n if (totalsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTotalsIsMutable();\n totals_.set(index, value);\n onChanged();\n } else {\n totalsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder setTotals(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (totalsBuilder_ == null) {\n ensureTotalsIsMutable();\n totals_.set(index, builderForValue.build());\n onChanged();\n } else {\n totalsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder addTotals(com.google.analytics.data.v1beta.Row value) {\n if (totalsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTotalsIsMutable();\n totals_.add(value);\n onChanged();\n } else {\n totalsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder addTotals(int index, com.google.analytics.data.v1beta.Row value) {\n if (totalsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTotalsIsMutable();\n totals_.add(index, value);\n onChanged();\n } else {\n totalsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder addTotals(com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (totalsBuilder_ == null) {\n ensureTotalsIsMutable();\n totals_.add(builderForValue.build());\n onChanged();\n } else {\n totalsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder addTotals(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (totalsBuilder_ == null) {\n ensureTotalsIsMutable();\n totals_.add(index, builderForValue.build());\n onChanged();\n } else {\n totalsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder addAllTotals(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.Row> values) {\n if (totalsBuilder_ == null) {\n ensureTotalsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, totals_);\n onChanged();\n } else {\n totalsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder clearTotals() {\n if (totalsBuilder_ == null) {\n totals_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000008);\n onChanged();\n } else {\n totalsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public Builder removeTotals(int index) {\n if (totalsBuilder_ == null) {\n ensureTotalsIsMutable();\n totals_.remove(index);\n onChanged();\n } else {\n totalsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder getTotalsBuilder(int index) {\n return getTotalsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public com.google.analytics.data.v1beta.RowOrBuilder getTotalsOrBuilder(int index) {\n if (totalsBuilder_ == null) {\n return totals_.get(index);\n } else {\n return totalsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getTotalsOrBuilderList() {\n if (totalsBuilder_ != null) {\n return totalsBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(totals_);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addTotalsBuilder() {\n return getTotalsFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addTotalsBuilder(int index) {\n return getTotalsFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * If requested, the totaled values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row totals = 4;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row.Builder> getTotalsBuilderList() {\n return getTotalsFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n getTotalsFieldBuilder() {\n if (totalsBuilder_ == null) {\n totalsBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>(\n totals_, ((bitField0_ & 0x00000008) != 0), getParentForChildren(), isClean());\n totals_ = null;\n }\n return totalsBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.Row> maximums_ =\n java.util.Collections.emptyList();\n\n private void ensureMaximumsIsMutable() {\n if (!((bitField0_ & 0x00000010) != 0)) {\n maximums_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>(maximums_);\n bitField0_ |= 0x00000010;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n maximumsBuilder_;\n\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row> getMaximumsList() {\n if (maximumsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(maximums_);\n } else {\n return maximumsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public int getMaximumsCount() {\n if (maximumsBuilder_ == null) {\n return maximums_.size();\n } else {\n return maximumsBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public com.google.analytics.data.v1beta.Row getMaximums(int index) {\n if (maximumsBuilder_ == null) {\n return maximums_.get(index);\n } else {\n return maximumsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder setMaximums(int index, com.google.analytics.data.v1beta.Row value) {\n if (maximumsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMaximumsIsMutable();\n maximums_.set(index, value);\n onChanged();\n } else {\n maximumsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder setMaximums(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (maximumsBuilder_ == null) {\n ensureMaximumsIsMutable();\n maximums_.set(index, builderForValue.build());\n onChanged();\n } else {\n maximumsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder addMaximums(com.google.analytics.data.v1beta.Row value) {\n if (maximumsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMaximumsIsMutable();\n maximums_.add(value);\n onChanged();\n } else {\n maximumsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder addMaximums(int index, com.google.analytics.data.v1beta.Row value) {\n if (maximumsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMaximumsIsMutable();\n maximums_.add(index, value);\n onChanged();\n } else {\n maximumsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder addMaximums(com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (maximumsBuilder_ == null) {\n ensureMaximumsIsMutable();\n maximums_.add(builderForValue.build());\n onChanged();\n } else {\n maximumsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder addMaximums(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (maximumsBuilder_ == null) {\n ensureMaximumsIsMutable();\n maximums_.add(index, builderForValue.build());\n onChanged();\n } else {\n maximumsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder addAllMaximums(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.Row> values) {\n if (maximumsBuilder_ == null) {\n ensureMaximumsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, maximums_);\n onChanged();\n } else {\n maximumsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder clearMaximums() {\n if (maximumsBuilder_ == null) {\n maximums_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000010);\n onChanged();\n } else {\n maximumsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public Builder removeMaximums(int index) {\n if (maximumsBuilder_ == null) {\n ensureMaximumsIsMutable();\n maximums_.remove(index);\n onChanged();\n } else {\n maximumsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder getMaximumsBuilder(int index) {\n return getMaximumsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public com.google.analytics.data.v1beta.RowOrBuilder getMaximumsOrBuilder(int index) {\n if (maximumsBuilder_ == null) {\n return maximums_.get(index);\n } else {\n return maximumsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getMaximumsOrBuilderList() {\n if (maximumsBuilder_ != null) {\n return maximumsBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(maximums_);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addMaximumsBuilder() {\n return getMaximumsFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addMaximumsBuilder(int index) {\n return getMaximumsFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * If requested, the maximum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row maximums = 5;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row.Builder> getMaximumsBuilderList() {\n return getMaximumsFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n getMaximumsFieldBuilder() {\n if (maximumsBuilder_ == null) {\n maximumsBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>(\n maximums_, ((bitField0_ & 0x00000010) != 0), getParentForChildren(), isClean());\n maximums_ = null;\n }\n return maximumsBuilder_;\n }\n\n private java.util.List<com.google.analytics.data.v1beta.Row> minimums_ =\n java.util.Collections.emptyList();\n\n private void ensureMinimumsIsMutable() {\n if (!((bitField0_ & 0x00000020) != 0)) {\n minimums_ = new java.util.ArrayList<com.google.analytics.data.v1beta.Row>(minimums_);\n bitField0_ |= 0x00000020;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n minimumsBuilder_;\n\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row> getMinimumsList() {\n if (minimumsBuilder_ == null) {\n return java.util.Collections.unmodifiableList(minimums_);\n } else {\n return minimumsBuilder_.getMessageList();\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public int getMinimumsCount() {\n if (minimumsBuilder_ == null) {\n return minimums_.size();\n } else {\n return minimumsBuilder_.getCount();\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public com.google.analytics.data.v1beta.Row getMinimums(int index) {\n if (minimumsBuilder_ == null) {\n return minimums_.get(index);\n } else {\n return minimumsBuilder_.getMessage(index);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder setMinimums(int index, com.google.analytics.data.v1beta.Row value) {\n if (minimumsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMinimumsIsMutable();\n minimums_.set(index, value);\n onChanged();\n } else {\n minimumsBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder setMinimums(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (minimumsBuilder_ == null) {\n ensureMinimumsIsMutable();\n minimums_.set(index, builderForValue.build());\n onChanged();\n } else {\n minimumsBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder addMinimums(com.google.analytics.data.v1beta.Row value) {\n if (minimumsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMinimumsIsMutable();\n minimums_.add(value);\n onChanged();\n } else {\n minimumsBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder addMinimums(int index, com.google.analytics.data.v1beta.Row value) {\n if (minimumsBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureMinimumsIsMutable();\n minimums_.add(index, value);\n onChanged();\n } else {\n minimumsBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder addMinimums(com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (minimumsBuilder_ == null) {\n ensureMinimumsIsMutable();\n minimums_.add(builderForValue.build());\n onChanged();\n } else {\n minimumsBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder addMinimums(\n int index, com.google.analytics.data.v1beta.Row.Builder builderForValue) {\n if (minimumsBuilder_ == null) {\n ensureMinimumsIsMutable();\n minimums_.add(index, builderForValue.build());\n onChanged();\n } else {\n minimumsBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder addAllMinimums(\n java.lang.Iterable<? extends com.google.analytics.data.v1beta.Row> values) {\n if (minimumsBuilder_ == null) {\n ensureMinimumsIsMutable();\n com.google.protobuf.AbstractMessageLite.Builder.addAll(values, minimums_);\n onChanged();\n } else {\n minimumsBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder clearMinimums() {\n if (minimumsBuilder_ == null) {\n minimums_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n onChanged();\n } else {\n minimumsBuilder_.clear();\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public Builder removeMinimums(int index) {\n if (minimumsBuilder_ == null) {\n ensureMinimumsIsMutable();\n minimums_.remove(index);\n onChanged();\n } else {\n minimumsBuilder_.remove(index);\n }\n return this;\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder getMinimumsBuilder(int index) {\n return getMinimumsFieldBuilder().getBuilder(index);\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public com.google.analytics.data.v1beta.RowOrBuilder getMinimumsOrBuilder(int index) {\n if (minimumsBuilder_ == null) {\n return minimums_.get(index);\n } else {\n return minimumsBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public java.util.List<? extends com.google.analytics.data.v1beta.RowOrBuilder>\n getMinimumsOrBuilderList() {\n if (minimumsBuilder_ != null) {\n return minimumsBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(minimums_);\n }\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addMinimumsBuilder() {\n return getMinimumsFieldBuilder()\n .addBuilder(com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public com.google.analytics.data.v1beta.Row.Builder addMinimumsBuilder(int index) {\n return getMinimumsFieldBuilder()\n .addBuilder(index, com.google.analytics.data.v1beta.Row.getDefaultInstance());\n }\n /**\n *\n *\n * <pre>\n * If requested, the minimum values of metrics.\n * </pre>\n *\n * <code>repeated .google.analytics.data.v1beta.Row minimums = 6;</code>\n */\n public java.util.List<com.google.analytics.data.v1beta.Row.Builder> getMinimumsBuilderList() {\n return getMinimumsFieldBuilder().getBuilderList();\n }\n\n private com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>\n getMinimumsFieldBuilder() {\n if (minimumsBuilder_ == null) {\n minimumsBuilder_ =\n new com.google.protobuf.RepeatedFieldBuilderV3<\n com.google.analytics.data.v1beta.Row,\n com.google.analytics.data.v1beta.Row.Builder,\n com.google.analytics.data.v1beta.RowOrBuilder>(\n minimums_, ((bitField0_ & 0x00000020) != 0), getParentForChildren(), isClean());\n minimums_ = null;\n }\n return minimumsBuilder_;\n }\n\n private int rowCount_;\n /**\n *\n *\n * <pre>\n * The total number of rows in the query result. `rowCount` is independent of\n * the number of rows returned in the response, the `limit` request\n * parameter, and the `offset` request parameter. For example if a query\n * returns 175 rows and includes `limit` of 50 in the API request, the\n * response will contain `rowCount` of 175 but only 50 rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int32 row_count = 7;</code>\n *\n * @return The rowCount.\n */\n @java.lang.Override\n public int getRowCount() {\n return rowCount_;\n }\n /**\n *\n *\n * <pre>\n * The total number of rows in the query result. `rowCount` is independent of\n * the number of rows returned in the response, the `limit` request\n * parameter, and the `offset` request parameter. For example if a query\n * returns 175 rows and includes `limit` of 50 in the API request, the\n * response will contain `rowCount` of 175 but only 50 rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int32 row_count = 7;</code>\n *\n * @param value The rowCount to set.\n * @return This builder for chaining.\n */\n public Builder setRowCount(int value) {\n\n rowCount_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * The total number of rows in the query result. `rowCount` is independent of\n * the number of rows returned in the response, the `limit` request\n * parameter, and the `offset` request parameter. For example if a query\n * returns 175 rows and includes `limit` of 50 in the API request, the\n * response will contain `rowCount` of 175 but only 50 rows.\n * To learn more about this pagination parameter, see\n * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination).\n * </pre>\n *\n * <code>int32 row_count = 7;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearRowCount() {\n\n rowCount_ = 0;\n onChanged();\n return this;\n }\n\n private com.google.analytics.data.v1beta.ResponseMetaData metadata_;\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.ResponseMetaData,\n com.google.analytics.data.v1beta.ResponseMetaData.Builder,\n com.google.analytics.data.v1beta.ResponseMetaDataOrBuilder>\n metadataBuilder_;\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n *\n * @return Whether the metadata field is set.\n */\n public boolean hasMetadata() {\n return metadataBuilder_ != null || metadata_ != null;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n *\n * @return The metadata.\n */\n public com.google.analytics.data.v1beta.ResponseMetaData getMetadata() {\n if (metadataBuilder_ == null) {\n return metadata_ == null\n ? com.google.analytics.data.v1beta.ResponseMetaData.getDefaultInstance()\n : metadata_;\n } else {\n return metadataBuilder_.getMessage();\n }\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n public Builder setMetadata(com.google.analytics.data.v1beta.ResponseMetaData value) {\n if (metadataBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n metadata_ = value;\n onChanged();\n } else {\n metadataBuilder_.setMessage(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n public Builder setMetadata(\n com.google.analytics.data.v1beta.ResponseMetaData.Builder builderForValue) {\n if (metadataBuilder_ == null) {\n metadata_ = builderForValue.build();\n onChanged();\n } else {\n metadataBuilder_.setMessage(builderForValue.build());\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n public Builder mergeMetadata(com.google.analytics.data.v1beta.ResponseMetaData value) {\n if (metadataBuilder_ == null) {\n if (metadata_ != null) {\n metadata_ =\n com.google.analytics.data.v1beta.ResponseMetaData.newBuilder(metadata_)\n .mergeFrom(value)\n .buildPartial();\n } else {\n metadata_ = value;\n }\n onChanged();\n } else {\n metadataBuilder_.mergeFrom(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n public Builder clearMetadata() {\n if (metadataBuilder_ == null) {\n metadata_ = null;\n onChanged();\n } else {\n metadata_ = null;\n metadataBuilder_ = null;\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n public com.google.analytics.data.v1beta.ResponseMetaData.Builder getMetadataBuilder() {\n\n onChanged();\n return getMetadataFieldBuilder().getBuilder();\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n public com.google.analytics.data.v1beta.ResponseMetaDataOrBuilder getMetadataOrBuilder() {\n if (metadataBuilder_ != null) {\n return metadataBuilder_.getMessageOrBuilder();\n } else {\n return metadata_ == null\n ? com.google.analytics.data.v1beta.ResponseMetaData.getDefaultInstance()\n : metadata_;\n }\n }\n /**\n *\n *\n * <pre>\n * Metadata for the report.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.ResponseMetaData metadata = 8;</code>\n */\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.ResponseMetaData,\n com.google.analytics.data.v1beta.ResponseMetaData.Builder,\n com.google.analytics.data.v1beta.ResponseMetaDataOrBuilder>\n getMetadataFieldBuilder() {\n if (metadataBuilder_ == null) {\n metadataBuilder_ =\n new com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.ResponseMetaData,\n com.google.analytics.data.v1beta.ResponseMetaData.Builder,\n com.google.analytics.data.v1beta.ResponseMetaDataOrBuilder>(\n getMetadata(), getParentForChildren(), isClean());\n metadata_ = null;\n }\n return metadataBuilder_;\n }\n\n private com.google.analytics.data.v1beta.PropertyQuota propertyQuota_;\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.PropertyQuota,\n com.google.analytics.data.v1beta.PropertyQuota.Builder,\n com.google.analytics.data.v1beta.PropertyQuotaOrBuilder>\n propertyQuotaBuilder_;\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n *\n * @return Whether the propertyQuota field is set.\n */\n public boolean hasPropertyQuota() {\n return propertyQuotaBuilder_ != null || propertyQuota_ != null;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n *\n * @return The propertyQuota.\n */\n public com.google.analytics.data.v1beta.PropertyQuota getPropertyQuota() {\n if (propertyQuotaBuilder_ == null) {\n return propertyQuota_ == null\n ? com.google.analytics.data.v1beta.PropertyQuota.getDefaultInstance()\n : propertyQuota_;\n } else {\n return propertyQuotaBuilder_.getMessage();\n }\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n public Builder setPropertyQuota(com.google.analytics.data.v1beta.PropertyQuota value) {\n if (propertyQuotaBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n propertyQuota_ = value;\n onChanged();\n } else {\n propertyQuotaBuilder_.setMessage(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n public Builder setPropertyQuota(\n com.google.analytics.data.v1beta.PropertyQuota.Builder builderForValue) {\n if (propertyQuotaBuilder_ == null) {\n propertyQuota_ = builderForValue.build();\n onChanged();\n } else {\n propertyQuotaBuilder_.setMessage(builderForValue.build());\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n public Builder mergePropertyQuota(com.google.analytics.data.v1beta.PropertyQuota value) {\n if (propertyQuotaBuilder_ == null) {\n if (propertyQuota_ != null) {\n propertyQuota_ =\n com.google.analytics.data.v1beta.PropertyQuota.newBuilder(propertyQuota_)\n .mergeFrom(value)\n .buildPartial();\n } else {\n propertyQuota_ = value;\n }\n onChanged();\n } else {\n propertyQuotaBuilder_.mergeFrom(value);\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n public Builder clearPropertyQuota() {\n if (propertyQuotaBuilder_ == null) {\n propertyQuota_ = null;\n onChanged();\n } else {\n propertyQuota_ = null;\n propertyQuotaBuilder_ = null;\n }\n\n return this;\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n public com.google.analytics.data.v1beta.PropertyQuota.Builder getPropertyQuotaBuilder() {\n\n onChanged();\n return getPropertyQuotaFieldBuilder().getBuilder();\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n public com.google.analytics.data.v1beta.PropertyQuotaOrBuilder getPropertyQuotaOrBuilder() {\n if (propertyQuotaBuilder_ != null) {\n return propertyQuotaBuilder_.getMessageOrBuilder();\n } else {\n return propertyQuota_ == null\n ? com.google.analytics.data.v1beta.PropertyQuota.getDefaultInstance()\n : propertyQuota_;\n }\n }\n /**\n *\n *\n * <pre>\n * This Analytics Property's quota state including this request.\n * </pre>\n *\n * <code>.google.analytics.data.v1beta.PropertyQuota property_quota = 9;</code>\n */\n private com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.PropertyQuota,\n com.google.analytics.data.v1beta.PropertyQuota.Builder,\n com.google.analytics.data.v1beta.PropertyQuotaOrBuilder>\n getPropertyQuotaFieldBuilder() {\n if (propertyQuotaBuilder_ == null) {\n propertyQuotaBuilder_ =\n new com.google.protobuf.SingleFieldBuilderV3<\n com.google.analytics.data.v1beta.PropertyQuota,\n com.google.analytics.data.v1beta.PropertyQuota.Builder,\n com.google.analytics.data.v1beta.PropertyQuotaOrBuilder>(\n getPropertyQuota(), getParentForChildren(), isClean());\n propertyQuota_ = null;\n }\n return propertyQuotaBuilder_;\n }\n\n private java.lang.Object kind_ = \"\";\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @return The kind.\n */\n public java.lang.String getKind() {\n java.lang.Object ref = kind_;\n if (!(ref instanceof java.lang.String)) {\n com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n kind_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @return The bytes for kind.\n */\n public com.google.protobuf.ByteString getKindBytes() {\n java.lang.Object ref = kind_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b =\n com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);\n kind_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @param value The kind to set.\n * @return This builder for chaining.\n */\n public Builder setKind(java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n\n kind_ = value;\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @return This builder for chaining.\n */\n public Builder clearKind() {\n\n kind_ = getDefaultInstance().getKind();\n onChanged();\n return this;\n }\n /**\n *\n *\n * <pre>\n * Identifies what kind of resource this message is. This `kind` is always the\n * fixed string \"analyticsData#runReport\". Useful to distinguish between\n * response types in JSON.\n * </pre>\n *\n * <code>string kind = 10;</code>\n *\n * @param value The bytes for kind to set.\n * @return This builder for chaining.\n */\n public Builder setKindBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n checkByteStringIsUtf8(value);\n\n kind_ = value;\n onChanged();\n return this;\n }\n\n @java.lang.Override\n public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.setUnknownFields(unknownFields);\n }\n\n @java.lang.Override\n public final Builder mergeUnknownFields(\n final com.google.protobuf.UnknownFieldSet unknownFields) {\n return super.mergeUnknownFields(unknownFields);\n }\n\n // @@protoc_insertion_point(builder_scope:google.analytics.data.v1beta.RunReportResponse)\n }\n\n // @@protoc_insertion_point(class_scope:google.analytics.data.v1beta.RunReportResponse)\n private static final com.google.analytics.data.v1beta.RunReportResponse DEFAULT_INSTANCE;\n\n static {\n DEFAULT_INSTANCE = new com.google.analytics.data.v1beta.RunReportResponse();\n }\n\n public static com.google.analytics.data.v1beta.RunReportResponse getDefaultInstance() {\n return DEFAULT_INSTANCE;\n }\n\n private static final com.google.protobuf.Parser<RunReportResponse> PARSER =\n new com.google.protobuf.AbstractParser<RunReportResponse>() {\n @java.lang.Override\n public RunReportResponse parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new RunReportResponse(input, extensionRegistry);\n }\n };\n\n public static com.google.protobuf.Parser<RunReportResponse> parser() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.protobuf.Parser<RunReportResponse> getParserForType() {\n return PARSER;\n }\n\n @java.lang.Override\n public com.google.analytics.data.v1beta.RunReportResponse getDefaultInstanceForType() {\n return DEFAULT_INSTANCE;\n }\n}" ]
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.Row; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse;
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.analytics; /* Google Analytics Data API sample quickstart application. This application demonstrates the usage of the Analytics Data API using service account credentials. Before you start the application, please review the comments starting with "TODO(developer)" and update the code to use correct values. To run this sample using Maven: cd java-analytics-data/samples/snippets mvn compile mvn exec:java -Dexec.mainClass="com.example.analytics.QuickstartSample" */ // [START analyticsdata_quickstart] public class QuickstartSample { public static void main(String... args) throws Exception { /** * TODO(developer): Replace this variable with your Google Analytics 4 property ID before * running the sample. */ String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunReport(propertyId); } // This is an example snippet that calls the Google Analytics Data API and runs a simple report // on the provided GA4 property id. static void sampleRunReport(String propertyId) throws Exception { /** * TODO(developer): Uncomment this variable and replace with your Google Analytics 4 property ID * before running the sample. */ // propertyId = "YOUR-GA4-PROPERTY-ID"; // [START analyticsdata_initialize] // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { // [END analyticsdata_initialize] // [START analyticsdata_run_report] RunReportRequest request = RunReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("city")) .addMetrics(Metric.newBuilder().setName("activeUsers")) .addDateRanges(DateRange.newBuilder().setStartDate("2020-03-31").setEndDate("today")) .build(); // Make the request.
RunReportResponse response = analyticsData.runReport(request);
6
groupon/Selenium-Grid-Extras
SeleniumGridExtras/src/main/java/com/groupon/seleniumgridextras/tasks/DownloadGeckoDriver.java
[ "public class RuntimeConfig {\n\n public static String configFile = \"selenium_grid_extras_config.json\";\n private static Config config = null;\n private static OS currentOS = new OS();\n private static Logger logger = Logger.getLogger(RuntimeConfig.class);\n private static WebDriverReleaseManager releaseManager;\n private static SessionTracker sessionTracker;\n\n public static int getGridExtrasPort() {\n if(getConfig() == null) {\n return 3000;\n } else {\n return getConfig().getGridExtrasPort();\n }\n }\n\n public static WebDriverReleaseManager getReleaseManager() {\n if (releaseManager == null) {\n releaseManager =\n loadWebDriverReleaseManager(\"https://selenium-release.storage.googleapis.com/\",\n \"https://chromedriver.storage.googleapis.com/LATEST_RELEASE\",\n \"https://api.github.com/repos/mozilla/geckodriver/releases\");\n }\n\n return releaseManager;\n }\n\n\n private static WebDriverReleaseManager loadWebDriverReleaseManager(String webDriverAndIEDriverURL,\n String chromeDriverUrl,\n String geckoDriverUrl) {\n try {\n return new WebDriverReleaseManager(new URL(webDriverAndIEDriverURL),\n new URL(chromeDriverUrl),\n new URL(geckoDriverUrl));\n } catch (MalformedURLException e) {\n logger.error(\"Seems that \" + webDriverAndIEDriverURL + \" is malformed\");\n logger.error(e.toString());\n e.printStackTrace();\n } catch (DocumentException e) {\n logger.error(\"Something went wrong loading webdriver versions\");\n logger.error(e.toString());\n e.printStackTrace();\n }\n\n return null;\n }\n\n public RuntimeConfig() {\n config = new Config();\n }\n\n\n protected static void clearConfig() {\n //Use only for tests, don't use for any other reason\n config = null;\n }\n\n public static String getConfigFile() {\n return configFile;\n }\n\n public static void setConfigFile(String file) {\n configFile = file;\n }\n\n public static Config load(boolean UpdateConfigsFromHub) {\n Map overwriteValues;\n config = DefaultConfig.getDefaultConfig();\n logger.debug(config);\n\n if (UpdateConfigsFromHub) {\n new ConfigPuller().updateFromRemote();\n }\n\n ConfigFileReader configFileObject = new ConfigFileReader(configFile);\n\n logger.debug(configFileObject.toHashMap());\n\n if (!configFileObject.hasContent()) {\n logger.info(\"Previous config was not found, will ask input from user\");\n Config userInput = Config.initilizedFromUserInput();\n logger.debug(userInput);\n }\n\n // Read the primary config file\n configFileObject.readConfigFile();\n overwriteValues = configFileObject.toHashMap();\n logger.debug(overwriteValues);\n\n //Overwrite default configs\n config.overwriteConfig(overwriteValues);\n\n //Load node info from the node classes\n config.loadNodeClasses();\n config.loadHubClasses(); // TODO added for Hub\n\n //Write out all of the possible examples into an example file\n config.writeToDisk(RuntimeConfig.getConfigFile() + \".example\");\n\n logger.debug(config);\n return config;\n }\n\n\n public static Config load() {\n return load(false);\n }\n\n public static File getSeleniumGridExtrasJarFile() {\n try {\n return new File(\n SeleniumGridExtras.class.getProtectionDomain().getCodeSource().getLocation().toURI());\n } catch (URISyntaxException e) {\n logger.error(\"Could not get jar file\");\n logger.error(e);\n throw new RuntimeException(e);\n }\n }\n\n\n public static String getSeleniungGridExtrasHomePath() {\n return FilenameUtils\n .getFullPathNoEndSeparator(getSeleniumGridExtrasJarFile().getAbsolutePath());\n }\n\n\n public static Config getConfig() {\n return config;\n }\n\n public static OS getOS() {\n return currentOS;\n }\n\n public static String getHostIp() {\n String ip = null;\n if (config != null) {\n if (config.getHostIp() != null) {\n ip = config.getHostIp();\n } else if (config.getDefaultRole().equals(\"hub\") && config.getHubs().size() > 0) {\n ip = config.getHubs().get(0).getConfiguration().getHost();\n } else if (config.getDefaultRole().equals(\"node\") && config.getNodes().size() > 0) {\n ip = config.getNodes().get(0).getConfiguration() != null ? config.getNodes().get(0).getConfiguration().getHost() : config.getNodes().get(0).getHost();\n }\n }\n if (ip == null) {\n ip = currentOS.getHostIp();\n }\n return ip;\n }\n\n\n public static SessionTracker getTestSessionTracker() {\n if (sessionTracker == null) {\n sessionTracker = new SessionTracker();\n }\n\n return sessionTracker;\n }\n\n}", "public class GeckoDriverDownloader extends Downloader {\n\n private String bit;\n private String version;\n\n private static Logger logger = Logger.getLogger(GeckoDriverDownloader.class);\n private static final String GECKODRIVER_RELEASES_URL = \"https://api.github.com/repos/mozilla/geckodriver/releases\";\n\n public GeckoDriverDownloader(String version, String bitVersion) {\n\n setDestinationDir(RuntimeConfig.getConfig().getGeckoDriver().getDirectory());\n setVersion(version);\n setBitVersion(bitVersion);\n\n setDestinationFile(\"geckodriver_\" + getVersion() + \".\" + getExtension());\n\n setSourceURL(buildSourceURL());\n }\n\n @Override\n public void setSourceURL(String source) {\n sourceURL = source;\n }\n\n @Override\n public void setDestinationFile(String destination) {\n destinationFile = destination;\n }\n\n @Override\n public void setDestinationDir(String dir) {\n destinationDir = dir;\n }\n\n @Override\n public boolean download() {\n\n logger.info(\"Downloading from \" + getSourceURL());\n\n if (startDownload()) {\n\n if (Unzipper.unzip(getDestinationFileFullPath().getAbsolutePath(), getDestinationDir())) {\n\n String geckodriver = \"geckodriver\";\n if (RuntimeConfig.getOS().isWindows()){\n geckodriver = geckodriver + \".exe\";\n }\n\n\n File tempUnzipedExecutable = new File(getDestinationDir(), geckodriver);\n File finalExecutable =\n new File(RuntimeConfig.getConfig().getGeckoDriver().getExecutablePath());\n\n if (tempUnzipedExecutable.exists()){\n logger.debug(tempUnzipedExecutable.getAbsolutePath());\n logger.debug(\"It does exist\");\n logger.debug(finalExecutable.getAbsolutePath());\n } else {\n logger.debug(tempUnzipedExecutable.getAbsolutePath());\n logger.debug(\"NO exist\");\n logger.debug(finalExecutable.getAbsolutePath());\n }\n\n tempUnzipedExecutable.renameTo(finalExecutable);\n\n setDestinationFile(finalExecutable.getAbsolutePath());\n\n finalExecutable.setExecutable(true, false);\n finalExecutable.setReadable(true, false);\n\n return true;\n }\n }\n return false;\n }\n\n public String getBitVersion() {\n return bit;\n }\n\n public void setBitVersion(String bit) {\n this.bit = bit;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n private String getExtension() {\n String ext;\n\n if (RuntimeConfig.getOS().isWindows()) {\n ext = \"zip\";\n } else if (RuntimeConfig.getOS().isMac()) {\n ext = \"tar.gz\";\n } else {\n ext = \"tar.gz\";\n }\n return ext;\n }\n\n protected static String getOSName() {\n String os;\n\n if (RuntimeConfig.getOS().isWindows()) {\n os = getWindowsName();\n } else if (RuntimeConfig.getOS().isMac()) {\n os = getMacName();\n } else {\n os = getLinuxName();\n }\n\n return os;\n }\n\n protected static String getLinuxName() {\n return \"linux\";\n }\n\n protected static String getMacName() {\n return \"macos\";\n }\n\n protected static String getWindowsName() {\n return \"win\";\n }\n\n private String buildSourceURL()\n {\n final String base_url = \"https://github.com/mozilla/geckodriver/releases/download/v\";\n\n String firstPart = base_url + getVersion() + \"/geckodriver-v\" + getVersion() + \"-\" + getOSName();\n\n if (getOSName() == getMacName())\n {\n return firstPart + \".\" + getExtension();\n }\n else\n {\n return firstPart + getBitVersion() + \".\" + getExtension();\n }\n }\n\n public static String[] getBitArchitecturesForVersion(String geckoDriverVersionNumber)\n {\n ArrayList<String> bitArchitecturesAvailable = new ArrayList<String>();\n String[] versions = getVersionManifest();\n for (String version : versions)\n {\n Matcher versionMatcher = Pattern.compile(\"geckodriver-v\" + geckoDriverVersionNumber + \"-\" + getOSName()).matcher(version);\n if (versionMatcher.find())\n {\n if(Pattern.compile(getOSName() + JsonCodec.WebDriver.Downloader.BIT_64).matcher(version).find())\n {\n bitArchitecturesAvailable.add(JsonCodec.WebDriver.Downloader.BIT_64);\n }\n else if (Pattern.compile(getOSName() + JsonCodec.WebDriver.Downloader.BIT_32).matcher(version).find())\n {\n bitArchitecturesAvailable.add(JsonCodec.WebDriver.Downloader.BIT_32);\n }\n }\n }\n return bitArchitecturesAvailable.toArray(new String[] {});\n }\n\n private static String[] getVersionManifest()\n {\n List<String> versions = new ArrayList<String>();\n GitHubDownloader gitHubDownloader = new GitHubDownloader(GECKODRIVER_RELEASES_URL);\n try\n {\n List<Map<String, String>> results = gitHubDownloader.getAllDownloadableAssets();\n for (Map<String, String> kv : results) {\n for (String key : kv.keySet()) {\n versions.add(key);\n }\n }\n } catch (IOException e)\n {\n e.printStackTrace();\n } catch (URISyntaxException e)\n {\n e.printStackTrace();\n }\n finally{\n return versions.toArray(new String[] {});\n }\n }\n}", "public abstract class Downloader {\n\n protected String errorMessage = \"\";\n protected String sourceURL;\n protected String destinationFile;\n protected String destinationDir;\n\n private static Logger logger = Logger.getLogger(Downloader.class);\n\n public boolean download(){\n return startDownload();\n }\n\n public File getDestinationFileFullPath(){\n File dir = new File(getDestinationDir());\n File file = new File(getDestinationFile());\n File combined = new File(dir.getAbsolutePath() + RuntimeConfig.getOS().getFileSeparator() + file.getName());\n return combined;\n }\n\n public String getDestinationFile(){\n return destinationFile;\n }\n\n public String getSourceURL(){\n return sourceURL;\n }\n\n\n public String getDestinationDir(){\n return destinationDir;\n }\n\n public String getErrorMessage(){\n return errorMessage;\n }\n\n public void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n protected boolean startDownload(){\n try {\n URL url = new URL(getSourceURL());\n logger.info(\"Starting to download from \" + url);\n FileUtils.copyURLToFile(url, getDestinationFileFullPath());\n logger.info(\"Download complete\");\n return true;\n } catch (MalformedURLException error){\n logger.error(error.toString());\n setErrorMessage(error.toString());\n } catch (IOException error) {\n logger.error(error.toString());\n setErrorMessage(error.toString());\n }\n logger.error(\"Download failed\");\n return false;\n }\n\n public abstract void setSourceURL(String source);\n public abstract void setDestinationFile(String destination);\n public abstract void setDestinationDir(String dir);\n\n\n}", "public class TaskDescriptions {\n\n public static class Endpoints {\n public static final String AUTO_UPGRADE_WEBDRIVER = \"/auto_upgrade_webdriver\";\n public static final String DOWNLOAD_CHROMEDRIVER = \"/download_chromedriver\";\n public static final String DOWNLOAD_GECKODRIVER = \"/download_geckodriver\";\n public static final String DOWNLOAD_IEDRIVER = \"/download_iedriver\";\n public static final String DOWNLOAD_WEBDRIVER = \"/download_webdriver\";\n public static final String DIR = \"/dir\";\n public static final String CONFIG = \"/config\";\n public static final String GET_FILE = \"/get_file\";\n public static final String PORT_INFO = \"/port_info\";\n public static final String GET_NODE_CONFIG = \"/get_node_config\";\n public static final String PS = \"/ps\";\n public static final String GRID_STATUS = \"/grid_status\";\n public static final String IE_PROTECTED_MODE = \"/ie_protected_mode\";\n public static final String IE_MIXED_CONTENT = \"/ie_mixed_content\";\n public static final String KILL_ALL_BY_NAME = \"/kill_all_by_name\";\n public static final String KILL_CHROME = \"/kill_chrome\";\n public static final String KILL_FIREFOX = \"/kill_firefox\";\n public static final String KILL_IE = \"/kill_ie\";\n public static final String KILL_SAFARI = \"/kill_safari\";\n public static final String KILL_PID = \"/kill_pid\";\n public static final String MOVE_MOUSE = \"/move_mouse\";\n public static final String LOG_DELETE = \"/log_delete\";\n public static final String NETSTAT = \"/netstat\";\n public static final String REBOOT = \"/reboot\";\n public static final String RESOLUTION = \"/resolution\";\n public static final String SCREENSHOT = \"/screenshot\";\n public static final String SETUP = \"/setup\";\n public static final String START_GRID = \"/start_grid\";\n public static final String STOP_GRID = \"/stop_grid\";\n public static final String STOP_GRID_EXTRAS = \"/stop_extras\";\n public static final String SYSTEM = \"/system\";\n public static final String TEARDOWN = \"/teardown\";\n public static final String UPDATE_NODE_CONFIG = \"/update_node_config\";\n public static final String VIDEO = \"/video\";\n public static final String SESSION_HISTORY = \"/session_history\";\n public static final String UPGRADE_GRID_EXTRAS = \"/upgrade_grid_extras\";\n public static final String USER_AUTO_LOGON = \"/user_auto_logon\";\n }\n\n\n public static class Description {\n\n public static final\n String AUTO_UPGRADE_WEBDRIVER =\n \"Automatically checks the latest versions of all drivers and upgrades the current config to use them\";\n public static final\n String DOWNLOAD_CHROMEDRIVER =\n \"Downloads a version of ChromeDriver to local machine\";\n public static final\n String DOWNLOAD_GECKODRIVER =\n \"Downloads a version of GeckoDriver to local machine\";\n public static final\n String DOWNLOAD_IEDRIVER =\n \"Downloads a version of IEDriver.exe to local machine\";\n public static final\n String DOWNLOAD_WEBDRIVER =\n \"Downloads a version of WebDriver jar to local machine\";\n public static final\n String DIR =\n \"Gives accesses to a shared directory, user has access to put files into it and get files from it. Directory deleted on restart.\";\n public static final\n String CONFIG =\n \"Returns JSON view of the full configuration of the Selenium Grid Extras\";\n public static final\n String GET_FILE = \"(Not yet implemented) - Retrives a file from shared Directory\";\n public static final\n String PORT_INFO = \"Returns parsed information on a PID occupying a given port\";\n public static final\n String\n GET_NODE_CONFIG =\n \"Provides the grid node config from central location\";\n public static final String PS = \"Gets a list of currently running processes\";\n public static final\n String\n GRID_STATUS =\n \"Returns status of the Selenium Grid hub/node. If currently running and what is the PID\";\n public static final\n String\n IE_PROTECTED_MODE =\n \"Changes protected mode for Internet Explorer on/off. No param for current status\";\n public static final\n String\n KILL_ALL_BY_NAME =\n \"Executes os level kill command on a given PID name\";\n public static final\n String\n KILL_CHROME =\n \"Executes os level kill command on all instance of Google Chrome\";\n public static final\n String\n KILL_FIREFOX =\n \"Executes os level kill command on all instance of Firefox\";\n public static final\n String\n KILL_IE =\n \"Executes os level kill command on all instance of Internet Explorer\";\n public static final\n String\n KILL_SAFARI =\n \"Executes os level kill command on all instance of Safari\";\n public static final String KILL_PID = \"Kills a given process id\";\n public static final String LOG_DELETE = \"Delete logs older than X Days. X is define in the config.json\";\n public static final\n String\n MOVE_MOUSE =\n \"Moves the computers mouse to x and y location. (Default 0,0)\";\n public static final\n String\n NETSTAT =\n \"Returns a system call for all ports. Use /port_info to get parsed details\";\n public static final String REBOOT = \"Restart the host node\";\n public static final String RESOLUTION = \"Changes the screen resolution. No param for current resolution\";\n public static final String SCREENSHOT = \"Take a full OS screen Screen Shot of the node\";\n public static final\n String\n SETUP =\n \"Calls several pre-defined tasks to act as setup before build\";\n public static final String START_GRID = \"Starts an instance of Selenium Grid Hub or NodeConfig\";\n public static final String STOP_GRID = \"Stops grid or node process\";\n public static final String STOP_GRID_EXTRAS = \"Shuts down Grid Extras service\";\n public static final String SYSTEM = \"Returns system details about the current node\";\n public static final\n String\n TEARDOWN =\n \"Calls several pre-defined tasks to act as teardown after build\";\n public static final\n String\n UPDATE_NODE_CONFIG =\n \"Send the current config to the central location to be stored\";\n public static final String VIDEO = \"Starts and stops video recording\";\n public static final String SESSION_HISTORY = \"Displays the threads of test session on all nodes or per node basis\";\n public static final String IE_MIXED_CONTENT = \"Changes mixed content for Internet Explorer on/off. No param for current status\";\n public static final String UPGRADE_GRID_EXTRAS = \"Download specified version of Selenium Grid Extras\";\n public static final String SETS_A_USER_TO_AUTOMATICALLY_LOGON_INTO_SYSTEM_POST_REBOOT = \"Sets a user to automatically logon into system post reboot\";\n }\n\n public static class HTTP {\n\n public static final String GET = \"GET\";\n public static final String JSON = \"json\";\n }\n\n\n public static class UI {\n\n public static final String BTN_SUCCESS = \"btn-success\";\n public static final String BTN_DANGER = \"btn-danger\";\n public static final String BTN_INFO = \"btn-info\";\n public static final String BTN = \"btn\";\n public static final String AUTO_LOGON_USER = \"Auto Logon User\";\n\n public static class ButtonText {\n\n public static final String DOWNLOAD_CHROMEDRIVER = \"Download Chrome-Driver\";\n public static final String DOWNLOAD_GECKODRIVER = \"Download Gecko-Driver\";\n public static final String DOWNLOAD_IEDRIVER = \"Download IE-Driver\";\n public static final String DOWNLOAD_WEBDRIVER = \"Download WebDriver\";\n public static final String DIR = \"List Shared Dir\";\n public static final String CONFIG = \"Get Config\";\n public static final String GET_FILE = \"Get File\";\n public static final String PORT_INFO = \"Get Info for Port\";\n public static final String GET_NODE_CONFIG = \"Get Node Config\";\n public static final String PS = \"Get Processes\";\n public static final String GRID_STATUS = \"Grid Status\";\n public static final String IE_PROTECTED_MODE = \"Enanble/Disable Protected Mode\";\n public static final String IE_MIXED_CONTENT = \"Enanble/Disable Mixed Content\";\n public static final String KILL_ALL_BY_NAME = \"Kill all by name\";\n public static final String KILL_CHROME = \"Kill all chrome\";\n public static final String KILL_FIREFOX = \"Kill all firefox\";\n public static final String KILL_IE = \"Kill all IE\";\n public static final String KILL_SAFARI = \"Kill all Safari\";\n public static final String KILL_PID = \"Kill PID\";\n public static final String MOVE_MOUSE = \"Move mouse\";\n public static final String NETSTAT = \"netstat\";\n public static final String REBOOT = \"reboot\";\n public static final String RESOLUTION = \"resolution\";\n public static final String SCREENSHOT = \"screenshot\";\n public static final String SETUP = \"setup\";\n public static final String START_GRID = \"StartGrid\";\n public static final String STOP_GRID = \"Stop Grid\";\n public static final String STOP_GRID_EXTRAS = \"Shut Down Grid Extras\";\n public static final String SYSTEM = \"System Info\";\n public static final String TEARDOWN = \"Teardown\";\n public static final String UPDATE_NODE_CONFIG = \"Get Node Config\";\n public static final String SESSION_HISTORY = \"Get Session History\";\n }\n\n }\n}", "public class JsonCodec {\n\n public static final String OUT = \"out\";\n public static final String ERROR = \"error\";\n public static final String EXIT_CODE = \"exit_code\";\n public static final String PARAMETER = \"parameter\";\n public static final String FILES = \"files\";\n public static final String TIMESTAMP = \"timestamp\";\n public static final String CONFIRM = \"confirm\";\n public static final String TRUE = \"true\";\n public static final String N_A = \"N/A\";\n public static final String FALSE_INT = \"0\";\n public static final String TRUE_INT = \"1\";\n public static final String WARNING = \"__WARNING__\";\n public static final String COMMAND = \"command\";\n public static final String LOGS_DELETED = \"logs_deleted\";\n\n public static class GridExtras{\n\n public static final String VERSION = \"version\";\n public static final String CURRENT_VERSION = \"current_version\";\n public static final String CURRENT_GRID_EXTRAS_FILE = \"current_grid_extras_file\";\n public static final String NEW_VERSION = \"new_version\";\n public static final String VERSION_GRID_EXTRAS_FILE = \"version_grid_extras_file\";\n public static final String REMOTE_JAR_URL = \"remote_jar_url\";\n public static final String DOWNLOADED_FILE_SIZE = \"downloaded_file_size\";\n public static final String ALL_AVAILABLE_RELEASES = \"all_available_releases\";\n }\n\n public static class SessionLogging {\n\n public static final String NEW = \"new\";\n public static final String GET = \"get\";\n }\n\n\n public static class SetupTeardown {\n public static final String RESULTS = \"results\";\n public static final String CLASSES_TO_EXECUTE = \"classes_to_execute\";\n }\n\n public static class Images {\n public static final String WIDTH = \"width\";\n public static final String HEIGHT = \"height\";\n public static final String KEEP = \"keep\";\n public static final String FILE_TYPE = \"file_type\";\n public static final String FILE = \"file\";\n public static final String IMAGE = \"image\";\n public static final String PNG = \"png\";\n }\n\n public static class Video {\n\n public static final String SESSION = \"session\";\n public static final String ACTION = \"action\";\n public static final String DESCRIPTION = \"description\";\n public static final String CURRENT_VIDEOS = \"current_videos\";\n public static final String START = \"start\";\n public static final String STOP = \"stop\";\n public static final String HEARTBEAT = \"heartbeat\";\n public static final String STATUS = \"status\";\n public static final String STOP_ALL = \"stop_all\";\n public static final String AVAILABLE_VIDEOS = \"available_videos\";\n public static final String VIDEO_DOWNLOAD_URL = \"download_url\";\n public static final String VIEDO_SIZE = \"size\";\n public static final String LAST_MODIFIED = \"last_modified\";\n public static final String VIDEO_ABSOLUTE_PATH = \"absolute_path\";\n }\n\n public static class OS {\n\n public static final String PROCESS_NAME = \"process_name\";\n public static final String PORT = \"port\";\n public static final String PID = \"pid\";\n public static final String PROCESS = \"process\";\n public static final String USER = \"user\";\n public static final String HOSTNAME = \"hostname\";\n public static final String IP = \"ip\";\n public static final String UPTIME = \"uptime\";\n public static final String USERNAME = \"username\";\n public static final String PASSWORD = \"password\";\n public static final String DOMAIN = \"domain\";\n public static final String CURRENT_USER = \"current_user\";\n public static final String CURRENT_DOMAIN = \"current_domain\";\n public static final String AUTO_LOGON_ENABLED = \"auto_logon_enabled\";\n public static final String RESOLUTION_WIDTH = \"width\";\n public static final String RESOLUTION_HEIGHT = \"height\";\n\n public static class JVM {\n public static final String JVM_INFO = \"jvm\";\n public static final String AVAILABLE_PROCESSORS_TO_JVM = \"available_processors\";\n public static final String FREE_MEMORY_AVAILABLE_TO_JVM = \"free_memory\";\n public static final String MAX_MEMORY = \"max_memory\";\n }\n\n public static class Mouse {\n public static final String X = \"x\";\n public static final String Y = \"y\";\n }\n\n public static class KillCommands {\n\n public static final String COMMAND = \"command\";\n public static final String WAIT_TO_FINISH = \"wait_to_finish\";\n public static final String NAME = \"name\";\n public static final String SIGNAL = \"signal\";\n public static final String ID = \"id\";\n }\n\n public static class Windows {\n\n public static class InternetExplorer {\n public static final String INTERNET_ZONE = \"1\";\n public static final String INTRANET_ZONE = \"2\";\n public static final String TRUSTED_ZONE = \"3\";\n public static final String RESTRICTED_ZONE = \"4\";\n public static final String INTERNET = \"Internet\";\n public static final String LOCAL_INTRANET = \"Local Intranet\";\n public static final String TRUSTED_SITES = \"Trusted Sites\";\n public static final String RESTRICTED_SITES = \"Restricted Sites\";\n public static final String ENABLED = \"enabled\";\n }\n\n public static class RegistryKeys {\n public static final String IE_PROTECTED_MODE = \"2500\";\n public static final String IE_MIXED_CONTENT = \"1609\";\n }\n }\n\n public static class Hardware {\n\n public static class Ram {\n public static final String RAM = \"ram\";\n public static final String TOTAL = \"total\";\n public static final String FREE = \"free\";\n public static final String TOTAL_SWAP = \"total_swap\";\n public static final String FREE_SWAP = \"free_swap\";\n }\n\n public static class HardDrive {\n\n public static final String DRIVES = \"drives\";\n public static final String FREE = \"free\";\n public static final String SIZE = \"size\";\n public static final String DRIVE = \"drive\";\n public static final String USABLE = \"usable\";\n }\n\n public static class Processor {\n\n public static final String PROCESSOR = \"processor\";\n public static final String INFO = \"info\";\n public static final String ARCHITECTURE = \"architecture\";\n public static final String CORES = \"cores\";\n public static final String LOAD = \"load\";\n }\n }\n }\n\n public static class Config {\n\n public static final String CONFIG_FILE = \"config_file\";\n public static final String CONFIG_RUNTIME = \"config_runtime\";\n public static final String CONTENT = \"content\";\n public static final String FILENAME = \"filename\";\n }\n\n public static class WebDriver {\n\n public static final String OLD_WEB_DRIVER_JAR = \"old_web_driver_jar\";\n public static final String OLD_CHROME_DRIVER = \"old_chrome_driver\";\n public static final String OLD_GECKO_DRIVER = \"old_gecko_driver\";\n public static final String OLD_IE_DRIVER = \"old_ie_driver\";\n public static final String NEW_WEB_DRIVER_JAR = \"new_web_driver_jar\";\n public static final String NEW_CHROME_DRIVER = \"new_chrome_driver\";\n public static final String NEW_GECKO_DRIVER = \"new_gecko_driver\";\n public static final String NEW_IE_DRIVER = \"new_ie_driver\";\n\n\n public static class Grid {\n public static final String HUB_RUNNING = \"hub_running\";\n public static final String NODE_RUNNING = \"node_running\";\n public static final String HUB_INFO = \"hub_info\";\n public static final String NODE_INFO = \"node_info\";\n public static final String NODE_SESSIONS_LIMIT = \"node_sessions_limit\";\n public static final String NODE_WILL_UNREGISTER_DURING_REBOOT = \"node_will_unregister_during_reboot\";\n public static final String NODE = \"node\";\n public static final String PORT = \"port\";\n public static final String HOST = \"host\";\n public static final String ROLE = \"role\";\n public static final String SERVLETS = \"servlets\";\n public static final String HUB = \"hub\";\n\n public static final String SESSION_ID = \"session\";\n\n public static final String LOGS = \"logs\";\n public static final String INTERNAL_KEY = \"internal_key\";\n public static final String EXTERNAL_KEY = \"external_key\";\n public static final String NOT_YET_ASSIGNED = \"Not Yet Assigned\";\n public static final String REQUESTED_CAPABILITIES = \"requested_capabilities\";\n public static final String NEW_SESSION_PARAM = \"session\";\n public static final String RECORDED_SESSIONS = \"sessions\";\n }\n\n public static class Downloader {\n\n public static final String BIT_32 = \"32\";\n public static final String BIT_64 = \"64\";\n public static final String ROOT_DIR = \"root_dir\";\n public static final String BIT = \"bit\";\n public static final String WIN32 = \"Win32\";\n public static final String FILE = \"file\";\n public static final String FILE_FULL_PATH = \"file_full_path\";\n public static final String SOURCE_URL = \"source_url\";\n public static final String VERSION = \"version\";\n }\n }\n}" ]
import com.google.gson.JsonObject; import com.groupon.seleniumgridextras.config.RuntimeConfig; import com.groupon.seleniumgridextras.downloader.GeckoDriverDownloader; import com.groupon.seleniumgridextras.downloader.Downloader; import com.groupon.seleniumgridextras.tasks.config.TaskDescriptions; import com.groupon.seleniumgridextras.utilities.json.JsonCodec; import org.apache.log4j.Logger; import java.io.File; import java.util.Map;
/** * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * Created with IntelliJ IDEA. * User: Dima Kovalenko (@dimacus) && Darko Marinov * Date: 5/10/13 * Time: 4:06 PM */ package com.groupon.seleniumgridextras.tasks; public class DownloadGeckoDriver extends ExecuteOSTask { private String bit = JsonCodec.WebDriver.Downloader.BIT_32; private static Logger logger = Logger.getLogger(DownloadGeckoDriver.class); public DownloadGeckoDriver() { setEndpoint(TaskDescriptions.Endpoints.DOWNLOAD_GECKODRIVER); setDescription(TaskDescriptions.Description.DOWNLOAD_GECKODRIVER); JsonObject params = new JsonObject(); params.addProperty(JsonCodec.WebDriver.Downloader.VERSION, "Version of GeckoDriver to download, such as 0.10.0"); params.addProperty(JsonCodec.WebDriver.Downloader.BIT, "Bit Version of GeckoDriver 32/64 - (default: 32)"); setAcceptedParams(params); setRequestType(TaskDescriptions.HTTP.GET); setResponseType(TaskDescriptions.HTTP.JSON); setClassname(this.getClass().getCanonicalName().toString()); setCssClass(TaskDescriptions.UI.BTN_SUCCESS); setButtonText(TaskDescriptions.UI.ButtonText.DOWNLOAD_GECKODRIVER); setEnabledInGui(true); addResponseDescription(JsonCodec.WebDriver.Downloader.ROOT_DIR, "Directory to which executable file was saved to"); addResponseDescription(JsonCodec.WebDriver.Downloader.FILE, "Relative path to file on the node"); addResponseDescription(JsonCodec.WebDriver.Downloader.FILE_FULL_PATH, "Full path to file on node"); addResponseDescription(JsonCodec.WebDriver.Downloader.SOURCE_URL, "Url from which the executable was downloaded. If file already exists, this will be blank, and download will be skipped"); // bit value should be initialized from configuration this.bit = RuntimeConfig.getConfig().getGeckoDriver().getBit(); logger.debug(RuntimeConfig.getConfig()); getJsonResponse() .addKeyValues(JsonCodec.WebDriver.Downloader.ROOT_DIR, RuntimeConfig.getConfig().getGeckoDriver().getDirectory()); getJsonResponse().addKeyValues( JsonCodec.WebDriver.Downloader.SOURCE_URL, ""); } @Override public JsonObject execute() { return execute(RuntimeConfig.getConfig().getGeckoDriver().getVersion()); } @Override public JsonObject execute(Map<String, String> parameter) { if (!parameter.isEmpty() && parameter.containsKey(JsonCodec.WebDriver.Downloader.VERSION)) { if (parameter.containsKey(JsonCodec.WebDriver.Downloader.BIT)) { this.bit = parameter.get(JsonCodec.WebDriver.Downloader.BIT).toString(); } else { this.bit = JsonCodec.WebDriver.Downloader.BIT_32; } return execute(parameter.get(JsonCodec.WebDriver.Downloader.VERSION).toString()); } else { return execute(); } } @Override public JsonObject execute(String version) { Downloader downloader =
new GeckoDriverDownloader(version, this.bit);
1
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/fragment/AllStopFragment.java
[ "public class OneStopActivity extends AppCompatActivity {\n private Toolbar toolbar;\n private ViewPager viewPager;\n private SlidingTabLayout slidingTabLayout;\n\n private FavoriteStops favoriteStops;\n private FavoriteStopLine favoriteStopLine;\n\n private int stop_zone_id;\n private StopZone stop;\n\n private UpdateRunnable updateRunnable;\n private MaterialDialog current_dialog;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_slidingtabs);\n\n Bundle bundle = getIntent().getExtras();\n stop_zone_id = bundle.getInt(\"stop_zone_id\");\n stop = Data.getData().getMap().getStopZoneById(stop_zone_id);\n\n toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);\n setSupportActionBar(toolbar);\n getSupportActionBar().setDisplayShowTitleEnabled(true);\n getSupportActionBar().setDisplayShowHomeEnabled(true);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n getSupportActionBar().setHomeButtonEnabled(true);\n getSupportActionBar().setTitle(stop.getName());\n toolbar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n viewPager = (ViewPager) findViewById(R.id.viewpager);\n\n viewPager.setAdapter(new OneStopPageAdapter(getSupportFragmentManager()));\n\n favoriteStops = new FavoriteStops(getApplicationContext());\n favoriteStopLine = new FavoriteStopLine(getApplicationContext());\n\n slidingTabLayout = new SlidingTabLayout(getApplicationContext());\n slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);\n slidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.textClearColor));\n slidingTabLayout.setDividerColors(getResources().getColor(R.color.primaryColor));\n slidingTabLayout.setViewPager(viewPager);\n }\n\n\n @Override\n public void onResume(){\n super.onResume();\n EventBus.getDefault().register(this);\n updateRunnable = new UpdateRunnable();\n updateRunnable.run();\n Data.getData().setToUpdate(new RealTimeToUpdate(stop.getStops()));\n }\n\n @Override\n public void onPause(){\n super.onPause();\n EventBus.getDefault().unregister(this);\n updateRunnable.stop();\n if (isFinishing()) overridePendingTransition(R.anim.fade_scale_in, R.anim.slide_to_right);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.stop_menu, menu);\n getMenuInflater().inflate(R.menu.add_to_home, menu);\n MenuItem item = menu.findItem(R.id.action_favorite);\n if (favoriteStops.isInFav(stop)) {\n item.setIcon(R.drawable.ic_star_white_24dp);\n } else {\n item.setIcon(R.drawable.ic_star_border_white_24dp);\n }\n if (stop.getReports().size() > 0) {\n getMenuInflater().inflate(R.menu.alert_report_item, menu);\n }\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.action_favorite:\n if (favoriteStops.isInFav(stop)) {\n favoriteStops.remove(stop);\n item.setIcon(R.drawable.ic_star_border_white_24dp);\n } else {\n favoriteStops.add(stop);\n item.setIcon(R.drawable.ic_star_white_24dp);\n }\n return true;\n case R.id.report:\n choiceReportDialog();\n return true;\n case R.id.report_warn:\n createAllReportDialog();\n return true;\n case R.id.action_add_line_on_home:\n ArrayList<CharSequence> lines = new ArrayList<>();\n for (Line l : stop.getLines()) {\n lines.add(\"Ligne \" + l.getShortName());\n }\n CharSequence[] lineString = lines.toArray(new CharSequence[lines.size()]);\n\n MaterialDialog dialog = new MaterialDialog.Builder(OneStopActivity.this)\n .title(R.string.line_choice)\n .items(lineString)\n .itemsCallback(new MaterialDialog.ListCallback() {\n @Override\n public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {\n StopZone s = stop;\n Line l = s.getLines().get(which);\n favoriteStopLine.addLineStop(l, s);\n dialog.dismiss();\n }\n }).build();\n dialog.show();\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n\n\n private void choiceReportDialog() {\n MaterialDialog dialog = new MaterialDialog.Builder(this)\n .title(R.string.choose_report_category)\n .items(R.array.report_types)\n .itemsCallback(new MaterialDialog.ListCallback() {\n @Override\n public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {\n if (ReportType.reportFromPosition(which) == ReportType.AUTRE) {\n createInputDialog();\n return;\n }\n createDialog(which, null);\n dialog.dismiss();\n }\n })\n .build();\n dialog.show();\n }\n\n private void createDialog(final int position, final String message) {\n String content = String.format(getString(R.string.create_report), getResources().getStringArray(R.array.report_types)[position], stop.getName());\n MaterialDialog dialog = new MaterialDialog.Builder(this)\n .title(R.string.confirm_report_title)\n .content(content)\n .negativeText(R.string.no)\n .positiveText(R.string.yes)\n .onPositive(new MaterialDialog.SingleButtonCallback() {\n @Override\n public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {\n Data.getData().getReportEvent().sendReport(getBaseContext(), new Report(stop, ReportType.reportFromPosition(position), message));\n Data.getData().update();\n dialog.dismiss();\n }\n }).build();\n dialog.show();\n }\n\n private void confirmDialog(final int position) {\n String content = String.format(getString(R.string.confirm_report), getResources().getStringArray(R.array.report_types)[stop.getReports().get(position).getType().getValueForString()], stop.getName());\n MaterialDialog dialog = new MaterialDialog.Builder(this)\n .title(R.string.confirm_report_title)\n .content(content)\n .negativeText(R.string.no)\n .positiveText(R.string.yes)\n .onPositive(new MaterialDialog.SingleButtonCallback() {\n @Override\n public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {\n Report r = stop.getReports().get(position);\n Data.getData().getReportEvent().confirmReport(getBaseContext(), r.getReportId());\n dialog.dismiss();\n }\n }).build();\n dialog.show();\n }\n\n private void createInputDialog() {\n new MaterialDialog.Builder(this)\n .title(R.string.input_report)\n .inputType(InputType.TYPE_CLASS_TEXT)\n .input(R.string.none, R.string.none, new MaterialDialog.InputCallback() {\n @Override\n public void onInput(MaterialDialog dialog, CharSequence input) {\n createDialog(ReportType.AUTRE.getValueForString(), input.toString());\n }\n }).show();\n }\n\n private void updateAllReportDialog() {\n if (current_dialog != null && current_dialog.isShowing()) {\n View view = current_dialog.getCustomView();\n RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);\n ReportAdapter adapter = new ReportAdapter(stop.getReports(), getBaseContext());\n recyclerView.setAdapter(adapter);\n adapter.SetOnItemClickListener(new ReportAdapter.OnItemClickListener() {\n @Override\n public void onItemClick(View v, int position) {\n confirmDialog(position);\n }\n });\n }\n }\n\n private void createAllReportDialog() {\n\n String title = getBaseContext().getResources().getQuantityString(R.plurals.report, stop.getReports().size());\n current_dialog = new MaterialDialog.Builder(this)\n .title(title)\n .customView(R.layout.view_recycler, false)\n .positiveText(R.string.OK)\n .build();\n\n View view = current_dialog.getCustomView();\n RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);\n\n recyclerView.setHasFixedSize(true);\n\n LinearLayoutManager layoutManager = new org.solovyev.android.views.llm.LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false);\n recyclerView.setLayoutManager(layoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n\n RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getBaseContext());\n recyclerView.addItemDecoration(itemDecoration);\n\n ReportAdapter adapter = new ReportAdapter(stop.getReports(), getBaseContext());\n recyclerView.setAdapter(adapter);\n adapter.SetOnItemClickListener(new ReportAdapter.OnItemClickListener() {\n\n @Override\n public void onItemClick(View v, int position) {\n confirmDialog(position);\n }\n });\n current_dialog.show();\n }\n\n public void onEvent(MessageUpdate event){\n if (event.type == MessageUpdate.Type.REPORT_UPDATE) {\n invalidateOptionsMenu();\n updateAllReportDialog();\n }\n }\n\n public class OneStopPageAdapter extends FragmentStatePagerAdapter {\n public OneStopPageAdapter(FragmentManager fm) {\n super(fm);\n }\n\n @Override\n public CharSequence getPageTitle(int linePosition) {\n return getString(R.string.one_line) + \" \" + stop.getLines().get(linePosition).getShortName();\n }\n\n @Override\n public int getCount() {\n return stop.getLines().size();\n }\n\n @Override\n public Fragment getItem(int position) {\n return StopLineFragment.newInstance(stop.getID(), position);\n }\n }\n}", "public class AllStopAdapter extends RecyclerView.Adapter<AllStopAdapter.ViewHolder> {\n\n public OnItemClickListener mItemClickListener;\n private ArrayList<StopZone> stops;\n\n public AllStopAdapter(ArrayList<StopZone> stops) {\n this.stops = stops;\n Collections.sort(stops, new Comparator<StopZone>() {\n @Override\n public int compare(StopZone s1, StopZone s2) {\n return s1.getName().compareToIgnoreCase(s2.getName());\n }\n });\n }\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n // create a new view\n View v = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.item_stop, parent, false);\n\n // set the view's size, margins, paddings and layout parameters\n ViewHolder vh = new ViewHolder(v);\n\n return vh;\n }\n\n @Override\n public void onBindViewHolder(ViewHolder holder, int position) {\n holder.textView.setText(stops.get(position).getName());\n }\n\n @Override\n public int getItemCount() {\n return stops.size();\n }\n\n public interface OnItemClickListener {\n void onItemClick(View view , int position);\n }\n\n public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {\n this.mItemClickListener = mItemClickListener;\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{\n\n public TextView textView;\n public LinearLayout linearLayout;\n\n\n public ViewHolder(View v) {\n super(v);\n textView = (TextView) itemView.findViewById(R.id.title);\n linearLayout = (LinearLayout) itemView.findViewById(R.id.element);\n v.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n if (mItemClickListener != null) {\n mItemClickListener.onItemClick(v, getPosition());\n }\n }\n }\n}", "public class DividerItemDecoration extends RecyclerView.ItemDecoration {\n private Drawable mDivider;\n private Paint paint;\n\n public DividerItemDecoration(Context context) {\n mDivider = context.getResources().getDrawable(R.drawable.separator);\n paint = new Paint();\n paint.setColor(context.getResources().getColor(R.color.separator));\n paint.setStrokeWidth(1);\n }\n\n @Override\n public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {\n int startX = parent.getPaddingLeft();\n int stopX = parent.getWidth() - parent.getPaddingRight();\n\n int childCount = parent.getChildCount();\n for (int i = 0; i < childCount -1; i++) {\n View child = parent.getChildAt(i);\n\n RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();\n\n int y = child.getBottom() + params.bottomMargin;\n\n c.drawLine(startX, y, stopX, y, paint);\n }\n }\n}", "public class Data {\n\n private static final String TAG = Data.class.getSimpleName();\n\n private DisruptEventHandler disruptEventHandler;\n private ReportEvent reportEvent;\n private RealTimes realTimes;\n private TamMap map;\n private RealTimeToUpdate toUpdate;\n\n private static Data data;\n\n private Data() {\n data = this;\n }\n\n public void init(Context context) {\n reportEvent = new ReportEvent(context);\n disruptEventHandler = new DisruptEventHandler(context);\n realTimes = new RealTimes(context);\n map = new TamMap(context);\n }\n\n public static synchronized Data getData() {\n if (data == null) {\n return new Data();\n } else {\n return data;\n }\n }\n\n public void update() {\n if (toUpdate != null) {\n if (toUpdate.isLine()) {\n realTimes.updateLine(toUpdate.getLine());\n } else {\n realTimes.updateStops(toUpdate.getStops());\n }\n }\n reportEvent.getReports();\n //disruptEventHandler.getReports();\n }\n\n public DisruptEventHandler getDisruptEventHandler() {\n return disruptEventHandler;\n }\n\n public TamMap getMap() {\n return map;\n }\n\n public void setToUpdate(RealTimeToUpdate toUpdate) {\n this.toUpdate = toUpdate;\n update();\n }\n\n public RealTimes getRealTimes() {\n return realTimes;\n }\n\n public ReportEvent getReportEvent() {\n return reportEvent;\n }\n}", "public class StopZone {\n private int _id;\n private int cityway_id;\n private int tam_id;\n private String name;\n private String search_name;\n private ArrayList<Line> lines;\n private ArrayList<Stop> stops;\n\n private Location location;\n private ArrayList<Report> reportList;\n private float distanceFromUser;\n\n public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){\n this.lines = new ArrayList<>();\n this.reportList = new ArrayList<>();\n this.name = name;\n this.cityway_id = cityway_id;\n this._id = _id;\n this.tam_id = tam_id;\n this.search_name = search_name;\n this.location = new Location(name);\n this.location.setLongitude(lon);\n this.location.setLatitude(lat);\n this.stops = new ArrayList<>();\n }\n\n public void addLine(Line line) {\n if (!this.lines.contains(line)) {\n this.lines.add(line);\n }\n }\n\n public void addStop(Stop stop) {\n this.stops.add(stop);\n }\n\n public String getName() {\n return name;\n }\n\n public ArrayList<Line> getLines() {\n return this.lines;\n }\n\n public int getID() {\n return this._id;\n }\n\n public void addReport(Report report) {\n this.reportList.add(report);\n }\n\n public ArrayList<Report> getReports() {\n ArrayList<Report> res = new ArrayList<>();\n Calendar date = Calendar.getInstance();\n for (Report r : this.reportList) {\n if (r.isValid(date)) res.add(r);\n }\n Collections.reverse(res); // the last is the oldest now.\n return res;\n }\n\n public void removeReport(Report rep) {\n this.reportList.remove(rep);\n }\n\n public void calcDistanceFromUser(Location user) {\n distanceFromUser = user.distanceTo(this.location);\n }\n\n public String getNormalisedName() {\n return search_name;\n }\n\n public float getDistanceFromUser() {\n return distanceFromUser;\n }\n\n public ArrayList<Stop> getStops(Line line) {\n ArrayList<Stop> res = new ArrayList<>();\n for (Stop stop : stops) {\n if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) {\n res.add(stop);\n }\n }\n return res;\n }\n\n public ArrayList<Stop> getStops() {\n return stops;\n }\n\n @Override\n public String toString() {\n return \"StopZone{\" +\n \"name='\" + name + '\\'' +\n \", lines=\" + lines +\n \", stops=\" + stops +\n '}';\n }\n}" ]
import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.activity.OneStopActivity; import flying.grub.tamtime.adapter.AllStopAdapter; import flying.grub.tamtime.adapter.DividerItemDecoration; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.map.StopZone;
package flying.grub.tamtime.fragment; public class AllStopFragment extends Fragment { private RecyclerView recyclerView; private AllStopAdapter adapter; private RecyclerView.LayoutManager layoutManager;
private ArrayList<StopZone> currentDisplayedStop;
4
developers-payu-latam/payu-latam-java-payments-sdk
src/main/java/com/payu/sdk/PayUPayments.java
[ "enum RequestMethod {\n\t/** The get request method. */\n\tGET,\n\t/** The post request method. */\n\tPOST,\n\t/** The delete request method. */\n\tDELETE,\n\t/** The put request method. */\n\tPUT\n}", "public final class HttpClientHelper {\n\n\t/** The connection timeout in ms. */\n\tprivate static final int CONNECTION_TIMEOUT = 10000;\n\n\t/** The socket timeout in ms. */\n\tpublic static final int SOCKET_TIMEOUT = 85000;\n\n\t/**\n\t * Default private empty constructor\n\t */\n\tprivate HttpClientHelper() {\n\t}\n\n\t/**\n\t * Sends the post request to the server\n\t *\n\t * @param request\n\t * The request to be sent to the server\n\t * @param requestMethod\n\t * The request method to be sent to the server\n\t * @return The response in a xml format\n\t * @throws ConnectionException\n\t * @throws SDKException\n\t */\n\tpublic static String sendRequest(Request request, RequestMethod requestMethod)\n\t\t\tthrows PayUException, ConnectionException {\n\n\t\treturn sendRequest(request, requestMethod, SOCKET_TIMEOUT);\n\t}\n\t\n\t/**\n\t * Send request with extra headers.\n\t *\n\t * @param request the request\n\t * @param headers the headers\n\t * @param requestMethod the request method\n\t * @return the string\n\t * @throws PayUException the pay U exception\n\t * @throws ConnectionException the connection exception\n\t */\n\tpublic static String sendRequestWithExtraHeaders(Request request, Map<String, String> headers,\n\t\t\tRequestMethod requestMethod) throws PayUException, ConnectionException {\n\n\t\treturn sendRequest(request, headers, requestMethod, SOCKET_TIMEOUT);\n\t}\n\n\n\t/**\n\t * Sends the post request to the server\n\t *\n\t * @param request\n\t * The request to be sent to the server\n\t * @param requestMethod\n\t * The request method to be sent to the server\n\t * @param socketTimeOut\n\t * \t\t\t The socket time out.\n\t * @return The response in a xml format\n\t * @throws ConnectionException\n\t * @throws SDKException\n\t */\n\tpublic static String sendRequest(Request request, RequestMethod requestMethod, Integer socketTimeOut)\n\t\t\tthrows PayUException, ConnectionException {\n\n\t\tHttpClient httpClient = new DefaultHttpClient();\n\t\tsetHttpClientParameters(httpClient.getParams(), socketTimeOut);\n\t\thttpClient = doModifySSLOptions(request, requestMethod, httpClient);\n\n\t\ttry {\n\n\t\t\tHttpRequestBase httpRequest = createHttpRequest(request, requestMethod);\n\n\t\t\tHttpResponse httpResponse = httpClient.execute(httpRequest);\n\n\t\t\tif (httpResponse == null) {\n\t\t\t\tthrow new ConnectionException(\"No response from server\");\n\t\t\t}\n\n\t\t\tInteger httpStatus = httpResponse.getStatusLine().getStatusCode();\n\n\t\t\tInteger[] successStatus = { HttpStatus.SC_OK, HttpStatus.SC_CREATED,\n\t\t\t\t\tHttpStatus.SC_ACCEPTED };\n\n\t\t\tif (Arrays.asList(successStatus).contains(httpStatus)) {\n\n\t\t\t\treturn getXmlResponse(httpResponse);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn manageResponse(httpResponse);\n\t\t\t}\n\n\t\t}\n\t\tcatch (PayUException e) {\n\t\t\tthrow e;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new ConnectionException(e.getMessage(), e);\n\t\t}\n\t\tfinally {\n\t\t\thttpClient.getConnectionManager().shutdown();\n\t\t}\n\t}\n\t\n\t/**\n\t * Send request.\n\t *\n\t * @param request the request\n\t * @param headers the headers\n\t * @param requestMethod the request method\n\t * @param socketTimeOut the socket time out\n\t * @return the string\n\t * @throws PayUException the pay U exception\n\t * @throws ConnectionException the connection exception\n\t */\n\tpublic static String sendRequest(Request request, Map<String, String> headers,\n\t\t\tRequestMethod requestMethod, Integer socketTimeOut)\n\t\t\tthrows PayUException, ConnectionException {\n\n\t\tHttpClient httpClient = new DefaultHttpClient();\n\t\tsetHttpClientParameters(httpClient.getParams(), socketTimeOut);\n\n\t\thttpClient = doModifySSLOptions(request, requestMethod, httpClient);\n\n\t\ttry {\n\n\t\t\tHttpRequestBase httpRequest = createHttpRequest(request, requestMethod);\n\t\t\t\n\t\t\taddRequestExtraHeaders(httpRequest, headers);\n\n\t\t\tHttpResponse httpResponse = httpClient.execute(httpRequest);\n\n\t\t\tif (httpResponse == null) {\n\t\t\t\tthrow new ConnectionException(\"No response from server\");\n\t\t\t}\n\n\t\t\tInteger httpStatus = httpResponse.getStatusLine().getStatusCode();\n\n\t\t\tInteger[] successStatus = { HttpStatus.SC_OK, HttpStatus.SC_CREATED,\n\t\t\t\t\tHttpStatus.SC_ACCEPTED };\n\n\t\t\tif (Arrays.asList(successStatus).contains(httpStatus)) {\n\n\t\t\t\treturn getXmlResponse(httpResponse);\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn manageResponse(httpResponse);\n\t\t\t}\n\n\t\t}\n\t\tcatch (PayUException e) {\n\t\t\tthrow e;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new ConnectionException(e.getMessage(), e);\n\t\t}\n\t\tfinally {\n\t\t\thttpClient.getConnectionManager().shutdown();\n\t\t}\n\t}\n\n\t/**\n\t * This method validates the url and call the method that disable the SSL options when the case is not\n\t * PRD or Sandbox enviroments\n\t * @param request\n\t * @param requestMethod\n\t * @param httpClient\n\t * @return httpClient\n\t * @throws ConnectionException\n\t */\n\tprivate static HttpClient doModifySSLOptions(final Request request, final RequestMethod requestMethod, HttpClient httpClient)\n\t\t\tthrows ConnectionException {\n\t\tString url = request.getRequestUrl(requestMethod);\n\t\tif(!url.contains(Constants.PAYMENTS_PRD_URL) && !url.contains(Constants.PAYMENTS_SANDBOX_URL) && \n\t\t\t\t!url.contains(Constants.PAYMENTS_STG_URL)){\n\t\t\thttpClient = WebClientDevWrapper.wrapClient(httpClient);\n\t\t}else{\n\t\t\thttpClient = buildHttpClient(httpClient);\n\t\t}\n\t\treturn httpClient;\n\t}\n\n\t/**\n\t * Manage the response with specific exceptions\n\t *\n\t * @param httpResponse\n\t * The response sent by the server\n\t * @return The reason of the error response\n\t * @throws IOException\n\t * @throws SDKException\n\t */\n\tprivate static String manageResponse(HttpResponse httpResponse)\n\t\t\tthrows IOException, SDKException {\n\t\tint httpStatus = httpResponse.getStatusLine().getStatusCode();\n\t\tswitch (httpStatus) {\n\t\tcase HttpStatus.SC_UNAUTHORIZED: {\n\t\t\tthrow new AuthenticationException(\"Invalid credentials\");\n\t\t}\n\t\tcase HttpStatus.SC_SERVICE_UNAVAILABLE: {\n\t\t\tthrow new ConnectionException(httpResponse.getStatusLine()\n\t\t\t\t\t.getReasonPhrase());\n\t\t}\n\t\tcase HttpStatus.SC_NOT_FOUND: {\n\t\t\tString error;\n\t\t\ttry{\n\t\t\t\terror = getErrorMessage(httpResponse);\n\t\t\t}catch(Exception exception){\n\t\t\t\tthrow new ConnectionException(httpResponse.getStatusLine().toString());\n\t\t\t}\n\t\t\tthrow new PayUException(ErrorCode.NO_RESULTS_FOUND, error);\n\t\t}\n\t\tcase HttpStatus.SC_UNPROCESSABLE_ENTITY: {\n\t\t\tString error = getErrorMessage(httpResponse);\n\t\t\tthrow new PayUException(ErrorCode.INVALID_PARAMETERS, error);\n\t\t}\n\t\tdefault: {\n\t\t\tString error = getErrorMessage(httpResponse);\n\t\t\tthrow new ConnectionException(error);\n\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Gets the response error message\n\t *\n\t * @param httpResponse\n\t * The response sent by the server\n\t * @return The message associated to the error response\n\t * @throws PayUException\n\t * @throws IOException\n\t */\n\tprivate static String getErrorMessage(HttpResponse httpResponse)\n\t\t\tthrows PayUException, IOException, ConnectionException {\n\n\t\tString error = httpResponse.getStatusLine().getReasonPhrase();\n\t\ttry{\n\t\t\tString xml = getXmlResponse(httpResponse);\n\n\t\t\tif (xml != null && !xml.isEmpty()) {\n\n\t\t\t\tErrorResponse response;\n\n\t\t\t\ttry {\n\n\t\t\t\t\tresponse = JaxbUtil.convertXmlToJava(ErrorResponse.class, xml);\n\n\t\t\t\t} catch (PayUException ex) {\n\t\t\t\t\tLoggerUtil.debug(\"Invalid XML entity\");\n\t\t\t\t\treturn error;\n\t\t\t\t}\n\n\t\t\t\tif (response.getDescription() != null) {\n\t\t\t\t\treturn response.getDescription();\n\t\t\t\t}\n\n\t\t\t\tif (response.getErrorList() != null\n\t\t\t\t\t\t&& response.getErrorList().length > 0) {\n\t\t\t\t\treturn Arrays.toString(response.getErrorList());\n\t\t\t\t}\n\t\t\t}\n\t\t} catch(Exception exception){\n\t\t\tthrow new ConnectionException(httpResponse.getStatusLine().toString());\n\t\t}\n\n\t\treturn error;\n\t}\n\n\t/**\n\t * Get xml response\n\t *\n\t * @param httpResponse\n\t * The response sent by the server\n\t * @return The xml associated to the response\n\t * @throws PayUException\n\t * @throws IOException\n\t */\n\tprivate static String getXmlResponse(HttpResponse httpResponse)\n\t\t\tthrows PayUException, IOException {\n\n\t\tHttpEntity entity = httpResponse.getEntity();\n\t\tInputStream inputStream = (InputStream) entity.getContent();\n\t\tString xml = inputStreamToString(inputStream);\n\n\t\tif (!xml.isEmpty()) {\n\t\t\tLoggerUtil.debug(\"Response:\\n {0}\", XmlFormatter.prettyFormat(xml));\n\t\t}\n\n\t\treturn xml;\n\t}\n\n\t/**\n\t * Sets the parameters to the request\n\t *\n\t * @param params\n\t * The parameters to be set\n\t * @param socketTimeOut socket time out.\n\t */\n\tprivate static void setHttpClientParameters(HttpParams params, Integer socketTimeOut) {\n\n\t\tHttpProtocolParams\n\t\t\t\t.setContentCharset(params, Constants.DEFAULT_ENCODING);\n\t\tHttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);\n\t\tHttpConnectionParams.setSoTimeout(params, socketTimeOut);\n\t}\n\n\t/**\n\t * Creates a http request with the given request\n\t *\n\t * @param request\n\t * The original request\n\t * @param requestMethod\n\t * The request method to be sent to the server\n\t * @return The created http request\n\t * @throws URISyntaxException\n\t * @throws UnsupportedEncodingException\n\t * @throws PayUException\n\t * @throws ConnectionException\n\t */\n\tprivate static HttpRequestBase createHttpRequest(Request request,\n\t\t\tRequestMethod requestMethod) throws URISyntaxException,\n\t\t\tUnsupportedEncodingException, PayUException, ConnectionException {\n\n\t\tString url = request.getRequestUrl(requestMethod);\n\n\t\tURI postUrl = new URI(url);\n\n\t\tHttpRequestBase httpMethod;\n\n\t\tLoggerUtil.debug(\"sending request...\");\n\n\t\tString xml = Constants.EMPTY_STRING;\n\n\t\tswitch (requestMethod) {\n\t\tcase POST:\n\t\t\thttpMethod = new HttpPost();\n\t\t\tbreak;\n\t\tcase GET:\n\t\t\thttpMethod = new HttpGet();\n\t\t\tbreak;\n\t\tcase DELETE:\n\t\t\thttpMethod = new HttpDelete();\n\t\t\tbreak;\n\t\tcase PUT:\n\t\t\thttpMethod = new HttpPut();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new ConnectionException(\"Invalid connection method\");\n\t\t}\n\n\t\thttpMethod.addHeader(\"Content-Type\", MediaType.XML.getCode()\n\t\t\t\t+ \"; charset=utf-8\");\n\n\t\tLanguage lng = request.getLanguage() != null ? request.getLanguage() : PayU.language;\n\t\thttpMethod.setHeader(\"Accept-Language\", lng.name());\n\n\t\t// Sets the method entity\n\t\tif (httpMethod instanceof HttpEntityEnclosingRequestBase) {\n\t\t\txml = request.toXml();\n\t\t\t((HttpEntityEnclosingRequestBase) httpMethod)\n\t\t\t\t\t.setEntity(new StringEntity(xml, Constants.DEFAULT_ENCODING));\n\t\t\tLoggerUtil.debug(\"Message to send:\\n {0}\", xml);\n\t\t}\n\n\t\thttpMethod.setURI(postUrl);\n\n\t\taddRequestHeaders(request, httpMethod);\n\n\t\tLoggerUtil.debug(\"URL to send:\\n {0}\", url);\n\n\t\treturn httpMethod;\n\t}\n\n\t/**\n\t * Updates the base request to add the header\n\t *\n\t * @param requestBase\n\t * The request that needs its header\n\t */\n\tprivate static void addRequestHeaders(Request apiRequest, HttpRequestBase requestBase) {\n\n\t\trequestBase.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.XML.getCode()\n\t\t\t\t+ \"; charset=utf-8\");\n\t\trequestBase.addHeader(HttpHeaders.ACCEPT, MediaType.XML.getCode());\n\n\t\tString username = getUserName(apiRequest);\n\n\t\tString password = getPassword(apiRequest);\n\n\t\tCredentials credentials = new UsernamePasswordCredentials(username, password);\n\n\t\trequestBase.addHeader(BasicScheme.authenticate(credentials,\n\t\t\t\tConstants.DEFAULT_ENCODING, false));\n\t}\n\t\n\t/**\n\t * Adds the request extra headers.\n\t *\n\t * @param httpRequest the http request\n\t * @param headers the headers\n\t * @throws ConnectionException \n\t */\n\tprivate static void addRequestExtraHeaders(HttpRequestBase httpRequest,\n\t\t\tMap<String, String> headers) throws ConnectionException {\n\n\t\ttry {\n\t\t\tfor (Map.Entry<String, String> entry : headers.entrySet()) {\n\t\t\t\thttpRequest.setHeader(entry.getKey(), entry.getValue());\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new ConnectionException(\n\t\t\t\t\t\"Exception caught when adding the extra headers to be sent\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Gets the user name.\n\t * \n\t * @param apiRequest\n\t * @return\n\t */\n\tprivate static String getUserName(Request apiRequest) {\n\n\t\tMerchant merchant = null;\n\n\t\tif (apiRequest instanceof CommandRequest) {\n\t\t\tmerchant = ((CommandRequest) apiRequest).getMerchant();\n\t\t}\n\n\t\treturn apiRequest.getApiLogin() != null ? apiRequest.getApiLogin()\n\t\t\t\t: merchant != null && merchant.getApiLogin() != null ? merchant\n\t\t\t\t\t\t.getApiLogin() : PayU.apiLogin;\n\t}\n\n\t/**\n\t * Gets the password.\n\t * \n\t * @param apiRequest\n\t * @return\n\t */\n\tprivate static String getPassword(Request apiRequest) {\n\t\t\n\t\tMerchant merchant = null;\n\n\t\tif (apiRequest instanceof CommandRequest) {\n\t\t\tmerchant = ((CommandRequest) apiRequest).getMerchant();\n\t\t}\n\n\t\treturn apiRequest.getApiKey() != null ? apiRequest.getApiKey()\n\t\t\t\t: merchant != null && merchant.getApiKey() != null ? merchant\n\t\t\t\t\t\t.getApiKey() : PayU.apiKey;\n\t}\n\n\t/**\n\t * Transforms an incoming InputStream into a String\n\t *\n\t * @param inputStream\n\t * The stream to be transformed\n\t * @return The transformed stream\n\t * @throws IOException\n\t * @throws PayUException\n\t */\n\tprivate static String inputStreamToString(InputStream inputStream)\n\t\t\tthrows IOException, PayUException {\n\n\t\tBufferedReader bufferedReader = new BufferedReader(\n\t\t\t\tnew InputStreamReader(inputStream, Constants.DEFAULT_ENCODING));\n\t\tStringBuilder stringBuilder = new StringBuilder();\n\n\t\tString line = null;\n\t\ttry {\n\t\t\twhile ((line = bufferedReader.readLine()) != null) {\n\t\t\t\tstringBuilder.append(line).append(Constants.LINE_SEPARATOR);\n\t\t\t}\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tinputStream.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new PayUException(\n\t\t\t\t\t\tPayUException.ErrorCode.XML_DESERIALIZATION_ERROR, e);\n\t\t\t}\n\t\t}\n\n\t\treturn stringBuilder.toString();\n\t}\n\n\t/**\n\t * Builds a HttpClient\n\t * @param base The http client to wrap\n\t * @return a {@link HttpClient}\n\t */\n\tprivate static HttpClient buildHttpClient(final HttpClient base) {\n\n\t\tfinal SSLSocketFactory ssf = new SSLSocketFactory(SSLContexts.createDefault(),\n\t\t\t\tnew String[] { \"TLSv1\", \"TLSv1.1\", \"TLSv1.2\" }, null, null);\n\t\tbase.getConnectionManager()\n\t\t\t\t.getSchemeRegistry().register(new Scheme(\"https\", Constants.HTTPS_PORT, ssf));\n\n\t\treturn new DefaultHttpClient(base.getConnectionManager(), base.getParams());\n\n\t}\n}", "@XmlRootElement(name = \"transaction\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class Transaction implements Serializable {\n\n\t/** The generated serial version Id */\n\tprivate static final long serialVersionUID = -6954674089900251114L;\n\t/** The transaction order */\n\t@XmlElement(required = false)\n\tprivate Order order;\n\t/** The transaction credit card */\n\t@XmlElement(required = false)\n\tprivate CreditCard creditCard;\n\t/** The transaction debit card */\n\t@XmlElement(required = false)\n\tprivate DebitCard debitCard;\n\t/** The transaction credit card swipe */\n\t@XmlElement(required = false)\n\tprivate CreditCardSwipe creditCardSwipe;\n\t// Token stuff\n\t/** The transaction credit card token id */\n\t@XmlElement(required = false)\n\tprivate String creditCardTokenId;\n\t/** If the transaction credit card token was created */\n\t@XmlElement(required = false)\n\tprivate Boolean createCreditCardToken;\n\t/** The transaction type */\n\t@XmlElement(required = false)\n\tprivate TransactionType type;\n\t/** The transaction parent id */\n\t@XmlElement(required = false)\n\tprivate String parentTransactionId;\n\t/** The transaction payment method */\n\t@XmlElement(required = false)\n\tprivate String paymentMethod;\n\n\t/** The transaction integration method. */\n\t@XmlElement(required = false)\n\tprivate TransactionIntegrationMethod integrationMethod;\n\t/** The transaction source */\n\t@XmlElement(required = false)\n\tprivate TransactionSource source;\n\t/** The transaction payment country */\n\t@XmlElement(required = false)\n\tprivate PaymentCountry paymentCountry;\n\t/** The transaction response */\n\t@XmlElement(required = false)\n\tprivate TransactionResponse transactionResponse;\n\n\t/** The transaction payer. */\n\t@XmlElement(required = false)\n\tprivate Payer payer;\n\n\t/** The transaction device session id */\n\t@XmlElement(required = false)\n\tprivate String deviceSessionId;\n\t/** The buyer IP address. */\n\t@XmlElement(required = false)\n\tprivate String ipAddress;\n\t/** The browser cookie. */\n\t@XmlElement(required = false)\n\tprivate String cookie;\n\t/** The browser user agent. */\n\t@XmlElement(required = false)\n\tprivate String userAgent;\n\t/** The expiration date of the transaction. */\n\t@XmlElement(required = false)\n\t@XmlJavaTypeAdapter(DateAdapter.class)\n\tprivate Date expirationDate;\n\n\t/** The map of the values. */\n\t@XmlJavaTypeAdapter(MapAdditionalValueAdapter.class)\n\tprivate Map<String, AdditionalValue> additionalValues;\n\n\t/** The extra parameters. */\n\t@XmlJavaTypeAdapter(MapExtraParameterAdapter.class)\n\tprivate Map<String, String> extraParameters;\n\n\t/** the related transaction id. */\n\t@XmlElement(required = false)\n\tprivate String id;\n\n\t/**\n\t * Explains why a transaction is requested to be cancelled\n\t */\n\t@XmlElement(required = false)\n\tprivate String reason;\n\n\t/** The Bcash request */\n\t@XmlElement\n\tprivate BcashRequest bcashRequest;\n\t\n\t/** The platform ID */\n\t@XmlElement(required = false)\n\tprivate Integer platformId;\n\n\t@XmlElement(required = false)\n\tprivate Boolean termsAndConditionsAcepted;\n\n\t/**\n\t * Returns the transaction order\n\t *\n\t * @return the order\n\t */\n\tpublic Order getOrder() {\n\t\treturn order;\n\t}\n\n\t/**\n\t * Returns the transaction credit card\n\t *\n\t * @return the creditCard\n\t */\n\tpublic CreditCard getCreditCard() {\n\t\treturn creditCard;\n\t}\n\t\n\t/**\n\t * Returns the transaction debit card.\n\t *\n\t * @return the debit card\n\t */\n\tpublic DebitCard getDebitCard() {\n\t\treturn debitCard;\n\t}\n\n\t/**\n\t * Returns the transaction credit card swipe\n\t *\n\t * @return the credit card swipe\n\t */\n\tpublic CreditCardSwipe getCreditCardSwipe() {\n\t\treturn creditCardSwipe;\n\t}\n\n\t/**\n\t * Returns the transaction credit card token id\n\t *\n\t * @return the credit card token Id for recurrent payments.\n\t */\n\tpublic String getCreditCardTokenId() {\n\t\treturn creditCardTokenId;\n\t}\n\n\t/**\n\t * Returns the create credit card token flag for recurrent payments\n\t *\n\t * @return the flag.\n\t */\n\tpublic Boolean getCreateCreditCardToken() {\n\t\treturn createCreditCardToken;\n\t}\n\n\t/**\n\t * Returns the transaction type\n\t *\n\t * @return the type\n\t */\n\tpublic TransactionType getType() {\n\t\treturn type;\n\t}\n\n\t/**\n\t * Returns the transaction parent id\n\t *\n\t * @return the parent transaction\n\t */\n\tpublic String getParentTransactionId() {\n\t\treturn parentTransactionId;\n\t}\n\n\t/**\n\t * Returns the transaction payment method\n\t *\n\t * @return the payment method\n\t */\n\tpublic String getPaymentMethod() {\n\t\treturn paymentMethod;\n\t}\n\n\t/**\n\t * Gets the transaction integration method.\n\t *\n\t * @return the transaction integration method\n\t */\n\tpublic TransactionIntegrationMethod getIntegrationMethod() {\n\t\treturn integrationMethod;\n\t}\n\n\t/**\n\t * Returns the transaction source\n\t *\n\t * @return the source\n\t */\n\tpublic TransactionSource getSource() {\n\t\treturn source;\n\t}\n\n\t/**\n\t * Returns the transaction payment country\n\t *\n\t * @return the payment country\n\t */\n\tpublic PaymentCountry getPaymentCountry() {\n\t\treturn paymentCountry;\n\t}\n\n\t/**\n\t * Returns the transaction response\n\t *\n\t * @return the transaction response\n\t */\n\tpublic TransactionResponse getTransactionResponse() {\n\t\treturn transactionResponse;\n\t}\n\n\t/**\n\t * Returns the transaction payer\n\t *\n\t * @return the payer\n\t */\n\tpublic Payer getPayer() {\n\t\treturn payer;\n\t}\n\n\t/**\n\t * Returns the transaction device session id\n\t *\n\t * @return the device session id\n\t */\n\tpublic String getDeviceSessionId() {\n\t\treturn deviceSessionId;\n\t}\n\n\t/**\n\t * Returns the buyer IP address.\n\t *\n\t * @return the IP address\n\t */\n\tpublic String getIpAddress() {\n\t\treturn ipAddress;\n\t}\n\n\t/**\n\t * Returns the browser cookie\n\t *\n\t * @return the cookie\n\t */\n\tpublic String getCookie() {\n\t\treturn cookie;\n\t}\n\n\t/**\n\t * Returns the browser user agent\n\t *\n\t * @return the user agent\n\t */\n\tpublic String getUserAgent() {\n\t\treturn userAgent;\n\t}\n\n\t/**\n\t * Returns the transaction expiration date\n\t *\n\t * @return the expiration date\n\t */\n\tpublic Date getExpirationDate() {\n\t\treturn expirationDate;\n\t}\n\n\t/**\n\t * Returns the transaction additional values\n\t *\n\t * @return the additional values\n\t */\n\tpublic Map<String, AdditionalValue> getAdditionalValues() {\n\t\treturn additionalValues;\n\t}\n\n\t/**\n\t * Returns the transaction extra parameters\n\t *\n\t * @return the extra parameters\n\t */\n\tpublic Map<String, String> getExtraParameters() {\n\t\treturn extraParameters;\n\t}\n\n\t/**\n\t * Returns the Bcash request\n\t *\n\t * @return the Bcash request\n\t */\n\tpublic BcashRequest getBcashRequest() {\n\n\t\treturn bcashRequest;\n\t}\n\n\t/**\n\t * Returns the platform ID\n\t * \n\t * @return the platform ID\n\t */\n\tpublic Integer getPlatformId() {\n\n\t\treturn platformId;\n\t}\n\n\t/**\n\t * Return the terms and conditions accepted\n\t *\n\t * @return the terms and conditions accepted\n\t */\n\tpublic Boolean getTermsAndConditionsAcepted() {\n\n\t\treturn termsAndConditionsAcepted;\n\t}\n\n\t/**\n\t * Sets the transaction order\n\t *\n\t * @param order\n\t * the order to set\n\t */\n\tpublic void setOrder(Order order) {\n\t\tthis.order = order;\n\t}\n\n\t/**\n\t * Sets the transaction credit card\n\t *\n\t * @param creditCard\n\t * the credit card to set\n\t */\n\tpublic void setCreditCard(CreditCard creditCard) {\n\t\tthis.creditCard = creditCard;\n\t}\n\n\t/**\n\t * Sets the transaction debit card.\n\t *\n\t * @param debitCard the new debit card\n\t */\n\tpublic void setDebitCard(DebitCard debitCard) {\n\t\tthis.debitCard = debitCard;\n\t}\n\t\n\t/**\n\t * Sets the transaction credit card swipe\n\t *\n\t * @param creditCardSwipe\n\t * the credit card swipe to set\n\t */\n\tpublic void setCreditCardSwipe(CreditCardSwipe creditCardSwipe) {\n\t\tthis.creditCardSwipe = creditCardSwipe;\n\t}\n\n\t/**\n\t * Sets the transaction credit card token id\n\t *\n\t * @param creditCardTokenId\n\t * the creditCardTokenId to set\n\t */\n\tpublic void setCreditCardTokenId(String creditCardTokenId) {\n\t\tthis.creditCardTokenId = creditCardTokenId;\n\t}\n\n\t/**\n\t * Sets the transaction create credit card token flag\n\t *\n\t * @param createCreditCardToken\n\t * the flag to set\n\t */\n\tpublic void setCreateCreditCardToken(Boolean createCreditCardToken) {\n\t\tthis.createCreditCardToken = createCreditCardToken;\n\t}\n\n\t/**\n\t * Sets the transaction type\n\t *\n\t * @param type\n\t * the type to set\n\t */\n\tpublic void setType(TransactionType type) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Sets the transaction parent id\n\t *\n\t * @param parentTransaction\n\t * the parent transaction to set\n\t */\n\tpublic void setParentTransactionId(String parentTransactionId) {\n\t\tthis.parentTransactionId = parentTransactionId;\n\t}\n\n\t/**\n\t * Sets the transaction payment method\n\t *\n\t * @param paymentMethod\n\t * the payment method to set\n\t */\n\tpublic void setPaymentMethod(String paymentMethod) {\n\t\tthis.paymentMethod = paymentMethod;\n\t}\n\n\t/**\n\t * Sets the transaction integration method.\n\t *\n\t * @param integrationMethod the new transaction integration method\n\t */\n\tpublic void setIntegrationMethod(TransactionIntegrationMethod integrationMethod) {\n\t\tthis.integrationMethod = integrationMethod;\n\t}\n\t\n\t/**\n\t * Sets the transaction source\n\t *\n\t * @param source\n\t * the source to set\n\t */\n\tpublic void setSource(TransactionSource source) {\n\t\tthis.source = source;\n\t}\n\n\t/**\n\t * Sets the transaction payment country\n\t *\n\t * @param paymentCountry\n\t * the payment country to set\n\t */\n\tpublic void setPaymentCountry(PaymentCountry paymentCountry) {\n\t\tthis.paymentCountry = paymentCountry;\n\t}\n\n\t/**\n\t * Sets the transaction response\n\t *\n\t * @param transactionResponse\n\t * the transaction response to set\n\t */\n\tpublic void setTransactionResponse(TransactionResponse transactionResponse) {\n\t\tthis.transactionResponse = transactionResponse;\n\t}\n\n\t/**\n\t * Sets the transactions payer\n\t *\n\t * @param payer\n\t * the payer to set\n\t */\n\tpublic void setPayer(Payer payer) {\n\t\tthis.payer = payer;\n\t}\n\n\t/**\n\t * Sets the transaction device session id\n\t *\n\t * @param deviceSessionId\n\t * the device session id to set\n\t */\n\tpublic void setDeviceSessionId(String deviceSessionId) {\n\t\tthis.deviceSessionId = deviceSessionId;\n\t}\n\n\t/**\n\t * Sets the buyer IP address.\n\t *\n\t * @param ipAddress\n\t * the IP address to set\n\t */\n\tpublic void setIpAddress(String ipAddress) {\n\t\tthis.ipAddress = ipAddress;\n\t}\n\n\t/**\n\t * Sets the browser cookie\n\t *\n\t * @param cookie\n\t * the cookie to set\n\t */\n\tpublic void setCookie(String cookie) {\n\t\tthis.cookie = cookie;\n\t}\n\n\t/**\n\t * Sets the browser user agent\n\t *\n\t * @param userAgent\n\t * the user agent to set\n\t */\n\tpublic void setUserAgent(String userAgent) {\n\t\tthis.userAgent = userAgent;\n\t}\n\n\t/**\n\t * Sets the transaction expiration date\n\t *\n\t * @param expirationDate\n\t * the expiration date to set\n\t */\n\tpublic void setExpirationDate(Date expirationDate) {\n\t\tthis.expirationDate = expirationDate;\n\t}\n\n\t/**\n\t * Sets the transaction additional values\n\t *\n\t * @param additionalValues\n\t * the additional values to set\n\t */\n\tpublic void setAdditionalValues(\n\t\t\tMap<String, AdditionalValue> additionalValues) {\n\t\tthis.additionalValues = additionalValues;\n\t}\n\n\t/**\n\t * Sets the transaction extra parameters\n\t *\n\t * @param extraParameters\n\t * the extra parameters to set\n\t */\n\tpublic void setExtraParameters(Map<String, String> extraParameters) {\n\t\tthis.extraParameters = extraParameters;\n\t}\n\n\t/**\n\t * Adds an extra parameter to the transaction\n\t *\n\t * @param name\n\t * The name of the extra parameter\n\t * @param value\n\t * The value of the extra parameter\n\t * @throws InvalidParametersException\n\t */\n\tpublic synchronized void addExtraParameter(String name, String value)\n\t\t\tthrows InvalidParametersException {\n\n\t\tif (name == null || value == null) {\n\t\t\tthrow new InvalidParametersException(\n\t\t\t\t\t\"neither the name nor the value of the extra parameter \"\n\t\t\t\t\t\t\t+ \"can be null\");\n\t\t}\n\n\t\tif (extraParameters == null) {\n\t\t\textraParameters = new HashMap<String, String>();\n\t\t}\n\n\t\textraParameters.put(name, value);\n\t}\n\n\t/**\n\t * @return the reason\n\t */\n\tpublic String getReason() {\n\n\t\treturn reason;\n\t}\n\n\t/**\n\t * @param reason the reason to set\n\t */\n\tpublic void setReason(String reason) {\n\n\t\tthis.reason = reason;\n\t}\n\n\t/**\n\t * Sets the transaction id\n\t *\n\t * @param transactionId\n\t * the transactionId to set\n\t */\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Returns the transaction id\n\t *\n\t * @return the transactionId\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Sets the Bcash request\n\t *\n\t * @param bcashRequest\n\t * the Bcash request to set\n\t */\n\tpublic void setBcashRequest(BcashRequest bcashRequest) {\n\n\t\tthis.bcashRequest = bcashRequest;\n\t}\n\n\t/**\n\t * Sets the platform ID\n\t * \n\t * @param platformId\n\t * the platform ID\n\t */\n\tpublic void setPlatformId(Integer platformId) {\n\n\t\tthis.platformId = platformId;\n\t}\n\n\t/**\n\t * Sets the terms and conditions accepted\n\t *\n\t * @param termsAndConditionsAcepted\n\t * the terms and conditions accepted to set\n\t */\n\tpublic void setTermsAndConditionsAcepted(Boolean termsAndConditionsAcepted) {\n\n\t\tthis.termsAndConditionsAcepted = termsAndConditionsAcepted;\n\t}\n\n}", "@XmlRootElement(name = \"transactionResponse\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class TransactionResponse implements Serializable {\n\n\t/** The generated serial version Id */\n\tprivate static final long serialVersionUID = 7073372114746122059L;\n\t/** the related order id. */\n\t@XmlElement(required = false)\n\tprivate Long orderId;\n\t/** the order's reference code */\n\t@XmlElement(required = false)\n\tprivate String orderReferenceCode;\n\t/** the related transaction id. */\n\t@XmlElement(required = false)\n\tprivate String transactionId;\n\t/** The transaction state */\n\t@XmlElement(required = false)\n\tprivate TransactionState state;\n\t/** The payment network response code. */\n\t@XmlElement(required = false)\n\tprivate String paymentNetworkResponseCode;\n\t/** The error message related to the payment network response. */\n\t@XmlElement(required = false)\n\tprivate String paymentNetworkResponseErrorMessage;\n\t/** The trazability code related with the response. */\n\t@XmlElement(required = false)\n\tprivate String trazabilityCode;\n\t/** The authorization code. */\n\t@XmlElement(required = false)\n\tprivate String authorizationCode;\n\t/** The transaction pending reason */\n\t@XmlElement(required = false)\n\tprivate TransactionPendingReason pendingReason;\n\t/** The transaction response code */\n\t@XmlElement(required = false)\n\tprivate TransactionResponseCode responseCode;\n\t/** The error code. */\n\t@XmlElement(required = false)\n\tprivate TransactionErrorCode errorCode;\n\t/** The message related to the response code. */\n\t@XmlElement(required = false)\n\tprivate String responseMessage;\n\t/** The payment date. */\n\t@XmlElement(required = false)\n\tprivate String transactionDate;\n\t/** The payment time. */\n\t@XmlElement(required = false)\n\tprivate String transactionTime;\n\t/** The operation date. */\n\t@XmlElement(required = false)\n\t@XmlJavaTypeAdapter(DateAdapter.class)\n\tprivate Date operationDate;\n\n\t/** The extra parameters. */\n\t@XmlJavaTypeAdapter(MapExtraParameterAdapter.class)\n\tprivate Map<String, Object> extraParameters;\n\n\t/** The addicional info fields */\n @XmlJavaTypeAdapter(MapAdditionalInfoAdapter.class)\n private Map<String, String> additionalInfo;\n\n\n\t/**\n\t * Returns the order id\n\t *\n\t * @return the orderId\n\t */\n\tpublic Long getOrderId() {\n\t\treturn orderId;\n\t}\n\t\n\t/**\n\t * Gets the order's reference code\n\t * \n\t * @return the reference code from order\n\t */\n\tpublic String getOrderReferenceCode() {\n\t\treturn orderReferenceCode;\n\t}\n\n\t/**\n\t * Returns the transaction id\n\t *\n\t * @return the transactionId\n\t */\n\tpublic String getTransactionId() {\n\t\treturn transactionId;\n\t}\n\n\t/**\n\t * Returns the transaction state\n\t *\n\t * @return the state\n\t */\n\tpublic TransactionState getState() {\n\t\treturn state;\n\t}\n\n\t/**\n\t * Returns the payment network response code\n\t *\n\t * @return the paymentNetworkResponseCode\n\t */\n\tpublic String getPaymentNetworkResponseCode() {\n\t\treturn paymentNetworkResponseCode;\n\t}\n\n\t/**\n\t * Returns the payment network response error message\n\t *\n\t * @return the paymentNetworkResponseErrorMessage\n\t */\n\tpublic String getPaymentNetworkResponseErrorMessage() {\n\t\treturn paymentNetworkResponseErrorMessage;\n\t}\n\n\t/**\n\t * Returns the trazability code\n\t *\n\t * @return the trazabilityCode\n\t */\n\tpublic String getTrazabilityCode() {\n\t\treturn trazabilityCode;\n\t}\n\n\t/**\n\t * Returns the authorization code\n\t *\n\t * @return the authorizationCode\n\t */\n\tpublic String getAuthorizationCode() {\n\t\treturn authorizationCode;\n\t}\n\n\t/**\n\t * Returns the transaction pending reason\n\t *\n\t * @return the pendingReason\n\t */\n\tpublic TransactionPendingReason getPendingReason() {\n\t\treturn pendingReason;\n\t}\n\n\t/**\n\t * Returns the transaction response code\n\t *\n\t * @return the responseCode\n\t */\n\tpublic TransactionResponseCode getResponseCode() {\n\t\treturn responseCode;\n\t}\n\n\t/**\n\t * Returns the transaction error code\n\t *\n\t * @return the errorCode\n\t */\n\tpublic TransactionErrorCode getErrorCode() {\n\t\treturn errorCode;\n\t}\n\n\t/**\n\t * Returns the response message\n\t *\n\t * @return the responseMessage\n\t */\n\tpublic String getResponseMessage() {\n\t\treturn responseMessage;\n\t}\n\n\t/**\n\t * Returns the transaction date\n\t *\n\t * @return the transactionDate\n\t */\n\tpublic String getTransactionDate() {\n\t\treturn transactionDate;\n\t}\n\n\t/**\n\t * Returns the transaction time\n\t *\n\t * @return the transactionTime\n\t */\n\tpublic String getTransactionTime() {\n\t\treturn transactionTime;\n\t}\n\n\t/**\n\t * Returns the operation date\n\t *\n\t * @return the operationDate\n\t */\n\tpublic Date getOperationDate() {\n\t\treturn operationDate;\n\t}\n\n\t/**\n\t * Returns the extra parameters map\n\t *\n\t * @return the extraParameters\n\t */\n\tpublic Map<String, Object> getExtraParameters() {\n\t\treturn extraParameters;\n\t}\n\n\t/**\n * Returns the additional info map\n *\n * @return the additional info\n */\n public Map<String, String> getAdditionalInfo() {\n\n return additionalInfo;\n }\n\n\n\t/**\n\t * Sets the order id\n\t *\n\t * @param orderId\n\t * the orderId to set\n\t */\n\tpublic void setOrderId(Long orderId) {\n\t\tthis.orderId = orderId;\n\t}\n\t\n\t/**\n\t * Sets the order's reference code\n\t * \n\t * @param orderReferenceCode\n\t * \n\t */\n\tpublic void setOrderReferenceCode(String orderReferenceCode) {\n\t\tthis.orderReferenceCode = orderReferenceCode;\n\t}\n\n\t/**\n\t * Sets the transaction id\n\t *\n\t * @param transactionId\n\t * the transactionId to set\n\t */\n\tpublic void setTransactionId(String transactionId) {\n\t\tthis.transactionId = transactionId;\n\t}\n\n\t/**\n\t * Sets the transaction state\n\t *\n\t * @param state\n\t * the state to set\n\t */\n\tpublic void setState(TransactionState state) {\n\t\tthis.state = state;\n\t}\n\n\t/**\n\t * Sets the payment network response code\n\t *\n\t * @param paymentNetworkResponseCode\n\t * the paymentNetworkResponseCode to set\n\t */\n\tpublic void setPaymentNetworkResponseCode(String paymentNetworkResponseCode) {\n\t\tthis.paymentNetworkResponseCode = paymentNetworkResponseCode;\n\t}\n\n\t/**\n\t * Sets the payment network response error message\n\t *\n\t * @param paymentNetworkResponseErrorMessage\n\t * the paymentNetworkResponseErrorMessage to set\n\t */\n\tpublic void setPaymentNetworkResponseErrorMessage(\n\t\t\tString paymentNetworkResponseErrorMessage) {\n\t\tthis.paymentNetworkResponseErrorMessage = paymentNetworkResponseErrorMessage;\n\t}\n\n\t/**\n\t * Sets the trazability code\n\t *\n\t * @param trazabilityCode\n\t * the trazabilityCode to set\n\t */\n\tpublic void setTrazabilityCode(String trazabilityCode) {\n\t\tthis.trazabilityCode = trazabilityCode;\n\t}\n\n\t/**\n\t * Sets the authorization code\n\t *\n\t * @param authorizationCode\n\t * the authorizationCode to set\n\t */\n\tpublic void setAuthorizationCode(String authorizationCode) {\n\t\tthis.authorizationCode = authorizationCode;\n\t}\n\n\t/**\n\t * Sets the transaction pending reason\n\t *\n\t * @param pendingReason\n\t * the pendingReason to set\n\t */\n\tpublic void setPendingReason(TransactionPendingReason pendingReason) {\n\t\tthis.pendingReason = pendingReason;\n\t}\n\n\t/**\n\t * Sets the transaction response code\n\t *\n\t * @param responseCode\n\t * the responseCode to set\n\t */\n\tpublic void setResponseCode(TransactionResponseCode responseCode) {\n\t\tthis.responseCode = responseCode;\n\t}\n\n\t/**\n\t * Sets the transaction error code\n\t *\n\t * @param errorCode\n\t * the errorCode to set\n\t */\n\tpublic void setErrorCode(TransactionErrorCode errorCode) {\n\t\tthis.errorCode = errorCode;\n\t}\n\n\t/**\n\t * Sets the response message\n\t *\n\t * @param responseMessage\n\t * the responseMessage to set\n\t */\n\tpublic void setResponseMessage(String responseMessage) {\n\t\tthis.responseMessage = responseMessage;\n\t}\n\n\t/**\n\t * Sets the transaction date\n\t *\n\t * @param transactionDate\n\t * the transactionDate to set\n\t */\n\tpublic void setTransactionDate(String transactionDate) {\n\t\tthis.transactionDate = transactionDate;\n\t}\n\n\t/**\n\t * Sets the transaction time\n\t *\n\t * @param transactionTime\n\t * the transactionTime to set\n\t */\n\tpublic void setTransactionTime(String transactionTime) {\n\t\tthis.transactionTime = transactionTime;\n\t}\n\n\t/**\n\t * Sets the operation date\n\t *\n\t * @param operationDate\n\t * the operationDate to set\n\t */\n\tpublic void setOperationDate(Date operationDate) {\n\t\tthis.operationDate = operationDate;\n\t}\n\n\t/**\n\t * Sets the extra parameters map\n\t *\n\t * @param extraParameters\n\t * the extraParameters to set\n\t */\n\tpublic void setExtraParameters(Map<String, Object> extraParameters) {\n\t\tthis.extraParameters = extraParameters;\n\t}\n\n\t/**\n * Sets the additional info map\n *\n * @param additionalInfo the additional info to set\n */\n public void setAdditionalInfo(Map<String, String> additionalInfo) {\n\n this.additionalInfo = additionalInfo;\n }\n}", "@XmlRootElement(name = \"transactionTokenBatchResponse\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class MassiveTokenPaymentsResponse extends Response {\n\n\t/** The generated serial version Id */\n\tprivate static final long serialVersionUID = 1157400679436549655L;\n\n\t/** The transaction response sent by the server */\n\t@XmlElement(required = false)\n\tprivate String id;\n\n\t/**\n\t * Returns the transaction batch token id\n\t *\n\t * @return the transaction batch token id\n\t */\n\tpublic String getId() {\n\n\t\treturn id;\n\t}\n\n\t/**\n\t * Sets the transaction batch token id\n\t *\n\t * @param id the transaction batch token id to set\n\t */\n\tpublic void setId(String id) {\n\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Converts a xml string into a payment response object\n\t *\n\t * @param xml\n\t * The object in a xml format\n\t * @return The payment response object\n\t * @throws PayUException\n\t */\n\tpublic static MassiveTokenPaymentsResponse fromXml(String xml) throws PayUException {\n\n\t\treturn (MassiveTokenPaymentsResponse) fromBaseXml(new MassiveTokenPaymentsResponse(), xml);\n\t}\n\n}", "@XmlRootElement(name = \"request\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class PaymentAttemptRequest extends PaymentRequest {\n\n\t/** The class serial version. */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/** The payment request id. */\n\t@XmlTransient\n\tprivate Integer paymentRequestId;\n\n\t/**\n\t * Default constructor.\n\t * Necessary for JAXB marshaler\n\t */\n\t@SuppressWarnings(\"unused\")\n\tprivate PaymentAttemptRequest() {\n\n\t\t// Mandatory constructor.\n\t}\n\n\t/**\n\t * Class constructor.\n\t * \n\t * @param paymentRequestId the payment request id.\n\t */\n\tpublic PaymentAttemptRequest(final Integer paymentRequestId) {\n\n\t\tthis.paymentRequestId = paymentRequestId;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * @see com.payu.sdk.model.request.Request#getBaseRequestUrl(java.lang.String,\n\t * com.payu.sdk.constants.Resources.RequestMethod)\n\t */\n\t@Override\n\tprotected String getBaseRequestUrl(final String baseUrl, final RequestMethod requestMethod) {\n\n\t\treturn String.format(Resources.DEPENDENT_ENTITY_API_URL_PATTERN, baseUrl, Resources.V4_3,\n\t\t\t\tResources.URI_PAYMENT_REQUEST, getPaymentRequestId(), \"transaction\");\n\t}\n\n\t/**\n\t * @return the paymentRequestId\n\t */\n\tpublic Integer getPaymentRequestId() {\n\n\t\treturn paymentRequestId;\n\t}\n\n\t/**\n\t * @param paymentRequestId the paymentRequestId to set\n\t */\n\tpublic void setPaymentRequestId(final Integer paymentRequestId) {\n\n\t\tthis.paymentRequestId = paymentRequestId;\n\t}\n}", "@SuppressWarnings(\"deprecation\")\npublic class CommonRequestUtil {\n\n\t/**\n\t * Private Constructor\n\t */\n\tprotected CommonRequestUtil() {\n\t}\n\n\t/* Validation Methods */\n\n\t/**\n\t * Validates the parameters given, against the required ones.\n\t *\n\t * @param parameters\n\t * The parameters that need to be validated. If the parameters\n\t * are null or empty, exception is thrown.\n\t * @param required\n\t * The parameters that are required by the application to work.\n\t * @throws InvalidParametersException\n\t * Thrown if given parameters are not complete.\n\t */\n\tpublic static void validateParameters(Map<String, String> parameters,\n\t\t\tString... required) throws InvalidParametersException {\n\n\t\tStringBuilder errorMessage = new StringBuilder();\n\t\tboolean isError = false;\n\n\t\tif (parameters == null || parameters.isEmpty()) {\n\t\t\tthrow new InvalidParametersException(\n\t\t\t\t\t\"Parameters can not be null or empty.\");\n\t\t} else {\n\t\t\tfor (String r : required) {\n\t\t\t\tif (!parameters.keySet().contains(r)\n\t\t\t\t\t\t|| parameters.get(r) == null\n\t\t\t\t\t\t|| parameters.get(r).trim().isEmpty()) {\n\n\t\t\t\t\terrorMessage.append(\"Parameter [\").append(r)\n\t\t\t\t\t\t\t.append(\"] is required.\")\n\t\t\t\t\t\t\t.append(Constants.LINE_SEPARATOR);\n\t\t\t\t\tisError = true;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tif (isError) {\n\t\t\tthrow new InvalidParametersException(errorMessage.toString());\n\t\t}\n\n\t}\n\n\t/**\n\t * Validates the given parameters against the not allowed\n\t *\n\t * @param parameters\n\t * The parameters that need to be validated. If the parameters\n\t * are null or empty, exception is thrown.\n\t * @param notAllowed\n\t * The parameters that aren't allowed by the application.\n\t * @throws InvalidParametersException\n\t * Thrown if given parameters don't comply with not allowed ones.\n\t */\n\tpublic static void validateNotAllowedParameters(Set<String> parameters,\n\t\t\tString... notAllowed) throws InvalidParametersException {\n\n\t\tStringBuilder errorMessage = new StringBuilder();\n\t\tboolean isError = false;\n\n\t\tif (parameters == null || parameters.isEmpty()) {\n\t\t\tthrow new InvalidParametersException(\n\t\t\t\t\t\"Parameters can not be null or empty.\");\n\t\t} else {\n\t\t\tfor (String r : notAllowed) {\n\t\t\t\tif (parameters.contains(r)) {\n\t\t\t\t\terrorMessage.append(\"Parameter [\").append(r)\n\t\t\t\t\t\t\t.append(\"] is not allowed.\")\n\t\t\t\t\t\t\t.append(Constants.LINE_SEPARATOR);\n\t\t\t\t\tisError = true;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tif (isError) {\n\t\t\tthrow new InvalidParametersException(errorMessage.toString());\n\t\t}\n\n\t}\n\n\t/**\n\t * Validates a date string whit the payments date format\n\t *\n\t * @param dateParameter\n\t * the parameter to validate\n\t * @param name\n\t * the name of the parameter (log purposes)\n\t * @return The date it got\n\t * @throws InvalidParametersException\n\t */\n\tprotected static Date validateDateParameter(String dateParameter,\n\t\t\tString parameterName, String dateFormat)\n\t\t\tthrows InvalidParametersException {\n\n\t\treturn validateDateParameter(dateParameter, parameterName, dateFormat, true);\n\t}\n\n\t/**\n\t * Validates a date string whit the payments date format.\n\t * Evaluates the format of permissive form or not as indicated in the parameter\n\t *\n\t * @param dateParameter the parameter to validate\n\t * @param parameterName the name of the parameter (log purposes)\n\t * @param dateFormat the date format\n\t * @param permissive indicates whether the format validation is permissive\n\t * @return The date it got\n\t * @throws InvalidParametersException\n\t */\n\tprotected static Date validateDateParameter(String dateParameter,\n\t\t\tString parameterName, String dateFormat, boolean permissive)\n\t\t\tthrows InvalidParametersException {\n\n\t\tDate date = null;\n\n\t\tif (dateParameter != null) {\n\t\t\tSimpleDateFormat sdf = new SimpleDateFormat(dateFormat);\n\t\t\tsdf.setLenient(permissive);\n\t\t\ttry {\n\t\t\t\tdate = sdf.parse(dateParameter);\n\t\t\t} catch (ParseException e) {\n\t\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\t\"The [%s] format is invalid. Use [%s] \", parameterName,\n\t\t\t\t\t\tdateFormat), e);\n\t\t\t}\n\t\t}\n\n\t\treturn date;\n\t}\n\n\t/* Get Values Methods */\n\n\t/**\n\t * Gets a big decimal value from parameters\n\t *\n\t * @param value\n\t * the value to convert to big decimal\n\t * @param name\n\t * the name of the parameter (exception purposes)\n\t * @return the big decimal it got\n\t * @throws InvalidParametersException\n\t */\n\tprivate static BigDecimal getBigDecimal(String value, String name)\n\t\t\tthrows InvalidParametersException {\n\t\tBigDecimal bigDecimalValue = null;\n\t\ttry {\n\t\t\tbigDecimalValue = new BigDecimal(value);\n\t\t} catch (Exception e) {\n\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\"The parameter [%s] isn't a valid BigDecimal value\", name),\n\t\t\t\t\te);\n\t\t}\n\n\t\treturn bigDecimalValue;\n\t}\n\t\n\t/**\n\t * Gets a long value from parameters\n\t *\n\t * @param value\n\t * the value to convert to long\n\t * @param name\n\t * the name of the parameter (exception purposes)\n\t * @return the long it got\n\t * @throws InvalidParametersException\n\t */\n\tprivate static Long getLong(String value, String name)\n\t\t\tthrows InvalidParametersException {\n\t\tLong longValue = null;\n\t\ttry {\n\t\t\tlongValue = Long.valueOf(value);\n\t\t} catch (Exception e) {\n\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\"The parameter [%s] isn't a valid Long value\", name),\n\t\t\t\t\te);\n\t\t}\n\n\t\treturn longValue;\n\t}\n\n\t/**\n\t * Gets a parameter based on it's name\n\t *\n\t * @param enumClass\n\t * The class that defines the parameters\n\t * @param value\n\t * the value to get form the class\n\t * @return The value it got\n\t * @throws InvalidParametersException\n\t */\n\tprivate static <E extends Enum<E>> E getEnumValue(Class<E> enumClass,\n\t\t\tString value) throws InvalidParametersException {\n\t\tE enumValue = null;\n\t\ttry {\n\t\t\tenumValue = Enum.valueOf(enumClass, value);\n\t\t} catch (Exception e) {\n\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\"The parameter [%s] isn't a valid [%s] value\", value,\n\t\t\t\t\tenumClass.getSimpleName()), e);\n\t\t}\n\n\t\treturn enumValue;\n\t}\n\n\t/**\n\t * Gets a integer value from the parameters\n\t *\n\t * @param value\n\t * the value to convert to integer\n\t * @param name\n\t * the name of the parameter (exception purposes)\n\t * @return the integer value it got\n\t * @throws InvalidParametersException\n\t */\n\tprivate static Integer getInteger(String value, String name)\n\t\t\tthrows InvalidParametersException {\n\t\tInteger integerValue = null;\n\t\ttry {\n\t\t\tintegerValue = Integer.parseInt(value);\n\t\t} catch (Exception e) {\n\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\"The parameter [%s] isn't a valid integer value\", name), e);\n\t\t}\n\n\t\treturn integerValue;\n\t}\n\n\t/**\n\t * Gets a boolean value from the parameters\n\t *\n\t * @param value\n\t * the value to convert to Boolean\n\t * @param name\n\t * the name of the parameter (exception purposes)\n\t * @return the Boolean value it got\n\t * @throws InvalidParametersException\n\t */\n\tprivate static Boolean getBoolean(String value, String name)\n\t\t\tthrows InvalidParametersException {\n\t\tBoolean booleanValue = null;\n\t\ttry {\n\t\t\tbooleanValue = Boolean.valueOf(value);\n\t\t} catch (Exception e) {\n\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\"The parameter [%s] isn't a valid boolean value\", name), e);\n\t\t}\n\n\t\treturn booleanValue;\n\t}\n\n\t/**\n\t * Gets a byte array value from the parameters\n\t *\n\t * @param value the value to convert to byte array\n\t * @param name the name of the parameter (exception purposes)\n\t * @return the byte array value it got\n\t * @throws InvalidParametersException\n\t */\n\tpublic static byte[] getByteArray(String value, String name)\n\t\t\tthrows InvalidParametersException {\n\n\t\ttry {\n\t\t\treturn value.getBytes(StandardCharsets.UTF_8);\n\t\t} catch (Exception e) {\n\t\t\tthrow new InvalidParametersException(String.format(\n\t\t\t\t\t\"The parameter [%s] isn't a valid byte array\", name), e);\n\t\t}\n\t}\n\n\t/**\n\t * Get a parameter from the parameters map\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param paramName\n\t * the parameter to get\n\t * @return The parameter it got\n\t */\n\tpublic static String getParameter(Map<String, String> parameters,\n\t\t\tString paramName) {\n\t\tString parameter = parameters.get(paramName);\n\n\t\tif(parameter != null){\n\t\t\tparameter = parameter.trim();\n\t\t\tif(parameter.isEmpty()){\n\t\t\t\tparameter = null;\n\t\t\t}\n\t\t}\n\n\t\treturn parameter;\n\t}\n\n\t/**\n\t * Gets an integer parameter from the parameters map\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param paramName\n\t * the parameter to get\n\t * @return The integer parameter it got\n\t * @throws InvalidParametersException\n\t */\n\tprotected static Integer getIntegerParameter(\n\t\t\tMap<String, String> parameters, String paramName)\n\t\t\tthrows InvalidParametersException {\n\t\tString parameter = getParameter(parameters, paramName);\n\t\tif (parameter != null && parameter.trim().isEmpty()) {\n\t\t\tparameter = null;\n\t\t}\n\t\tInteger integerParameter = (parameter != null ? getInteger(parameter,\n\t\t\t\tparamName) : null);\n\n\t\treturn integerParameter;\n\t}\n\n\t/**\n\t * Gets a BigDecimal parameter from the parameters map\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param paramName\n\t * the parameter to get\n\t * @return The BigDecimal parameter it got\n\t * @throws InvalidParametersException\n\t */\n\tprotected static BigDecimal getBigDecimalParameter(\n\t\t\tMap<String, String> parameters, String paramName)\n\t\t\tthrows InvalidParametersException {\n\t\tString parameter = getParameter(parameters, paramName);\n\t\tif (parameter != null && parameter.trim().isEmpty()) {\n\t\t\tparameter = null;\n\t\t}\n\t\tBigDecimal bigDecimalParameter = (parameter != null ? getBigDecimal(\n\t\t\t\tparameter, paramName) : null);\n\n\t\treturn bigDecimalParameter;\n\t}\n\t\n\t/**\n\t * Gets a long parameter from the parameters map\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param paramName\n\t * the parameter to get\n\t * @return The long parameter it got\n\t * @throws InvalidParametersException\n\t */\n\tprotected static Long getLongParameter(\n\t\t\tMap<String, String> parameters, String paramName)\n\t\t\tthrows InvalidParametersException {\n\t\tString parameter = getParameter(parameters, paramName);\n\t\tif (parameter != null && parameter.trim().isEmpty()) {\n\t\t\tparameter = null;\n\t\t}\n\t\tLong longParameter = (parameter != null ? getLong(parameter,\n\t\t\t\tparamName) : null);\n\n\t\treturn longParameter;\n\t}\n\n\t/**\n\t * Gets an Enum value parameter from the parameters map\n\t *\n\t * @param enumClass The enum class\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param paramName\n\t * the parameter to get\n\t * @return The Enum value parameter it got\n\t * @throws InvalidParametersException\n\t */\n\tpublic static <E extends Enum<E>> E getEnumValueParameter(\n\t\t\tClass<E> enumClass, Map<String, String> parameters, String paramName)\n\t\t\tthrows InvalidParametersException {\n\t\tString parameter = getParameter(parameters, paramName);\n\n\t\tE enumValueParameter = (parameter != null ? getEnumValue(enumClass,\n\t\t\t\tparameter) : null);\n\n\t\treturn enumValueParameter;\n\t}\n\n\t/**\n\t * Gets the PaymentMethod value parameter from the parameters map.\n\t * If the parameter is null or does not belong to the enumeration returns null\n\t * @param parameters The parameters to be sent to the server\n\t * @param paramName the parameter to get\n\t * @return the PaymentMethod value or null\n\t * @deprecated Not for public use in the future because the class PaymentMethod is deprecated\n\t * @see #com.payu.sdk.PayUPayments.getPaymentMethodParameter(Map<String, String> parameters, String paramName)\n\t */\n\t@Deprecated\n\tpublic static PaymentMethod getPaymentMethodParameter(Map<String, String> parameters, String paramName){\n\t\tPaymentMethod paymentMethod = null;\n\t\tString parameter = getParameter(parameters, paramName);\n\t\tif (parameter != null){\n\t\t\tpaymentMethod = PaymentMethod.fromString(parameter);\n\t\t}\n\t\treturn paymentMethod;\n\t}\n\n\t/**\n\t * Gets a Boolean parameter from the parameters map\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param paramName\n\t * the parameter to get\n\t * @return The Boolean parameter it got\n\t * @throws InvalidParametersException\n\t */\n\tprotected static Boolean getBooleanParameter(\n\t\t\tMap<String, String> parameters, String paramName)\n\t\t\tthrows InvalidParametersException {\n\t\tString parameter = getParameter(parameters, paramName);\n\t\tif (parameter != null && parameter.trim().isEmpty()) {\n\t\t\tparameter = null;\n\t\t}\n\t\tBoolean booleanParameter = (parameter != null ? getBoolean(parameter,\n\t\t\t\tparamName) : null);\n\n\t\treturn booleanParameter;\n\t}\n\n\t/**\n\t * Gets an integer parameter from the parameters map\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @param paramName the parameter to get\n\t * @return The integer parameter it got\n\t * @throws InvalidParametersException\n\t */\n\tpublic static byte[] getByteArrayParameter(\n\t\t\tMap<String, String> parameters, String paramName)\n\t\t\tthrows InvalidParametersException {\n\n\t\tString parameter = getParameter(parameters, paramName);\n\t\tif (parameter != null && parameter.trim().isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\treturn getByteArray(parameter, paramName);\n\t}\n\n\t/* Build Methods */\n\n\t/**\n\t * Build the transaction additional values (currency and value)\n\t *\n\t * @param txCurrency\n\t * The currency of the transaction\n\t * @param txValue\n\t * The value of the transaction\n\t * @param taxValue\n\t * The tax value associated with the payment\n\t * @param taxReturnBase\n\t * The tax(IVA) return base associated with the payment\n\t * @return The created map of additional values\n\t */\n\tprotected static Map<String, AdditionalValue> buildAdditionalValues(\n\t\t\tCurrency txCurrency, BigDecimal txValue, BigDecimal taxValue,\n\t\t\tBigDecimal taxReturnBase) {\n\n\t\tif (txCurrency == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tMap<String, AdditionalValue> values = new HashMap<String, AdditionalValue>();\n\n\t\taddAdditionalValue(txCurrency, \"TX_VALUE\", txValue, values);\n\t\taddAdditionalValue(txCurrency, \"TX_TAX\", taxValue, values);\n\t\taddAdditionalValue(txCurrency, \"TX_TAX_RETURN_BASE\", taxReturnBase,\n\t\t\t\tvalues);\n\n\t\tif (!values.isEmpty()) {\n\t\t\treturn values;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Adds an additional value\n\t *\n\t * @param txCurrency\n\t * The currency of the transaction\n\t * @param name\n\t * The name of the new value\n\t * @param value\n\t * The value of the transaction\n\t * @param additionalValues\n\t * The additional values map where the new value will go\n\t */\n\tprivate static void addAdditionalValue(Currency txCurrency, String name,\n\t\t\tBigDecimal value, Map<String, AdditionalValue> additionalValues) {\n\n\t\tif (value != null) {\n\t\t\tAdditionalValue additionalValue = new AdditionalValue();\n\t\t\tadditionalValue.setCurrency(txCurrency);\n\t\t\tadditionalValue.setValue(value);\n\t\t\tadditionalValue.setName(name);\n\n\t\t\tadditionalValues.put(name, additionalValue);\n\t\t}\n\t}\n\n}", "public final class PaymentPlanRequestUtil extends CommonRequestUtil {\n\n\t/**\n\t * Private Constructor\n\t */\n\tprivate PaymentPlanRequestUtil() {\n\t}\n\n\t// valid keys for CreditCard\n\tpublic static final String[] CREDIT_CARD_VALID_PARAMS = new String[] {\n\t\t\tPayU.PARAMETERS.TOKEN_ID,\n\t\t\tPayU.PARAMETERS.CREDIT_CARD_NUMBER,\n\t\t\tPayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE,\n\t\t\tPayU.PARAMETERS.PAYMENT_METHOD, PayU.PARAMETERS.PAYER_NAME,\n\t\t\tPayU.PARAMETERS.PAYER_STREET, PayU.PARAMETERS.PAYER_STREET_2,\n\t\t\tPayU.PARAMETERS.PAYER_STREET_3, PayU.PARAMETERS.PAYER_CITY,\n\t\t\tPayU.PARAMETERS.PAYER_STATE, PayU.PARAMETERS.PAYER_COUNTRY,\n\t\t\tPayU.PARAMETERS.PAYER_POSTAL_CODE, PayU.PARAMETERS.PAYER_PHONE };\n\n\t// valid keys for BankAccount\n\tpublic static final String[] BANK_ACCOUNT_VALID_PARAMS = new String[] {\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_ID,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER_TYPE,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_CUSTOMER_NAME,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_AGENCY_NUMBER,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_AGENCY_DIGIT,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_ACCOUNT_DIGIT,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_NUMBER,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_BANK_NAME,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_TYPE,\n\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_STATE };\n\n\tpublic final static String EMPTY = \"\";\n\t/* Build Methods */\n\n\t/* PRIVATE METHODS */\n\n\t/**\n\t * Build the plan additional values (currency and value)\n\t *\n\t * @param txCurrency\n\t * The currency of the plan\n\t * @param txValue\n\t * The value of the plan\n\t * @param txTax\n\t * The tax of the plan\n\t * @param txTaxReturnBase\n\t * The tax return base of the plan\n\t * @param txAdditionalValue\n\t * The additional value of the plan\n\t * @return The created list of additional values\n\t */\n\tprivate static List<AdditionalValue> buildPlanAdditionalValues(\n\t\t\tCurrency txCurrency, BigDecimal txValue, BigDecimal txTax,\n\t\t\tBigDecimal txTaxReturnBase, BigDecimal txAdditionalValue) {\n\n\t\tif (txCurrency == null || txValue == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tList<AdditionalValue> values = new ArrayList<AdditionalValue>();\n\t\taddAdditionalValue(txCurrency, Constants.PLAN_VALUE, txValue, values);\n\t\taddAdditionalValue(txCurrency, Constants.PLAN_TAX, txTax, values);\n\t\taddAdditionalValue(txCurrency, Constants.PLAN_TAX_RETURN_BASE,\n\t\t\t\ttxTaxReturnBase, values);\n\t\taddAdditionalValue(txCurrency, Constants.PLAN_ADDITIONAL_VALUE,\n\t\t\t\ttxAdditionalValue, values);\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Build the item additional values (currency and value)\n\t *\n\t * @param txCurrency\n\t * The currency of the plan\n\t * @param txValue\n\t * The value of the plan\n\t * @param txTax\n\t * The tax of the plan\n\t * @param txTaxReturnBase\n\t * The tax return base of the plan\n\t * @return The created list of additional values\n\t */\n\tprivate static List<AdditionalValue> buildItemAdditionalValues(\n\t\t\tCurrency txCurrency, BigDecimal txValue, BigDecimal txTax,\n\t\t\tBigDecimal txTaxReturnBase) {\n\n\t\tif (txCurrency == null || txValue == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tList<AdditionalValue> values = new ArrayList<AdditionalValue>();\n\t\taddAdditionalValue(txCurrency, Constants.ITEM_VALUE, txValue, values);\n\t\taddAdditionalValue(txCurrency, Constants.ITEM_TAX, txTax, values);\n\t\taddAdditionalValue(txCurrency, Constants.ITEM_TAX_RETURN_BASE,\n\t\t\t\ttxTaxReturnBase, values);\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Creates or updates an additional value\n\t *\n\t * @param txCurrency\n\t * The transaction currency\n\t * @param name\n\t * The additional value name\n\t * @param value\n\t * The additional value value\n\t * @param additionalValues\n\t * The additional values list\n\t */\n\tprivate static void addAdditionalValue(Currency txCurrency, String name,\n\t\t\tBigDecimal value, List<AdditionalValue> additionalValues) {\n\n\t\tif (value != null) {\n\t\t\tAdditionalValue additionalValue = new AdditionalValue();\n\t\t\tadditionalValue.setName(name);\n\t\t\tadditionalValue.setCurrency(txCurrency);\n\t\t\tadditionalValue.setValue(value);\n\n\t\t\tadditionalValues.add(additionalValue);\n\t\t}\n\t}\n\n\t/* PUBLIC METHODS */\n\n\t/**\n\t * Builds a costumer request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete remove credit card token request\n\t */\n\tpublic static Customer buildCustomerRequest(Map<String, String> parameters) {\n\n\n\t\tString customerName = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_NAME);\n\n\t\tString customerEmail = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_EMAIL);\n\n\t\tString customerId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_ID);\n\n\t\tCustomer request = new Customer();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setFullName(customerName);\n\t\trequest.setEmail(customerEmail);\n\t\trequest.setId(customerId);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a costumer request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The request by customerRequestList\n\t * @throws PayUException\n\t */\n\tpublic static CustomerListRequest buildCustomerListRequest(Map<String, String> parameters) throws PayUException {\n\n\t\tMap<String, String> parametersFilter=new HashMap<String, String>();\n\n\t\tparametersFilter.put(PayU.PARAMETERS.PLAN_ID,\n\t\t\t\tparameters.get(PayU.PARAMETERS.PLAN_ID));\n\n\t\tparametersFilter.put(PayU.PARAMETERS.PLAN_CODE,\n\t\t\t\tparameters.get(PayU.PARAMETERS.PLAN_CODE));\n\n\t\tparametersFilter.put(PayU.PARAMETERS.LIMIT,\n\t\t\t\tparameters.get(PayU.PARAMETERS.LIMIT));\n\n\t\tparametersFilter.put(PayU.PARAMETERS.OFFSET,\n\t\t\t\tparameters.get(PayU.PARAMETERS.OFFSET));\n\n\t\tCustomerListRequest request = new CustomerListRequest();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\t\trequest.setMap(parametersFilter);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a credit card request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete credit card request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static PaymentPlanCreditCard buildCreditCardRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tString tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);\n\t\tString customerId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_ID);\n\t\tString creditCardNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_NUMBER);\n\t\tString creditCardName = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PAYER_NAME);\n\t\tString type = getParameter(parameters, PayU.PARAMETERS.PAYMENT_METHOD);\n\t\tString line1 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET);\n\t\tString line2 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_2);\n\t\tString line3 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_3);\n\t\tString city = getParameter(parameters, PayU.PARAMETERS.PAYER_CITY);\n\t\tString state = getParameter(parameters, PayU.PARAMETERS.PAYER_STATE);\n\t\tString country = getParameter(parameters, PayU.PARAMETERS.PAYER_COUNTRY);\n\t\tString postalCode = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PAYER_POSTAL_CODE);\n\t\tString phone = getParameter(parameters, PayU.PARAMETERS.PAYER_PHONE);\n\t\tString expDate = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE);\n\n\t\tString document = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_DOCUMENT);\n\n\t\tAddress address = new Address();\n\t\taddress.setLine1(line1 != null ? line1 : EMPTY);\n\t\taddress.setLine2(line2 != null ? line2 : EMPTY);\n\t\taddress.setLine3(line3 != null ? line3 : EMPTY);\n\t\taddress.setCity(city != null ? city : EMPTY);\n\t\taddress.setState(state);\n\t\taddress.setCountry(country);\n\t\taddress.setPostalCode(postalCode != null ? postalCode : EMPTY);\n\t\taddress.setPhone(phone);\n\n\t\tPaymentPlanCreditCard request = new PaymentPlanCreditCard();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setToken(tokenId);\n\t\trequest.setCustomerId(customerId);\n\t\trequest.setNumber(creditCardNumber);\n\t\trequest.setName(creditCardName);\n\t\trequest.setType(type);\n\t\trequest.setAddress(address);\n\t\trequest.setDocument(document != null ? document : EMPTY);\n\n\t\tvalidateDateParameter(expDate,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE,\n\t\t\t\tConstants.SECUNDARY_DATE_FORMAT);\n\n\t\tif (expDate != null) {\n\n\t\t\tString[] date = expDate.split(\"/\");\n\n\t\t\trequest.setExpMonth(Integer.parseInt(date[1]));\n\t\t\trequest.setExpYear(Integer.parseInt(date[0]));\n\n\t\t}\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a credit card request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete credit card request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static PaymentPlanCreditCardListRequest buildCreditCardListRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\t\tPaymentPlanCreditCardListRequest request = new PaymentPlanCreditCardListRequest();\n\t\tString customerId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_ID);\n\t\trequest.setCustomerId(customerId);\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a bank account request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete bank account request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static BankAccount buildBankAccountRequest(Map<String, String> parameters)\n\t\t\tthrows InvalidParametersException {\n\n\t\tString bankAccountId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_ID);\n\t\tString customerId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_ID);\n\t\tString accountId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ACCOUNT_ID);\n\t\tString customerName = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_CUSTOMER_NAME);\n\t\tString documentNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER);\n\t\tString documentNumberType = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER_TYPE);\n\t\tString bankName = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_BANK_NAME);\n\t\tString bankType = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_TYPE);\n\t\tString accountNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_NUMBER);\n\t\tString state = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_STATE);\n\t\tString country = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.COUNTRY);\n\t\tString accountDigit = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_ACCOUNT_DIGIT);\n\t\tString agencyDigit = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_AGENCY_DIGIT);\n\t\tString agencyNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BANK_ACCOUNT_AGENCY_NUMBER);\n\n\t\tBankAccount request = new BankAccount();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setId(bankAccountId);\n\t request.setAccountId(accountId);\n\t\trequest.setCustomerId(customerId);\n\t\trequest.setName(customerName);\n\t\trequest.setDocumentNumber(documentNumber);\n\t\trequest.setDocumentNumberType(documentNumberType);\n\t\trequest.setBank(bankName);\n\t\trequest.setType(bankType);\n\t\trequest.setAccountNumber(accountNumber);\n\t\trequest.setState(state);\n\t\trequest.setCountry(country);\n\t\trequest.setAgencyDigit(agencyDigit);\n\t\trequest.setAgencyNumber(agencyNumber);\n\t\trequest.setAccountDigit(accountDigit);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a bank account list request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete bank account request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static BankAccountListRequest buildBankAccountListRequest(Map<String, String> parameters)\n\t\t\tthrows InvalidParametersException {\n\n\t\tString customerId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_ID);\n\n\t\tBankAccountListRequest request = new BankAccountListRequest();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setCustomerId(customerId);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a subscription plan request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete SubscriptionPlan request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static SubscriptionPlan buildSubscriptionPlanRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tString planCode = getParameter(parameters, PayU.PARAMETERS.PLAN_CODE);\n\t\tInteger accountId = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ACCOUNT_ID);\n\t\tString planDescription = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_DESCRIPTION);\n\t\tString planInterval = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_INTERVAL);\n\t\tInteger planIntervalCount = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_INTERVAL_COUNT);\n\t\tInteger planTrialPeriodDays = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_TRIAL_PERIOD_DAYS);\n\t\tCurrency planCurrency = getEnumValueParameter(Currency.class,\n\t\t\t\tparameters, PayU.PARAMETERS.PLAN_CURRENCY);\n\t\tBigDecimal planValue = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_VALUE);\n\t\tBigDecimal planTax = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_TAX);\n\t\tBigDecimal planTaxReturnBase = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_TAX_RETURN_BASE);\n\t\tInteger maxPaymentsAllowed = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_MAX_PAYMENTS);\n\t\tInteger planPaymentAttemptsDelay = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_ATTEMPTS_DELAY);\n\n\t\tInteger planPaymentMaxPendingPayments = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_MAX_PENDING_PAYMENTS);\n\t\tInteger planPaymentMaxPaymentAttemps = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_MAX_PAYMENT_ATTEMPTS);\n\n\t\tBigDecimal planAdditionalValue = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_ADDITIONAL_VALUE);\n\n\t\tSubscriptionPlan request = new SubscriptionPlan();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setAccountId(accountId);\n\t\trequest.setPlanCode(planCode);\n\t\trequest.setDescription(planDescription);\n\t\trequest.setInterval(planInterval);\n\t\trequest.setIntervalCount(planIntervalCount);\n\t\trequest.setTrialDays(planTrialPeriodDays);\n\t\trequest.setMaxPaymentsAllowed(maxPaymentsAllowed);\n\t\trequest.setAdditionalValues(buildPlanAdditionalValues(planCurrency,\n\t\t\t\tplanValue, planTax, planTaxReturnBase, planAdditionalValue));\n\t\trequest.setPaymentAttemptsDelay(planPaymentAttemptsDelay);\n\t\trequest.setMaxPaymentAttempts(planPaymentMaxPaymentAttemps);\n\t\trequest.setMaxPendingPayments(planPaymentMaxPendingPayments);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a subscription plan list request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete SubscriptionPlan request\n\t * @throws InvalidParametersException\n\t * @throws PayUException\n\t */\n\tpublic static SubscriptionPlanListRequest buildSubscriptionPlanListRequest(Map<String, String> parameters)\n\t\t\tthrows InvalidParametersException, PayUException {\n\n\t\tSubscriptionPlanListRequest request = new SubscriptionPlanListRequest();\n\t\trequest.setMap(parameters);\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a Customer with a CreditCard request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete Customer with a CreditCard request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Customer buildCustomerWithCreditCardRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tPaymentPlanCreditCard creditCard = buildCreditCardRequest(parameters);\n\t\tCustomer request = buildCustomerRequest(parameters);\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.addCreditCard(creditCard);\n\n\t\treturn request;\n\t}\n\n\n\t/**\n\t * Builds a Customer with a BankAccount request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete Customer with a CreditCard request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Customer buildCustomerWithBankAccountRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tBankAccount bankAccount = buildBankAccountRequest(parameters);\n\t\tCustomer request = buildCustomerRequest(parameters);\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.addBankAccount(bankAccount);\n\n\t\treturn request;\n\t}\n\t\n\t/**\n\t * Builds a subscription request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete subscription request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildSubscriptionRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\t// Subscription basic parameters\n\t\tInteger trialDays = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.TRIAL_DAYS);\n\t\tBoolean immediatePayment = getBooleanParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.IMMEDIATE_PAYMENT);\n\t\tInteger quantity = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.QUANTITY);\n\t\tInteger installments = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.INSTALLMENTS_NUMBER);\n\n\t\tString subscriptionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.SUBSCRIPTION_ID);\n\t\tBoolean termsAndConditionsAcepted=getBooleanParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.TERMS_AND_CONDITIONS_ACEPTED);\n\t\t\n\t\tList<RecurringBillItem> recurringBillItems = buildRecurringBillItemList(parameters);\n\n\t\t// Plan parameter\n\t\tSubscriptionPlan plan = buildSubscriptionPlanRequest(parameters);\n\t\tString planId = getParameter(parameters, PayU.PARAMETERS.PLAN_ID);\n\t\tplan.setId(planId);\n\t\tif(planId!=null){\n\t\t\tplan.setAccountId(null);\n\t\t}\n\n\t\t// Customer parameter\n\t\tCustomer customer = buildCustomerRequest(parameters);\n\t\t// CreditCard parameter\n\t\tif (CollectionsUtil.interceptMaps(parameters.keySet(), CREDIT_CARD_VALID_PARAMS)) {\n\t\t\tPaymentPlanCreditCard cc = buildCreditCardRequest(parameters);\n\t\t\tif (parameters.containsKey(PayU.PARAMETERS.TOKEN_ID)) {\n\t\t\t\tcc.setAddress(null);\n\t\t\t}\n\t\t\tcc.setCustomerId(null);\n\t\t\tcustomer.addCreditCard(cc);\n\t\t}\n\t\t// BankAccount parameter\n\t\tif (CollectionsUtil.interceptMaps(parameters.keySet(), BANK_ACCOUNT_VALID_PARAMS)) {\n\t\t\tBankAccount bankAccount=buildBankAccountRequest(parameters);\n\t\t\tbankAccount.setCustomerId(null);\n\t\t\tif(bankAccount.getId()!=null){\n\t\t\t\tbankAccount.setAccountId(null);\n\t\t\t}\n\t\t\tcustomer.addBankAccount(bankAccount);\n\t\t}\n\t\t\n\t\t// Delivery address parameters\n\t\tAddress deliveryAddress = new Address();\n\t\tdeliveryAddress.setLine1(getParameter(parameters, PayU.PARAMETERS.DELIVERY_ADDRESS_1));\n\t\tdeliveryAddress.setLine2(getParameter(parameters, PayU.PARAMETERS.DELIVERY_ADDRESS_2));\n\t\tdeliveryAddress.setLine3(getParameter(parameters, PayU.PARAMETERS.DELIVERY_ADDRESS_3));\n\t\tdeliveryAddress.setCity(getParameter(parameters, PayU.PARAMETERS.DELIVERY_CITY));\n\t\tdeliveryAddress.setState(getParameter(parameters, PayU.PARAMETERS.DELIVERY_STATE));\n\t\tdeliveryAddress.setCountry(getParameter(parameters, PayU.PARAMETERS.DELIVERY_COUNTRY));\n\t\tdeliveryAddress.setPostalCode(getParameter(parameters, PayU.PARAMETERS.DELIVERY_POSTAL_CODE));\n\t\tdeliveryAddress.setPhone(getParameter(parameters, PayU.PARAMETERS.DELIVERY_PHONE));\n\t\t\n\t\t// Subscription notifyUrl, sourceReference, extra1 and extra 2 parameters\n\t\tString notifyUrl = getParameter(parameters, PayU.PARAMETERS.NOTIFY_URL);\n\t\tString sourceReference = getParameter(parameters, PayU.PARAMETERS.SOURCE_REFERENCE);\n\t\tString extra1 = getParameter(parameters, PayU.PARAMETERS.EXTRA1);\n\t\tString extra2 = getParameter(parameters, PayU.PARAMETERS.EXTRA2);\n\t\t\n\t\t// Subscription sourceId and description\n\t\tLong sourceId = getLongParameter(parameters, PayU.PARAMETERS.SOURCE_ID);\n\t\tString description = getParameter(parameters, PayU.PARAMETERS.DESCRIPTION);\n\t\tSubscriptionCreationSource creationSource = getEnumValueParameter(SubscriptionCreationSource.class, parameters,\n\t\t\t\tPayU.PARAMETERS.CREATION_SOURCE);\n\t\t\n\t\t// Migrated subscriptions parameters\n\t\tString sourceBuyerIP = getParameter(parameters, PayU.PARAMETERS.SOURCE_BUYER_IP);\n\t\tInteger sourceNumberOfPayments = getIntegerParameter(parameters, PayU.PARAMETERS.SOURCE_NUMBER_OF_PAYMENTS); \n\t\tInteger sourceNextPaymentNumber = getIntegerParameter(parameters, PayU.PARAMETERS.SOURCE_NEXT_PAYMENT_NUMBER);\n\t\t\n\t\t// Subscription basic parameters\n\t\tSubscription request = new Subscription();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setTrialDays(trialDays);\n\t\trequest.setImmediatePayment(immediatePayment);\n\t\trequest.setQuantity(quantity);\n\t\trequest.setInstallments(installments);\n\t\trequest.setTermsAndConditionsAcepted(termsAndConditionsAcepted);\n\t\trequest.setDeliveryAddress(deliveryAddress);\n\t\trequest.setRecurringBillItems(recurringBillItems);\n\t\trequest.setNotifyUrl(notifyUrl);\n\t\trequest.setSourceReference(sourceReference);\n\t\trequest.setExtra1(extra1);\n\t\trequest.setExtra2(extra2);\n\t\trequest.setSourceId(sourceId);\n\t\trequest.setDescription(description);\n\t\trequest.setSourceBuyerIp(sourceBuyerIP);\n\t\trequest.setSourceNumberOfPayments(sourceNumberOfPayments);\n\t\trequest.setSourceNextPaymentNumber(sourceNextPaymentNumber);\n\t\t\n\t\tif (creationSource != null) {\n\t\t\trequest.setCreationSource(creationSource.name());\n\t\t}\n\n\t\t// Subscription complex parameters (customer and plan)\n\t\trequest.setPlan(plan);\n\t\trequest.setCustomer(customer);\n\t\trequest.setId(subscriptionId);\n\n\t\treturn request;\n\t}\n\t\n\t/**\n\t * Builds a recurring billing item request without authentication\n\t * \n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return List<RecurringBillItem> The RecurringBillItems list\n\t * @throws InvalidParametersException\n\t */\n\tprivate static List<RecurringBillItem> buildRecurringBillItemList(Map<String, String> parameters)\n\t\t\tthrows InvalidParametersException {\n\t\t\n\t\tif (parameters.containsKey(PayU.PARAMETERS.SUBSCRIPTION_EXTRA_CHARGES_DESCRIPTION)) {\n\t\t\tString description = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_EXTRA_CHARGES_DESCRIPTION);\n\t\t\tBigDecimal value = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_VALUE);\n\t\t\tBigDecimal taxValue = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_TAX);\n\t\t\tBigDecimal taxReturnBase = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_TAX_RETURN_BASE);\n\t\t\tCurrency currency = getEnumValueParameter(Currency.class, parameters, PayU.PARAMETERS.CURRENCY);\n\t\t\tRecurringBillItem recurringBillItem = new RecurringBillItem();\n\t\t\trecurringBillItem.setDescription(description);\n\t\t\tList<AdditionalValue> additionalValues = buildItemAdditionalValues(currency, value, taxValue, taxReturnBase);\n\t\t\trecurringBillItem.setAdditionalValues(additionalValues);\n\t\t\treturn Arrays.asList(recurringBillItem);\n\t\t}\n\t\t\n\t\treturn Collections.emptyList();\n\t}\n\t\n\t/**\n\t * Builds an update subscription request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete subscription request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildSubscriptionUpdateRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tString newCreditCardToken = getParameter(parameters,\n\t\t\t\t PayU.PARAMETERS.TOKEN_ID);\n\n\t\tString newBankAccountId = getParameter(parameters,\n\t\t\t\t PayU.PARAMETERS.BANK_ACCOUNT_ID);\n\n\t\tString subscriptionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.SUBSCRIPTION_ID);\n\t\t\n\t\tSubscription request = new Subscription();\n\t\t\n\t\t// Set the delivery address fields\n\t\tAddress deliveryAddress = new Address();\n\t\tdeliveryAddress.setLine1(getParameter(parameters,PayU.PARAMETERS.DELIVERY_ADDRESS_1));\n\t\tdeliveryAddress.setLine2(getParameter(parameters,PayU.PARAMETERS.DELIVERY_ADDRESS_2));\n\t\tdeliveryAddress.setLine3(getParameter(parameters,PayU.PARAMETERS.DELIVERY_ADDRESS_3));\n\t\tdeliveryAddress.setCity(getParameter(parameters,PayU.PARAMETERS.DELIVERY_CITY));\n\t\tdeliveryAddress.setState(getParameter(parameters,PayU.PARAMETERS.DELIVERY_STATE));\n\t\tdeliveryAddress.setCountry(getParameter(parameters,PayU.PARAMETERS.DELIVERY_COUNTRY));\n\t\tdeliveryAddress.setPostalCode(getParameter(parameters,PayU.PARAMETERS.DELIVERY_POSTAL_CODE));\n\t\tdeliveryAddress.setPhone(getParameter(parameters,PayU.PARAMETERS.DELIVERY_PHONE));\n\t\t\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setUrlId(subscriptionId);\n\t\trequest.setCreditCardToken(newCreditCardToken);\n\t\trequest.setBankAccountId(newBankAccountId);\n\t\trequest.setDeliveryAddress(deliveryAddress);\n\t\t\n\t\treturn request;\n\n\t}\n\n\t/**\n\t * Builds a recurring bill item request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete recurring bill item request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildRecurringBillItemRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\t// Recurring bill item basic parameters\n\t\tBigDecimal value = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ITEM_VALUE);\n\n\t\tCurrency currency = getEnumValueParameter(Currency.class, parameters,\n\t\t\t\tPayU.PARAMETERS.CURRENCY);\n\n\t\tString description = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DESCRIPTION);\n\n\t\tBigDecimal taxValue = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ITEM_TAX);\n\n\t\tBigDecimal taxReturnBase = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ITEM_TAX_RETURN_BASE);\n\n\t\tString recurringBillItemId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.RECURRING_BILL_ITEM_ID);\n\n\t\tString recurringItemId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.RECURRING_ITEM_ID);\n\n\t\tString subscriptionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.SUBSCRIPTION_ID);\n\n\t\t// Subscription basic parameters\n\t\tRecurringBillItem request = new RecurringBillItem();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\trequest.setId(recurringBillItemId);\n\t\trequest.setDescription(description);\n\t\trequest.setSubscriptionId(subscriptionId);\n\t\trequest.setRecurringBillId(recurringItemId);\n\t\tList<AdditionalValue> additionalValues = buildItemAdditionalValues(\n\t\t\t\tcurrency, value, taxValue, taxReturnBase);\n\t\trequest.setAdditionalValues(additionalValues);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a recurring bill item request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete recurring bill item request\n\t * @throws InvalidParametersException\n\t * @throws PayUException\n\t */\n\tpublic static Request buildRecurringBillItemListRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException, PayUException {\n\n\t\tString description = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DESCRIPTION);\n\n\t\tString subscriptionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.SUBSCRIPTION_ID);\n\t\tMap<String, String> parametersRequest=new HashMap<String, String>();\n\t\tparametersRequest.put(PayU.PARAMETERS.SUBSCRIPTION_ID, subscriptionId);\n\t\tparametersRequest.put(PayU.PARAMETERS.DESCRIPTION, description);\n\t\tRecurringBillItemListRequest request = new RecurringBillItemListRequest();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\t\trequest.setMap(parametersRequest);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a recurring bill request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete recurring bill request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildRecurringBillRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\t// Recurring bill basic parameters\n\t\tString recurringBillId = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_ID);\n\n\t\tRecurringBill request = new RecurringBill();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\t\trequest.setId(recurringBillId);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a recurring bill list request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete recurring bill list request\n\t * @throws InvalidParametersException\n\t * @throws PayUException\n\t */\n\tpublic static Request buildRecurringBillListRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException, PayUException {\n\n\t\tString startDate = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_DATE_BEGIN);\n\t\tString endDate = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_DATE_FINAL);\n\n\t\t// Validates the PaymentMethodType value, if any.\n\t\tgetEnumValueParameter(\n\t\t\t\tPaymentMethodType.class, parameters, PayU.PARAMETERS.RECURRING_BILL_PAYMENT_METHOD_TYPE);\n\n\t\tvalidateDateParameter(\n\t\t\t\tstartDate, PayU.PARAMETERS.RECURRING_BILL_DATE_BEGIN, Constants.DEFAULT_DATE_WITHOUT_HOUR_FORMAT);\n\t\tvalidateDateParameter(\n\t\t\t\tendDate, PayU.PARAMETERS.RECURRING_BILL_DATE_FINAL, Constants.DEFAULT_DATE_WITHOUT_HOUR_FORMAT);\n\n\t\tRecurringBillListRequest request = new RecurringBillListRequest();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\t\trequest.setMap(parameters);\n\n\t\treturn request;\n\t}\n\n\n\t/**\n\t * Builds a subscription request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete subscription request\n\t * @throws InvalidParametersException\n\t * @throws PayUException\n\t */\n\tpublic static Request buildSubscriptionListRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException, PayUException {\n\n\t\t// Subscription parameters\n\n\t\tString customerId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CUSTOMER_ID);\n\t\tString planCode = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_CODE);\n\t\tString planId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PLAN_ID);\n\t\tString state = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.STATE);\n\t\tString subscriptionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.SUBSCRIPTION_ID);\n\t\tString accountId=getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ACCOUNT_ID);\n\t\tString limit=getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.LIMIT);\n\t\tString offset=getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.OFFSET);\n\t\tString sourceId = getParameter(parameters, \n\t\t\t\tPayU.PARAMETERS.SOURCE_ID);\n\n\t\tMap<String, String> paramsFilter=new HashMap<String, String>();\n\t\tparamsFilter.put(PayU.PARAMETERS.CUSTOMER_ID, customerId);\n\t\tparamsFilter.put(PayU.PARAMETERS.PLAN_CODE, planCode);\n\t\tparamsFilter.put(PayU.PARAMETERS.PLAN_ID, planId);\n\t\tparamsFilter.put(PayU.PARAMETERS.STATE, state);\n\t\tparamsFilter.put(PayU.PARAMETERS.SUBSCRIPTION_ID,subscriptionId);\n\t\tparamsFilter.put(PayU.PARAMETERS.ACCOUNT_ID, accountId);\n\t\tparamsFilter.put(PayU.PARAMETERS.LIMIT, limit);\n\t\tparamsFilter.put(PayU.PARAMETERS.OFFSET, offset);\n\t\tparamsFilter.put(PayU.PARAMETERS.SOURCE_ID, sourceId);\n\n\t\tSubscriptionsListRequest request = new SubscriptionsListRequest();\n\n\t\trequest.setMap(paramsFilter);\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\n\t\treturn request;\n\t}\n\t\n\t/**\n\t * Builds a recurring bill payment retry request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete recurring bill payment retry request\n\t * @throws InvalidParametersException\n\t * @throws PayUException\n\t */\n\tpublic static Request buildRecurringBillPaymentRetryRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException, PayUException {\n\n\t\tString recurringBillId = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_ID);\n\n\t\tRecurringBillPaymentRetry request = new RecurringBillPaymentRetry();\n\t\tRequestUtil.setAuthenticationCredentials(parameters, request);\n\t\trequest.setRecurringBillId(recurringBillId);\n\n\t\treturn request;\n\t}\n}", "public final class RequestUtil extends CommonRequestUtil {\n\n\t/** The encoding used to send confirmation page */\n\tprivate static final String ENCODING = Constants.DEFAULT_ENCODING\n\t\t\t.toString();\n\t/** The character to append parameters */\n\tprivate static final String APPENDER = \"&\";\n\t/** The character to assign a value param */\n\tprivate static final String EQUALS = \"=\";\n\n\t/**\n\t * Private Constructor\n\t */\n\tprivate RequestUtil() {\n\t}\n\n\t/**\n\t * Builds a payments ping request\n\t *\n\t * @return The complete payments ping request\n\t */\n\tpublic static PaymentRequest buildPaymentsPingRequest() {\n\n\t\treturn buildPaymentsPingRequest(Collections.<String, String>emptyMap());\n\n\t}\n\t\n\t/**\n\t * Builds a payments ping request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete payments ping request\n\t */\n\tpublic static PaymentRequest buildPaymentsPingRequest(Map<String, String> parameters) {\n\n\t\tPaymentRequest request = buildDefaultPaymentRequest();\n\t\trequest.setCommand(Command.PING);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\t\treturn request;\n\n\t}\n\n\t/**\n\t * Builds a reporting ping request\n\t *\n\t * @return The complete reporting request to be sent to the server\n\t */\n\tpublic static ReportingRequest buildReportingPingRequest() {\n\n\t\treturn buildReportingPingRequest(Collections.<String, String>emptyMap());\n\n\t}\n\t\n\t/**\n\t * Builds a reporting ping request\n\t *\n\t * @return The complete reporting request to be sent to the server\n\t */\n\tpublic static ReportingRequest buildReportingPingRequest(Map<String, String> parameters) {\n\n\t\tReportingRequest request = buildDefaultReportingRequest();\n\t\trequest.setCommand(Command.PING);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\t\treturn request;\n\n\t}\n\n\t/* Payment Requests */\n\n\t/**\n\t * Builds a get bank list request\n\t *\n\t * @param paymentCountry\n\t * The country in which the transaction is being done\n\t * @return The complete bank list request\n\t */\n\tpublic static Request buildBankListRequest(PaymentCountry paymentCountry) {\n\n\t\tPaymentRequest request = buildDefaultPaymentRequest();\n\t\trequest.setCommand(Command.GET_BANKS_LIST);\n\n\t\trequest.setBankListInformation(new BankListInformation(\n\t\t\t\tPaymentMethod.PSE, paymentCountry));\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a payment request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @param transactionType\n\t * The transaction that is being done\n\t * @return The complete payment request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildPaymentRequest(Map<String, String> parameters,\n\t\t\tTransactionType transactionType) throws InvalidParametersException {\n\n\t\tPaymentRequest request = buildDefaultPaymentRequest();\n\t\trequest.setCommand(Command.SUBMIT_TRANSACTION);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\t\n\t\trequest.setTransaction(buildTransaction(parameters, transactionType));\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Sets the apiKey and apiLogin into merchant if the values are present \n\t * into the {@code parameters} and are not present into the constants:\n\t * <ul>\n\t * \t<li>PayU.apiKey</li>\n\t * \t<li>PayU.apiLogin</li>\n\t * </ul>\n\t * \n\t * @param parameters\n\t * @param request\n\t */\n\tprivate static void setAuthenticationByParameter(Map<String, String> parameters, CommandRequest request) {\n\n\t\t// The PayU.apiKey has priority over the parameters\n\t\tif (request.getMerchant() != null && request.getMerchant().getApiKey() == null) {\n\t\t\trequest.getMerchant().setApiKey(getParameter(parameters, PayU.PARAMETERS.API_KEY));\n\t\t}\n\t\t\n\t\t// The PayU.apiLogin has priority over the parameters\n\t\tif (request.getMerchant() != null && request.getMerchant().getApiLogin() == null) {\n\t\t\trequest.getMerchant().setApiLogin(getParameter(parameters, PayU.PARAMETERS.API_LOGIN));\n\t\t}\n\t}\n\n\t/**\n\t * Sets the language of the request if there is a parameter {@link PayU.PARAMETERS#LANGUAGE} present in\n\t * the parameters. If the parameter is present but it is not valid a warning is logged indicating that the\n\t * language will be obtained from {@link PayU#language}\n\t *\n\t * @param parameters the parameters\n\t * @param request the request\n\t */\n\tprivate static void setLanguageByParameter(Map<String, String> parameters, CommandRequest request) {\n\n\t\ttry {\n\t\t\tLanguage language = getEnumValueParameter(Language.class, parameters, PayU.PARAMETERS.LANGUAGE);\n\t\t\tif (language != null) {\n\t\t\t\trequest.setLanguage(language);\n\t\t\t}\n\t\t}\n\t\tcatch (InvalidParametersException e) {\n\t\t\tLoggerUtil.warning(\"The parameter {0} is invalid. The language will be obtained from PayU.language.\",\n\t\t\t\t\tPayU.PARAMETERS.LANGUAGE);\n\t\t}\n\t}\n\n\t/**\n\t * Sets the language of the request and the order if there is a parameter {@link PayU.PARAMETERS#LANGUAGE} present in\n\t * the parameters. If the parameter is present but it is not valid a warning is logged indicating that the\n\t * language will be obtained from {@link PayU#language}\n\t *\n\t * @param parameters the parameters\n\t * @param request the request\n\t */\n\tprivate static void setLanguageByParameter(Map<String, String> parameters, PaymentRequest request) {\n\n\t\ttry {\n\t\t\tLanguage language = getEnumValueParameter(Language.class, parameters, PayU.PARAMETERS.LANGUAGE);\n\t\t\tif (language != null) {\n\t\t\t\trequest.setLanguage(language);\n\n\t\t\t\tTransaction transaction = request.getTransaction();\n\t\t\t\tif (transaction == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tOrder order = transaction.getOrder();\n\t\t\t\tif (order == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\torder.setLanguage(language);\n\t\t\t}\n\t\t}\n\t\tcatch (InvalidParametersException e) {\n\t\t\tLoggerUtil.warning(\"The parameter {0} is invalid. The language will be obtained from PayU.language.\",\n\t\t\t\t\tPayU.PARAMETERS.LANGUAGE);\n\t\t}\n\t}\n\n\t/**\n\t * Builds the payment method list request\n\t *\n\t * @return The complete payment methods list request\n\t */\n\tpublic static Request buildPaymentMethodsListRequest() {\n\n\t\treturn buildPaymentMethodsListRequest(Collections.<String, String>emptyMap());\n\t}\n\t\n\t/**\n\t * Builds the payment methods list request.\n\t *\n\t * @param parameters\n\t * \t\t\tThe parameters to be sent to the server\n\t * @return The complete payment methods list request\n\t */\n\tpublic static Request buildPaymentMethodsListRequest(Map<String, String> parameters) {\n\n\t\tPaymentRequest request = buildDefaultPaymentRequest();\n\t\trequest.setCommand(Command.GET_PAYMENT_METHODS);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds the payment method request\n\t * \n\t * @param paymentMethod\n\t * @param apiKey\n\t * @param apiLogin\n\t * @return the payment method request\n\t */\n\tpublic static Request buildPaymentMethodAvailability(String paymentMethod, String apiKey, String apiLogin) {\n\t\t\n\t\tPaymentMethodRequest request = new PaymentMethodRequest();\n\t\trequest = (PaymentMethodRequest) buildDefaultRequest(request);\n\t\trequest.setTest(PayU.isTest);\n\t\trequest.setCommand(Command.GET_PAYMENT_METHOD_AVAILABILITY);\n\t\trequest.setPaymentMethod(paymentMethod);\n\t\t\n\t\t// Priority the api key obtained from PayU.apiKey\n\t\tif (request.getMerchant() != null && request.getMerchant().getApiKey() == null) {\n\t\t\trequest.getMerchant().setApiKey(apiKey);\n\t\t}\n\t\t\n\t\t// Priority the api login obtained from PayU.apiLogin\n\t\tif (request.getMerchant() != null && request.getMerchant().getApiLogin() == null) {\n\t\t\trequest.getMerchant().setApiLogin(apiLogin);\n\t\t}\n\t\t\n\t\treturn request;\n\t}\n\n\t/* Reporting Requests */\n\n\t/**\n\t * Builds a order details reporting by the id\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete reporting request to be sent to the server\n\t * @throws InvalidParametersException\n\t */\n\tpublic static ReportingRequest buildOrderReportingDetails(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tReportingRequest request = buildDefaultReportingRequest();\n\t\trequest.setCommand(Command.ORDER_DETAIL);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\t\t\n\t\tLong orderId = getLongParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ORDER_ID);\n\n\t\tMap<String, Object> details = new HashMap<String, Object>();\n\t\tdetails.put(PayU.PARAMETERS.ORDER_ID, orderId);\n\n\t\trequest.setDetails(details);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a order details reporting by reference code\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete reporting request to be sent to the server\n\t */\n\tpublic static ReportingRequest buildOrderReportingByReferenceCode(\n\t\t\tMap<String, String> parameters) {\n\n\t\tReportingRequest request = buildDefaultReportingRequest();\n\t\trequest.setCommand(Command.ORDER_DETAIL_BY_REFERENCE_CODE);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\trequest.setDetails(new HashMap<String, Object>(parameters));\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a transaction reporting by the id\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete reporting request to be sent to the server\n\t */\n\tpublic static ReportingRequest buildTransactionResponse(\n\t\t\tMap<String, String> parameters) {\n\n\t\tReportingRequest request = buildDefaultReportingRequest();\n\t\trequest.setCommand(Command.TRANSACTION_RESPONSE_DETAIL);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\trequest.setDetails(new HashMap<String, Object>(parameters));\n\n\t\treturn request;\n\t}\n\n\t/* Token Requests */\n\n\t/**\n\t * Builds a create credit card token request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete create credit card token request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildCreateTokenRequest(Map<String, String> parameters)\n\t\t\tthrows InvalidParametersException {\n\n\t\tString nameOnCard = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME);\n\n\t\tString payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);\n\n\t\tString dni = getParameter(parameters, PayU.PARAMETERS.PAYER_DNI);\n\n\t\tString creditCardNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_NUMBER);\n\n\t\tString expirationDate = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE);\n\n\t\tPaymentMethod paymentMethod = getEnumValueParameter(\n\t\t\t\tPaymentMethod.class, parameters, PayU.PARAMETERS.PAYMENT_METHOD);\n\n\t\tCreditCardTokenRequest request = new CreditCardTokenRequest();\n\t\trequest = (CreditCardTokenRequest) buildDefaultRequest(request);\n\t\trequest.setCommand(Command.CREATE_TOKEN);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\trequest.setCreditCardToken(buildCreditCardToken(nameOnCard, payerId,\n\t\t\t\tdni, paymentMethod, creditCardNumber, expirationDate));\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a get credit card token request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete get credit card token request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildGetCreditCardTokensRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\tString payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);\n\n\t\tString tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);\n\n\t\tString strStartDate = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.START_DATE);\n\n\t\tString strEndDate = getParameter(parameters, PayU.PARAMETERS.END_DATE);\n\n\t\tvalidateDateParameter(strStartDate, PayU.PARAMETERS.START_DATE,\n\t\t\t\tConstants.DEFAULT_DATE_FORMAT);\n\t\tvalidateDateParameter(strEndDate, PayU.PARAMETERS.END_DATE,\n\t\t\t\tConstants.DEFAULT_DATE_FORMAT);\n\n\t\tCreditCardTokenListRequest request = new CreditCardTokenListRequest();\n\t\trequest = (CreditCardTokenListRequest) buildDefaultRequest(request);\n\t\trequest.setCommand(Command.GET_TOKENS);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\tCreditCardTokenInformation information = new CreditCardTokenInformation();\n\n\t\tinformation.setPayerId(payerId);\n\t\tinformation.setTokenId(tokenId);\n\n\t\tinformation.setStartDate(strStartDate);\n\t\tinformation.setEndDate(strEndDate);\n\n\t\trequest.setCreditCardTokenInformation(information);\n\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a remove credit card token request\n\t *\n\t * @param parameters\n\t * The parameters to be sent to the server\n\t * @return The complete remove credit card token request\n\t */\n\tpublic static Request buildRemoveTokenRequest(Map<String, String> parameters) {\n\n\t\tString payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);\n\n\t\tString tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);\n\n\t\tRemoveCreditCardTokenRequest request = new RemoveCreditCardTokenRequest();\n\t\trequest = (RemoveCreditCardTokenRequest) buildDefaultRequest(request);\n\t\trequest.setCommand(Command.REMOVE_TOKEN);\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\n\t\tRemoveCreditCardToken remove = new RemoveCreditCardToken();\n\n\t\tremove.setPayerId(payerId);\n\t\tremove.setCreditCardTokenId(tokenId);\n\n\t\trequest.setRemoveCreditCardToken(remove);\n\n\t\treturn request;\n\t}\n\n\t/* PRIVATE METHODS */\n\n\t/* Default Requests Methods */\n\n\t/**\n\t * Builds a default request\n\t *\n\t * @return A simple request with merchant and language\n\t */\n\tprivate static Request buildDefaultRequest(CommandRequest request) {\n\t\trequest.setMerchant(buildMerchant());\n\t\trequest.setLanguage(PayU.language);\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds the default payment request\n\t *\n\t * @return A simple payment request with merchant, language and test\n\t */\n\tprivate static PaymentRequest buildDefaultPaymentRequest() {\n\t\tPaymentRequest request = new PaymentRequest();\n\t\trequest = (PaymentRequest) buildDefaultRequest(request);\n\t\trequest.setTest(PayU.isTest);\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds the default reporting request\n\t *\n\t * @return A simple reporting request with merchant, language and test\n\t */\n\tprivate static ReportingRequest buildDefaultReportingRequest() {\n\t\tReportingRequest request = new ReportingRequest();\n\t\trequest = (ReportingRequest) buildDefaultRequest(request);\n\t\trequest.setTest(PayU.isTest);\n\t\treturn request;\n\t}\n\n\t/**\n\t * Builds a credit card entity\n\t *\n\t * @param name\n\t * The credit card owner's name\n\t * @param creditCardNumber\n\t * The credit card's number\n\t * @param expirationDate\n\t * The credit card's expiration date\n\t * @param securityCode\n\t * The credit card's security code\n\t * @return The credit cards built\n\t */\n\tprivate static CreditCard buildCreditCard(String name,\n\t\t\tString creditCardNumber, String expirationDate,\n\t\t\tBoolean processWithoutCvv2, String securityCode) {\n\n\t\tif (creditCardNumber != null || processWithoutCvv2 != null\n\t\t\t\t|| securityCode != null) {\n\n\t\t\tCreditCard creditCard = new CreditCard();\n\t\t\tcreditCard.setName(name);\n\t\t\tcreditCard.setNumber(creditCardNumber);\n\t\t\tcreditCard.setExpirationDate(expirationDate);\n\t\t\tcreditCard.setProcessWithoutCvv2(processWithoutCvv2);\n\t\t\tcreditCard.setSecurityCode(securityCode);\n\n\t\t\treturn creditCard;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * builds credit card token\n\t *\n\t * @param nameOnCard\n\t * the credit card owner's name\n\t * @param payerId\n\t * the payer's id\n\t * @param payerIdentificationNumber\n\t * the payer's identification number\n\t * @param paymentMethod\n\t * the payment method being used\n\t * @param creditCardNumber\n\t * the credit card's number\n\t * @param expirationDate\n\t * the credit card's expiration date\n\t * @return The credit card token built\n\t */\n\tprivate static CreditCardToken buildCreditCardToken(String nameOnCard,\n\t\t\tString payerId, String payerIdentificationNumber,\n\t\t\tPaymentMethod paymentMethod, String creditCardNumber,\n\t\t\tString expirationDate) {\n\n\t\tCreditCardToken creditCardToken = new CreditCardToken();\n\t\tcreditCardToken.setName(nameOnCard);\n\t\tcreditCardToken.setPayerId(payerId);\n\t\tcreditCardToken.setIdentificationNumber(payerIdentificationNumber);\n\t\tcreditCardToken.setPaymentMethod(paymentMethod);\n\t\tcreditCardToken.setExpirationDate(expirationDate);\n\t\tcreditCardToken.setNumber(creditCardNumber);\n\n\t\treturn creditCardToken;\n\t}\n\n\t/**\n\t * Builds a credit card transaction\n\t *\n\t * @param transaction\n\t * The transaction to modify\n\t * @param nameOnCard\n\t * The credit card owner's name\n\t * @param creditCardNumber\n\t * The credit card's number\n\t * @param expirationDate\n\t * The credit card's expiration date\n\t * @param securityCode\n\t * The credit card's security code\n\t * @param installments\n\t * The number of installments for the transaction\n\t * @param createCreditCardToken\n\t * @throws InvalidParametersException\n\t */\n\tprivate static void buildCreditCardTransaction(Transaction transaction,\n\t\t\tString nameOnCard, String creditCardNumber, String expirationDate,\n\t\t\tBoolean processWithoutCvv2, String securityCode,\n\t\t\tInteger installments, Boolean createCreditCardToken)\n\t\t\tthrows InvalidParametersException {\n\n\t\ttransaction.setCreditCard(buildCreditCard(nameOnCard, creditCardNumber,\n\t\t\t\texpirationDate, processWithoutCvv2, securityCode));\n\n\t\tif (installments != null) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.INSTALLMENTS_NUMBER.name(),\n\t\t\t\t\tinstallments.toString());\n\t\t}\n\n\t\ttransaction.setCreateCreditCardToken(createCreditCardToken);\n\n\t}\n\n\t/**\n\t * Builds a merchant entity\n\t *\n\t * @return The merchant entity built\n\t */\n\tprivate static Merchant buildMerchant() {\n\n\t\tMerchant merchant = new Merchant();\n\t\tmerchant.setApiKey(PayU.apiKey);\n\t\tmerchant.setApiLogin(PayU.apiLogin);\n\n\t\treturn merchant;\n\t}\n\n\t/**\n\t * Builds the order\n\t *\n\t * @param accountId\n\t * The account's id number\n\t * @param txCurrency\n\t * The currency of the transaction\n\t * @param txValue\n\t * The value of the transaction\n\t * @param description\n\t * The description of the transaction\n\t * @param referenceCode\n\t * The order's reference code\n\t * @param notifyUrl\n\t * \t\t\t The confirmation page URL\n\t * @return The order built\n\t */\n\tprivate static Order buildOrder(Integer accountId, Currency txCurrency,\n\t\t\tBigDecimal txValue, BigDecimal taxValue, BigDecimal taxReturnBase,\n\t\t\tString description, String referenceCode, String notifyUrl) {\n\n\t\tOrder order = new Order();\n\t\torder.setAccountId(accountId);\n\t\torder.setDescription(description);\n\t\torder.setLanguage(PayU.language);\n\t\torder.setReferenceCode(referenceCode);\n\t\torder.setNotifyUrl(notifyUrl);\n\t\torder.setAdditionalValues(buildAdditionalValues(txCurrency, txValue,\n\t\t\t\ttaxValue, taxReturnBase));\n\n\t\treturn order;\n\t}\n\n\t/**\n\t * Builds the buyer entity\n\t *\n\t * @param parameters\n\t * The parameters map to build the buyer\n\t * @return The buyer built\n\t */\n\tprivate static Buyer buildBuyer(Map<String, String> parameters) throws InvalidParametersException {\n\n\t\tString buyerId = getParameter(parameters, PayU.PARAMETERS.BUYER_ID);\n\t\tString buyerEmail = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_EMAIL);\n\t\tString buyerName = getParameter(parameters, PayU.PARAMETERS.BUYER_NAME);\n\t\tString buyerCNPJ = getParameter(parameters, PayU.PARAMETERS.BUYER_CNPJ);\n\t\tString buyerContactPhone = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_CONTACT_PHONE);\n\t\tString buyerDniNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_DNI);\n\t\tDocumentType buyerDniType = getEnumValueParameter(DocumentType.class,\n\t\t\t\tparameters, PayU.PARAMETERS.BUYER_DNI_TYPE);\n\t\tString buyerCity = getParameter(parameters, PayU.PARAMETERS.BUYER_CITY);\n\t\tString buyerCountry = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_COUNTRY);\n\t\tString buyerPhone = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_PHONE);\n\t\tString buyerPostalCode = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_POSTAL_CODE);\n\t\tString buyerState = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_STATE);\n\t\tString buyerStreet = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_STREET);\n\t\tString buyerStreet2 = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_STREET_2);\n\t\tString buyerStreet3 = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.BUYER_STREET_3);\n\n\t\tBuyer buyer = new Buyer();\n\t\tbuildPerson(buyer, buyerId, buyerEmail, buyerName, buyerCNPJ,\n\t\t\t\tbuyerContactPhone, buyerDniNumber, buyerDniType, buyerCity,\n\t\t\t\tbuyerCountry, buyerPhone, buyerPostalCode, buyerState,\n\t\t\t\tbuyerStreet, buyerStreet2, buyerStreet3);\n\n\t\treturn buyer;\n\t}\n\n\t/**\n\t * Builds the payer entity\n\t *\n\t * @param parameters The parameters map to build the payer\n\t * @return The payer built\n\t * @throws InvalidParametersException\n\t */\n\tprivate static Payer buildPayer(final Map<String, String> parameters) throws InvalidParametersException {\n\n\t\tfinal String payerId = getParameter(parameters, PayU.PARAMETERS.PAYER_ID);\n\t\tfinal String payerEmail = getParameter(parameters, PayU.PARAMETERS.PAYER_EMAIL);\n\t\tfinal String payerName = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME);\n\t\tfinal String payerCNPJ = getParameter(parameters, PayU.PARAMETERS.PAYER_CNPJ);\n\t\tfinal String payerContactPhone = getParameter(parameters, PayU.PARAMETERS.PAYER_CONTACT_PHONE);\n\t\tfinal String payerDniNumber = getParameter(parameters, PayU.PARAMETERS.PAYER_DNI);\n\t\tfinal String payerCity = getParameter(parameters, PayU.PARAMETERS.PAYER_CITY);\n\t\tfinal String payerCountry = getParameter(parameters, PayU.PARAMETERS.PAYER_COUNTRY);\n\t\tfinal String payerPhone = getParameter(parameters, PayU.PARAMETERS.PAYER_PHONE);\n\t\tfinal String payerPostalCode = getParameter(parameters, PayU.PARAMETERS.PAYER_POSTAL_CODE);\n\t\tfinal String payerState = getParameter(parameters, PayU.PARAMETERS.PAYER_STATE);\n\t\tfinal String payerStreet = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET);\n\t\tfinal String payerStreet2 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_2);\n\t\tfinal String payerStreet3 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_3);\n\n\t\tfinal String payerBusinessName = getParameter(parameters, PayU.PARAMETERS.PAYER_BUSINESS_NAME);\n\t\tfinal PersonType payerType = getEnumValueParameter(PersonType.class, parameters,\n\t\t\t\tPayU.PARAMETERS.PAYER_PERSON_TYPE);\n\t\tfinal String payerBirthdate = getParameter(parameters, PayU.PARAMETERS.PAYER_BIRTH_DATE);\n\t\tfinal DocumentType payerDniType = getEnumValueParameter(DocumentType.class, parameters,\n\t\t\t\tPayU.PARAMETERS.PAYER_DNI_TYPE);\n\n\t\tif (payerBirthdate != null && !payerBirthdate.isEmpty()) {\n\n\t\t\tvalidateDateParameter(payerBirthdate, PayU.PARAMETERS.PAYER_BIRTH_DATE,\n\t\t\t\t\tConstants.DEFAULT_DATE_WITHOUT_HOUR_FORMAT, false);\n\t\t}\n\n\t\tfinal Payer payer = new Payer();\n\n\t\tbuildPerson(payer, payerId, payerEmail, payerName, payerCNPJ,\n\t\t\t\tpayerContactPhone, payerDniNumber, payerDniType, payerCity,\n\t\t\t\tpayerCountry, payerPhone, payerPostalCode, payerState,\n\t\t\t\tpayerStreet, payerStreet2, payerStreet3);\n\n\t\tpayer.setBusinessName(payerBusinessName);\n\t\tpayer.setPayerType(payerType);\n\t\tpayer.setBirthdate(payerBirthdate);\n\n\t\treturn payer;\n\t}\n\n\t/**\n\t * Builds the person entity\n\t *\n\t * @param person\n\t * The person to build\n\t * @param personId\n\t * The person's id in the merchant\n\t * @param email\n\t * The person's e-mail\n\t * @param name\n\t * The person's name\n\t * @param CNPJ\n\t * The person's CNPJ\n\t * @param contactPhone\n\t * The person's contact phone\n\t * @param dniNumber\n\t * The person's dni number\n\t * @param dniType\n\t * The person's dni type\n\t * @param city\n\t * The person's city\n\t * @param country\n\t * The person's country\n\t * @param phone\n\t * The person's phone\n\t * @param postalCode\n\t * The person's postal code\n\t * @param state\n\t * The person's state\n\t * @param street\n\t * The person's street\n\t * @param street2\n\t * The person's street2\n\t * @param street3\n\t * The person's street3\n\t */\n\tprivate static void buildPerson(Person person, String personId,\n\t\t\tString email, String name, String CNPJ, String contactPhone,\n\t\t\tString dniNumber, DocumentType dniType, String city, String country,\n\t\t\tString phone, String postalCode, String state, String street,\n\t\t\tString street2, String street3) {\n\n\t\tperson.setMerchantPersonId(personId);\n\t\tperson.setEmailAddress(email);\n\t\tperson.setFullName(name);\n\t\tperson.setCNPJ(CNPJ);\n\n\t\tperson.setContactPhone(contactPhone);\n\t\tperson.setDniNumber(dniNumber);\n\t\tperson.setDniType(dniType);\n\n\t\tAddress address = new Address();\n\t\taddress.setCity(city);\n\t\taddress.setCountry(country);\n\t\taddress.setPhone(phone);\n\t\taddress.setPostalCode(postalCode);\n\t\taddress.setState(state);\n\t\taddress.setLine1(street);\n\t\taddress.setLine2(street2);\n\t\taddress.setLine3(street3);\n\n\t\tperson.setAddress(address);\n\t}\n\n\t/**\n\t * Build a transaction request based on the query parameters\n\t *\n\t * @param parameters\n\t * The parameters map to send to the request\n\t * @param transactionType\n\t * The type of payment transaction to build\n\t * @return The transaction to be sent built\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Transaction buildTransaction(Map<String, String> parameters,\n\t\t\tTransactionType transactionType) throws InvalidParametersException {\n\n\t\tString payerName = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME);\n\n\t\tLong orderId = getLongParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ORDER_ID);\n\t\tInteger accountId = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.ACCOUNT_ID);\n\t\tString merchantIdParam = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.MARCHANT_ID);\n\t\tString apiKeyParam = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.API_KEY);\n\n\t\tString orderReference = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.REFERENCE_CODE);\n\t\tString orderDescription = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DESCRIPTION);\n\t\tString orderNotifyUrl = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.NOTIFY_URL);\n\n\t\tString creditCardHolderName = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_HOLDER_NAME);\n\t\tString creditCardNumber = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_NUMBER);\n\t\tString creditCardExpirationDate = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE);\n\t\tBoolean processWithoutCvv2 = getBooleanParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PROCESS_WITHOUT_CVV2);\n\t\tString securityCode = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREDIT_CARD_SECURITY_CODE);\n\n\t\tBoolean createCreditCardToken = getBooleanParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.CREATE_CREDIT_CARD_TOKEN);\n\n\t\tString parentTransactionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.TRANSACTION_ID);\n\n\t\tString expirationDate = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.EXPIRATION_DATE);\n\n\t\tString cookie = getParameter(parameters, PayU.PARAMETERS.COOKIE);\n\n\t\tPaymentCountry paymentCountry = getEnumValueParameter(\n\t\t\t\tPaymentCountry.class, parameters, PayU.PARAMETERS.COUNTRY);\n\n\t\t//Obtains the payment method. If the parameter is a value that doesn't belong to the enum, this return null and continue\n\n\t\tPaymentMethod paymentMethod = CommonRequestUtil\n\t\t\t\t.getPaymentMethodParameter(parameters,PayU.PARAMETERS.PAYMENT_METHOD);\n\n\t\tString reason = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.REASON);\n\n\t\tCurrency txCurrency = getEnumValueParameter(Currency.class, parameters,\n\t\t\t\tPayU.PARAMETERS.CURRENCY);\n\n\t\tBigDecimal txValue = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.VALUE);\n\n\t\tInteger installments = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.INSTALLMENTS_NUMBER);\n \n Integer promotionId = getIntegerParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PROMOTION_ID);\n\n\t\t// TAX_VALUE\n\t\tBigDecimal taxValue = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.TAX_VALUE);\n\n\t\t// TAX_RETURN_BASE\n\t\tBigDecimal taxReturnBase = getBigDecimalParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.TAX_RETURN_BASE);\n\n\t\t// IP Address\n\t\tString ipAddress = getParameter(parameters, PayU.PARAMETERS.IP_ADDRESS);\n\n\t\t// User Agent\n\t\tString userAgent = getParameter(parameters, PayU.PARAMETERS.USER_AGENT);\n\n\t\t// Device session ID\n\t\tString deviceSessionId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DEVICE_SESSION_ID);\n\n\t\t// Response page\n\t\tString responseUrlPage = getParameter(parameters, PayU.PARAMETERS.RESPONSE_URL);\n\n\t\tString tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID);\n\n\t\tTransaction transaction = new Transaction();\n\t\ttransaction.setType(transactionType);\n\n\t\tif (responseUrlPage != null) {\n\t\t\taddResponseUrlPage(transaction, responseUrlPage);\n\t\t}\n\n\t\t// Shipping address fields\n\t\tString shippingAddressLine1 = getParameter(parameters, PayU.PARAMETERS.SHIPPING_ADDRESS_1);\n\t\tString shippingAddressLine2 = getParameter(parameters, PayU.PARAMETERS.SHIPPING_ADDRESS_2);\n\t\tString shippingAddressLine3 = getParameter(parameters, PayU.PARAMETERS.SHIPPING_ADDRESS_3);\n\t\tString shippingAddressCity = getParameter(parameters, PayU.PARAMETERS.SHIPPING_CITY);\n\t\tString shippingAddressState = getParameter(parameters, PayU.PARAMETERS.SHIPPING_STATE);\n\t\tString shippingAddressCountry = getParameter(parameters, PayU.PARAMETERS.SHIPPING_COUNTRY);\n\t\tString shippingAddressPostalCode = getParameter(parameters, PayU.PARAMETERS.SHIPPING_POSTAL_CODE);\n\t\tString shippingAddressPhone = getParameter(parameters, PayU.PARAMETERS.SHIPPING_PHONE);\n\n\t\tBoolean termsAndConditionsAcepted = getBooleanParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.TERMS_AND_CONDITIONS_ACEPTED);\n\n\t\tString bcashRequestContentType = getParameter(parameters, PayU.PARAMETERS.BCASH_REQUEST_CONTENT_TYPE);\n\t\tString bcashRequestContent = getParameter(parameters, PayU.PARAMETERS.BCASH_REQUEST_CONTENT);\n\n\t\tif (bcashRequestContentType != null || bcashRequestContent != null) {\n\t\t\ttransaction.setBcashRequest(buildBcashRequest(bcashRequestContentType, bcashRequestContent));\n\t\t}\n\t\t\n\t\tInteger platformId = getIntegerParameter(parameters, PayU.PARAMETERS.PLATFORM_ID);\n\t\ttransaction.setPlatformId(platformId);\n\n\t\tTransactionSource transactionSource = getEnumValueParameter(TransactionSource.class,\n\t\t\t\tparameters,\n\t\t\t\tPayU.PARAMETERS.TRANSACTION_SOURCE);\n\t\tif (transactionSource == null) {\n\t\t\ttransactionSource = TransactionSource.PAYU_SDK;\n\t\t}\n\t\ttransaction.setSource(transactionSource);\n\n\t\tif (TransactionType.AUTHORIZATION_AND_CAPTURE.equals(transactionType)\n\t\t\t\t|| TransactionType.AUTHORIZATION.equals(transactionType)) {\n\n\t\t\ttransaction.setPaymentCountry(paymentCountry);\n\n\t\t\tString signature = getParameter(parameters,\n\t\t\t\t\tPayU.PARAMETERS.SIGNATURE);\n\t\t\tString merchantId = PayU.merchantId != null ? PayU.merchantId : merchantIdParam;\n\t\t\tString apiKey = PayU.apiKey != null ? PayU.apiKey : apiKeyParam;\n\n\t\t\tOrder order = buildOrder(accountId, txCurrency, txValue,\n\t\t\t\t\ttaxValue, taxReturnBase, orderDescription,\n\t\t\t\t\torderReference, orderNotifyUrl);\n\n\t\t\tif (signature == null && merchantId != null) {\n\t\t\t\tsignature = SignatureHelper.buildSignature(order,\n\t\t\t\t\t\tInteger.parseInt(merchantId), apiKey,\n\t\t\t\t\t\tSignatureHelper.DECIMAL_FORMAT_3,\n\t\t\t\t\t\tSignatureHelper.MD5_ALGORITHM);\n\t\t\t}\n\n\t\t\torder.setSignature(signature);\n\n\t\t\t// Adds the shipping address\n\t\t\tAddressV4 shippingAddress = buildShippingAddress(\n\t\t\t\t\tshippingAddressLine1, shippingAddressLine2,\n\t\t\t\t\tshippingAddressLine3, shippingAddressCity,\n\t\t\t\t\tshippingAddressState, shippingAddressCountry,\n\t\t\t\t\tshippingAddressPostalCode, shippingAddressPhone);\n\t\t\torder.setShippingAddress(shippingAddress);\n\n\t\t\ttransaction.setOrder(order);\n\n\t\t\tif (orderId != null ) {\n\t\t\t\ttransaction.getOrder().setId(orderId);\n\t\t\t}\n\n\t\t\ttransaction.getOrder().setBuyer(buildBuyer(parameters));\n\n\t\t\ttransaction.setCookie(cookie);\n\n\t\t\t// MAF parameters\n\t\t\ttransaction.setUserAgent(userAgent);\n\t\t\ttransaction.setIpAddress(ipAddress);\n\t\t\ttransaction.setDeviceSessionId(deviceSessionId);\n\n\t\t\t// PSE extra parameters\n\t\t\tif (PaymentMethod.PSE.equals(paymentMethod)) {\n\t\t\t\taddPSEExtraParameters(transaction, parameters);\n\t\t\t}\n\n\n\t\t\tif (creditCardNumber != null || tokenId != null) {\n\t\t\t\t\n\t\t\t\t// If credit card holder name is null or empty, a payer name\n\t\t\t\t// will be send to build a credit card\n\t\t\t\tcreditCardHolderName = creditCardHolderName != null\n\t\t\t\t\t\t&& !creditCardHolderName.trim().equals(\"\") ? creditCardHolderName\n\t\t\t\t\t\t: payerName;\n\t\t\t\t\n\t\t\t\tbuildCreditCardTransaction(transaction, creditCardHolderName,\n\t\t\t\t\t\tcreditCardNumber, creditCardExpirationDate,\n\t\t\t\t\t\tprocessWithoutCvv2, securityCode, installments,\n\t\t\t\t\t\tcreateCreditCardToken);\n\t\t\t}\n\n\t\t\tif (expirationDate != null) {\n\t\t\t\tDate expDate = validateDateParameter(expirationDate,\n\t\t\t\t\t\tPayU.PARAMETERS.EXPIRATION_DATE,\n\t\t\t\t\t\tConstants.DEFAULT_DATE_FORMAT);\n\t\t\t\ttransaction.setExpirationDate(expDate);\n\t\t\t}\n \n if (promotionId != null){\n \ttransaction.addExtraParameter(\n ExtraParemeterNames.PROMOTION_ID.name(),\n promotionId.toString());\n }\n\n\t\t\ttransaction.setCreditCardTokenId(tokenId);\n\t\t\t//Set the param of Payment Method\n\t\t\tString paramPaymentMethod = getParameter(parameters, PayU.PARAMETERS.PAYMENT_METHOD);\n\t\t\ttransaction.setPaymentMethod(paramPaymentMethod);\n\t\t\t//transaction.setPaymentMethod(paymentMethod);\n\t\t\ttransaction.setPayer(buildPayer(parameters));\n\n\t\t\ttransaction.setTermsAndConditionsAcepted(termsAndConditionsAcepted);\n\n\t\t\t//Set the integration method of request\n\t\t\tString paramIntegrationMethod = getParameter(parameters, PayU.PARAMETERS.INTEGRATION_METHOD);\n\t\t\ttransaction.setIntegrationMethod(TransactionIntegrationMethod.fromString(paramIntegrationMethod ));\n\t\t\t\n\t\t\taddTransactionExtraParameters(transaction, parameters);\n\t\t} else if (TransactionType.VOID.equals(transactionType)\n\t\t\t\t|| TransactionType.REFUND.equals(transactionType)\n\t\t\t\t|| TransactionType.PARTIAL_REFUND.equals(transactionType)\n\t\t\t\t|| TransactionType.CAPTURE.equals(transactionType)) {\n\n\t\t\ttransaction.setParentTransactionId(parentTransactionId);\n\n\t\t\tOrder order = new Order();\n\t\t\torder.setId(orderId);\n\n\t\t\torder.setReferenceCode(orderReference);\n\t\t\torder.setDescription(orderDescription);\n\t\t\torder.setLanguage(PayU.language);\n\n\t\t\ttransaction.setAdditionalValues(buildAdditionalValues(txCurrency,\n\t\t\t\t\ttxValue, taxValue, taxReturnBase));\n\t\t\ttransaction.setOrder(order);\n\n\t\t\ttransaction.setReason(reason);\n\t\t}\n\n\t\treturn transaction;\n\t}\n\t/**\n\t * Adds the transaction extra parameters.\n\t *\n\t * @param transaction the transaction\n\t * @param parameters the parameters\n\t * @throws InvalidParametersException the invalid parameters exception\n\t */\n\tprivate static void addTransactionExtraParameters(Transaction transaction, Map<String, String> parameters) throws InvalidParametersException {\n\n\t\tString extra1 = getParameter(parameters, PayU.PARAMETERS.EXTRA1);\n\t\tString extra2 = getParameter(parameters, PayU.PARAMETERS.EXTRA2);\n\t\tString extra3 = getParameter(parameters, PayU.PARAMETERS.EXTRA3);\n\t\tString dmApiSubject = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DM_API_SUBJECT);\n\n\t\tString dmApiMessage = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DM_API_MESSAGE);\n\n\t\tString dmApiUniqueMessageId = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.DM_API_UNIQUE_MESSAGE_ID);\n\n\t\t\n\t\tif (extra1 != null) {\n\t\t\ttransaction.addExtraParameter(ExtraParemeterNames.EXTRA1.name(), extra1);\n\t\t}\n\t\t\n\t\tif (extra2 != null) {\n\t\t\ttransaction.addExtraParameter(ExtraParemeterNames.EXTRA2.name(), extra2);\n\t\t}\n\t\t\n\t\tif (extra3 != null) {\n\t\t\ttransaction.addExtraParameter(ExtraParemeterNames.EXTRA3.name(), extra3);\n\t\t}\n\n\t\tif (StringUtils.isNotEmpty(dmApiMessage)) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.DM_API_MESSAGE.name(),\n\t\t\t\t\tdmApiMessage);\n\t\t}\n\n\t\tif (StringUtils.isNotEmpty(dmApiSubject)) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.DM_API_SUBJECT.name(),\n\t\t\t\t\tdmApiSubject);\n\t\t}\n\n\t\tif (StringUtils.isNotEmpty(dmApiUniqueMessageId)) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.DM_API_UNIQUE_MESSAGE_ID.name(),\n\t\t\t\t\tdmApiUniqueMessageId);\n\t\t}\n\t}\n\n\t/**\n\t * Adds the extra parameters required by the PSE payment method\n\t *\n\t * @param transaction\n\t * @param parameters\n\t * @throws InvalidParametersException\n\t */\n\tprivate static void addPSEExtraParameters(Transaction transaction,\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\t// PSE reference identification 1\n\t\tString pseReference1 = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.IP_ADDRESS);\n\n\t\t// PSE reference identification 2\n\t\tString pseReference2 = getEnumValueParameter(DocumentType.class,\n\t\t\t\tparameters, PayU.PARAMETERS.PAYER_DOCUMENT_TYPE).name();\n\n\t\t// PSE reference identification 3\n\t\tString pseReference3 = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PAYER_DNI);\n\n\t\t// PSE user type N-J (Natural or Legal)\n\t\tPersonType pseUserType = getEnumValueParameter(PersonType.class,\n\t\t\t\tparameters, PayU.PARAMETERS.PAYER_PERSON_TYPE);\n\n\t\t// PSE financial institution code (Bank code)\n\t\tString pseFinancialInstitutionCode = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PSE_FINANCIAL_INSTITUTION_CODE);\n\n\t\t// PSE financial institution name (Bank Name)\n\t\tString pseFinancialInstitutionName = getParameter(parameters,\n\t\t\t\tPayU.PARAMETERS.PSE_FINANCIAL_INSTITUTION_NAME);\n\n\t\tif (pseFinancialInstitutionCode != null) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.FINANCIAL_INSTITUTION_CODE.name(),\n\t\t\t\t\tpseFinancialInstitutionCode);\n\t\t}\n\n\t\tif (pseFinancialInstitutionName != null) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.FINANCIAL_INSTITUTION_NAME.name(),\n\t\t\t\t\tpseFinancialInstitutionName);\n\t\t}\n\n\t\tif (pseUserType != null) {\n\t\t\ttransaction.addExtraParameter(ExtraParemeterNames.USER_TYPE.name(),\n\t\t\t\t\tpseUserType.getPseCode());\n\t\t}\n\n\t\tif (pseReference1 != null) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.PSE_REFERENCE1.name(), pseReference1);\n\t\t}\n\n\t\tif (pseReference2 != null) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.PSE_REFERENCE2.name(), pseReference2);\n\t\t}\n\n\t\tif (pseReference3 != null) {\n\t\t\ttransaction.addExtraParameter(\n\t\t\t\t\tExtraParemeterNames.PSE_REFERENCE3.name(), pseReference3);\n\t\t}\n\n\t}\n\n\tpublic static String mapToString(Map<String, String> map)\n\t\t\tthrows PayUException {\n\t\tStringBuilder stringBuilder = new StringBuilder();\n\t\tif (map != null && !map.isEmpty()) {\n\t\t\tfor (Map.Entry<String, String> entry : map.entrySet()) {\n\t\t\t\tString key = (String) entry.getKey();\n\t\t\t\tString value = (String) entry.getValue();\n\t\t\t\tif (value != null) {\n\t\t\t\t\tif (stringBuilder.length() > 0) {\n\t\t\t\t\t\tstringBuilder.append(APPENDER);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstringBuilder.append((key != null ? URLEncoder.encode(\n\t\t\t\t\t\t\t\tkey, ENCODING) : \"\"));\n\t\t\t\t\t\tstringBuilder.append(EQUALS);\n\t\t\t\t\t\tstringBuilder.append(URLEncoder.encode(\n\t\t\t\t\t\t\t\tvalue, ENCODING));\n\t\t\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\t\t\tthrow new PayUException(ErrorCode.INVALID_PARAMETERS,\n\t\t\t\t\t\t\t\t\"can not encode the url\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn stringBuilder.toString();\n\t}\n\n\n\t/**\n\t * Method for add in the transaccion a {@link ExtraParemeterNames} with the response url page.\n\t * <ul>\n\t * \t<li>1. Get of the {@link ExtraParemeterNames} RESPONSE_URL.</li>\n\t * \t<li>2. sets in the extra parameter of the {@code responseUrl value}.</li>\n\t * </ul>\n\t *\n\t * @param transaction\n\t * @param responseUrl\n\t * @throws InvalidParametersException\n\t */\n\tprivate static void addResponseUrlPage(final Transaction transaction, String responseUrl) throws InvalidParametersException{\n\n\t\ttransaction.addExtraParameter(ExtraParemeterNames.RESPONSE_URL.name(),\n\t\t\t\tresponseUrl);\n\t}\n\n\t/**\n\t * Builds a {@link Address} according to parameters.\n\t *\n\t * @param shippingAddressLine1\n\t * the address line 1 to set.\n\t * @param shippingAddressLine2\n\t * the address line 2 to set.\n\t * @param shippingAddressLine3\n\t * the address line 3 to set.\n\t * @param shippingAddressCity\n\t * the address city to set.\n\t * @param shippingAddressState\n\t * the address state to set.\n\t * @param shippingAddressCountry\n\t * the address country to set.\n\t * @param shippingAddressPostalCode\n\t * the address postal code to set.\n\t * @param shippingAddressPhone\n\t * the address phone to set.\n\t * @return {@link Address} object.\n\t */\n\tprivate static AddressV4 buildShippingAddress(String shippingAddressLine1,\n\t\t\tString shippingAddressLine2, String shippingAddressLine3,\n\t\t\tString shippingAddressCity, String shippingAddressState,\n\t\t\tString shippingAddressCountry, String shippingAddressPostalCode,\n\t\t\tString shippingAddressPhone) {\n\n\t\tAddressV4 shippingAddress = new AddressV4();\n\t\tshippingAddress.setStreet1(shippingAddressLine1);\n\t\tshippingAddress.setStreet2(shippingAddressLine2);\n\t\tshippingAddress.setStreet3(shippingAddressLine3);\n\t\tshippingAddress.setCity(shippingAddressCity);\n\t\tshippingAddress.setState(shippingAddressState);\n\t\tshippingAddress.setCountry(shippingAddressCountry);\n\t\tshippingAddress.setPostalCode(shippingAddressPostalCode);\n\t\tshippingAddress.setPhone(shippingAddressPhone);\n\n\t\treturn shippingAddress;\n\t}\n\n\t/**\n\t * Builds a Bcash request\n\t *\n\t * @param contentType the content type\n\t * @param content the content\n\t * @return the Bcash request\n\t * @throws InvalidParametersException if any of the arguments is null\n\t */\n\tprivate static BcashRequest buildBcashRequest(String contentType, String content) throws InvalidParametersException {\n\n\t\tif (contentType == null || content == null) {\n\t\t\tthrow new InvalidParametersException(\"Both the bcashRequestContentType and bcashRequestContent must be set set\");\n\t\t}\n\n\t\tBcashRequest bcashRequest = new BcashRequest();\n\t\tbcashRequest.setContentType(contentType);\n\t\tbcashRequest.setContent(content);\n\t\treturn bcashRequest;\n\t}\n\t/**\n\t * Builds a recurring bill request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete recurring bill request\n\t * @throws InvalidParametersException\n\t */\n\tpublic static Request buildConfirmationPageRequest(\n\t\t\tMap<String, String> parameters) throws InvalidParametersException {\n\n\t\t// Recurring bill basic parameters\n\t\tString transactionId = getParameter(parameters, PayU.PARAMETERS.TRANSACTION_ID);\n\n\t\tConfirmationPageRequest request = new ConfirmationPageRequest();\n\t\tsetAuthenticationCredentials(parameters, request);\n\t\trequest.setTransactionId(transactionId);\n\n\t\treturn request;\n\t}\n\t\n\t/**\n\t * Sets the authentication credentials to the API request object.\n\t *\n\t * @param parameters the parameters.\n\t * @param request the API request.\n\t */\n\tpublic static void setAuthenticationCredentials(Map<String, String> parameters, Request request) {\n\n\t\trequest.setApiLogin(getParameter(parameters, PayU.PARAMETERS.API_LOGIN));\n\t\trequest.setApiKey(getParameter(parameters, PayU.PARAMETERS.API_KEY));\n\n\t\tString language = getParameter(parameters, PayU.PARAMETERS.LANGUAGE);\n\t\tif (language != null) {\n\t\t\trequest.setLanguage(Language.valueOf(language));\n\t\t}\n\t\telse {\n\t\t\trequest.setLanguage(null);\n\t\t}\n\n\t\tString isTest = getParameter(parameters, PayU.PARAMETERS.IS_TEST);\n\t\tif (isTest != null) {\n\t\t\trequest.setTest(Boolean.getBoolean(getParameter(parameters, PayU.PARAMETERS.IS_TEST)));\n\t\t}\n\t\telse {\n\t\t\trequest.setTest(false);\n\t\t}\n\t}\n\n\t/**\n\t * Builds a massive token payments request\n\t *\n\t * @param parameters The parameters to be sent to the server\n\t * @return The complete massive token payments payment request\n\t * @throws InvalidParametersException when a received parameter is invalid\n\t */\n\tpublic static Request buildMassiveTokenPaymentsRequest(final Map<String, String> parameters)\n\t\t\tthrows InvalidParametersException {\n\n\t\tfinal MassiveTokenPaymentsRequest request = (MassiveTokenPaymentsRequest) buildDefaultRequest(\n\t\t\t\tnew MassiveTokenPaymentsRequest());\n\n\t\tsetAuthenticationByParameter(parameters, request);\n\t\tsetLanguageByParameter(parameters, request);\n\t\trequest.setCommand(Command.PROCESS_BATCH_TRANSACTIONS_TOKEN);\n\t\trequest.setContentFile(getByteArrayParameter(parameters, PayU.PARAMETERS.CONTENT_FILE));\n\n\t\treturn request;\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.List; import java.util.Map; import com.payu.sdk.constants.Resources.RequestMethod; import com.payu.sdk.exceptions.ConnectionException; import com.payu.sdk.exceptions.InvalidParametersException; import com.payu.sdk.exceptions.PayUException; import com.payu.sdk.exceptions.SDKException.ErrorCode; import com.payu.sdk.helper.HttpClientHelper; import com.payu.sdk.model.Bank; import com.payu.sdk.model.Merchant; import com.payu.sdk.model.PaymentCountry; import com.payu.sdk.model.PaymentMethodApi; import com.payu.sdk.model.PaymentMethodComplete; import com.payu.sdk.model.Transaction; import com.payu.sdk.model.TransactionResponse; import com.payu.sdk.model.TransactionType; import com.payu.sdk.model.request.Command; import com.payu.sdk.model.response.ResponseCode; import com.payu.sdk.payments.model.BankListResponse; import com.payu.sdk.payments.model.MassiveTokenPaymentsResponse; import com.payu.sdk.payments.model.PaymentAttemptRequest; import com.payu.sdk.payments.model.PaymentMethodListResponse; import com.payu.sdk.payments.model.PaymentMethodResponse; import com.payu.sdk.payments.model.PaymentRequest; import com.payu.sdk.payments.model.PaymentResponse; import com.payu.sdk.utils.CommonRequestUtil; import com.payu.sdk.utils.PaymentMethodMap; import com.payu.sdk.utils.PaymentPlanRequestUtil; import com.payu.sdk.utils.RequestUtil;
public static TransactionResponse doRefundWithRequestHeaders(Map<String, String> parameters, Map<String, String> headers) throws PayUException, InvalidParametersException, ConnectionException { return processTransactionWithRequestHeaders(parameters, headers, TransactionType.REFUND); } /** * Do a partial refund transaction * * @param parameters * The parameters to be sent to the server * @return The transaction response to the request sent * @throws PayUException * @throws ConnectionException * @throws InvalidParametersException */ public static TransactionResponse doPartialRefund(Map<String, String> parameters) throws PayUException, InvalidParametersException, ConnectionException { return processTransaction(parameters, TransactionType.PARTIAL_REFUND); } /** * Do partial refund with request headers. * * @param parameters the parameters * @param headers the headers * @return the transaction response * @throws PayUException the pay U exception * @throws InvalidParametersException the invalid parameters exception * @throws ConnectionException the connection exception */ public static TransactionResponse doPartialRefundWithRequestHeaders( Map<String, String> parameters, Map<String, String> headers) throws PayUException, InvalidParametersException, ConnectionException { return processTransactionWithRequestHeaders(parameters, headers, TransactionType.PARTIAL_REFUND); } /** * Makes massive token payments petition * * @param parameters The parameters to be sent to the server * @return The transaction response to the request sent * @throws PayUException when the response of payments-api is error * @throws InvalidParametersException when a received parameter is invalid * @throws ConnectionException Connection error with payments-api */ public static String doMassiveTokenPayments(final Map<String, String> parameters) throws PayUException, InvalidParametersException, ConnectionException { validateMassiveTokenPaymentsRequest(parameters); return sendMassiveTokenPayments(parameters).getId(); } /** * Makes payment petition * * @param parameters * The parameters to be sent to the server * @param transactionType * The type of the payment transaction * @return The transaction response to the request sent * @throws PayUException * @throws InvalidParametersException * @throws ConnectionException */ private static TransactionResponse doPayment( Map<String, String> parameters, TransactionType transactionType) throws PayUException, InvalidParametersException, ConnectionException { return doPayment(parameters, transactionType, HttpClientHelper.SOCKET_TIMEOUT); } /** * Makes payment petition * * @param parameters * The parameters to be sent to the server * @param transactionType * The type of the payment transaction * @param the socket time out. * @return The transaction response to the request sent * @throws PayUException * @throws InvalidParametersException * @throws ConnectionException */ private static TransactionResponse doPayment( Map<String, String> parameters, TransactionType transactionType, Integer socketTimeOut) throws PayUException, InvalidParametersException, ConnectionException { String[] required = getRequiredParameters(parameters); RequestUtil.validateParameters(parameters, required); String res = HttpClientHelper.sendRequest( RequestUtil.buildPaymentRequest(parameters, transactionType), RequestMethod.POST, socketTimeOut); PaymentResponse response = PaymentResponse.fromXml(res); return response.getTransactionResponse(); } /** * From parameters map to transaction. * * @param parameters the parameters * @param transactionType the transaction type * @return the transaction * @throws PayUException the pay u exception * @throws InvalidParametersException the invalid parameters exception * @throws ConnectionException the connection exception */
public static Transaction fromParametersMapToTransaction(Map<String, String> parameters, TransactionType transactionType) throws PayUException, InvalidParametersException, ConnectionException {
2
w9jds/MarketBot
app/src/main/java/com/w9jds/marketbot/classes/components/StorageComponent.java
[ "public abstract class GroupsLoader extends BaseDataManager {\n\n @Inject CrestService publicCrest;\n @Inject SharedPreferences sharedPreferences;\n @Inject boolean isFirstRun;\n\n private Context context;\n private boolean updateFailed = false;\n\n public abstract void onProgressUpdate(int page, int totalPages, @Nullable String message);\n public abstract void onDataLoaded(List<? extends MarketItemBase> data);\n\n public GroupsLoader(Context context) {\n super(context);\n\n MarketBot.createNewStorageSession().inject(this);\n this.context = context;\n }\n\n private void incrementUpdatingCount(int count) {\n updatingCount.set(count);\n }\n\n private void decrementUpdatingCount() {\n updatingCount.decrementAndGet();\n }\n\n private int updatingCount() {\n return updatingCount.intValue();\n }\n\n private void updateStarted() {\n dispatchUpdateStartedCallbacks();\n }\n\n\n @Override\n protected void updateFinished() {\n super.updateFinished();\n\n if (!updateFailed && isFirstRun && updatingCount() == 0) {\n sharedPreferences.edit().putBoolean(\"isFirstRun\", false).apply();\n loadMarketGroups(null);\n }\n }\n\n private void dispatchUpdateStartedCallbacks() {\n if (updatingCount.intValue() == 0) {\n if (updatingCallbacks != null && !updatingCallbacks.isEmpty()) {\n for (DataUpdatingCallbacks updatingCallback : updatingCallbacks) {\n updatingCallback.dataUpdatingStarted();\n }\n }\n }\n }\n\n public void update() {\n updateStarted();\n incrementUpdatingCount(1);\n\n if (isConnected()) {\n publicCrest.getServer()\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(error -> loadFailed(error.getMessage()))\n .doOnNext(serverInfoResponse -> {\n if (serverInfoResponse.isSuccessful() && serverInfoResponse.body() != null) {\n CrestServerStatus serverInfo = serverInfoResponse.body();\n String serverVersion = sharedPreferences.getString(\"serverVersion\", \"\");\n if (!serverInfo.getServerVersion().equals(serverVersion) || isFirstRun) {\n incrementUpdatingCount(3);\n sharedPreferences.edit()\n .putString(\"serverVersion\", serverInfo.getServerVersion())\n .apply();\n\n updateMarketGroups();\n updateMarketTypes();\n updateRegions();\n }\n else {\n decrementUpdatingCount();\n updateFinished();\n }\n }\n else {\n updateFailed = true;\n loadFailed(\"Failed to get the CREST server version\");\n updateFinished();\n }\n }).subscribe();\n\n }\n else {\n updateFailed = true;\n loadFailed(\"Invalid Internet Connection\");\n updateFinished();\n }\n }\n\n private void updateMarketGroups() {\n publicCrest.getMarketGroups()\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(error -> {\n updateFailed = true;\n loadFailed(\"Failed to update cached market groups.\");\n decrementUpdatingCount();\n updateFinished();\n })\n .doOnNext(crestResponse -> {\n if (crestResponse.isSuccessful() && crestResponse.body() != null) {\n CrestDictionary<CrestMarketGroup> marketGroups = crestResponse.body();\n\n MarketGroupEntry.addNewMarketGroups(marketGroups.getItems());\n decrementUpdatingCount();\n updateFinished();\n }\n else {\n updateFailed = true;\n loadFailed(\"Failed to update cached market groups.\");\n decrementUpdatingCount();\n updateFinished();\n }\n }).subscribe();\n }\n\n private List<CrestMarketType> getAllMarketTypes() {\n try {\n List<CrestMarketType> crestMarketTypes = new ArrayList<>();\n CrestDictionary<CrestMarketType> dictionary;\n int page = 0;\n\n do {\n page = page + 1;\n dictionary = publicCrest.getMarketTypes(page).execute().body();\n if (dictionary == null) {\n break;\n }\n\n crestMarketTypes.addAll(dictionary.getItems());\n onProgressUpdate(crestMarketTypes.size(), (int)dictionary.getTotalCount(), null);\n } while(dictionary.getPageNext() != null);\n\n return crestMarketTypes;\n }\n catch(Exception ex) {\n updateFailed = true;\n decrementUpdatingCount();\n updateFinished();\n\n return new ArrayList<>();\n }\n }\n\n private void updateMarketTypes() {\n BehaviorSubject<Map.Entry<Integer, Integer>> subject = BehaviorSubject.create();\n CompositeSubscription subscriptions = new CompositeSubscription();\n subscriptions.add(subject\n .observeOn(AndroidSchedulers.mainThread())\n .doOnNext(progress -> {\n onProgressUpdate(progress.getKey(), progress.getValue(), \"Storing items list...\");\n\n if (progress.getKey().equals(progress.getValue())) {\n subscriptions.unsubscribe();\n decrementUpdatingCount();\n updateFinished();\n }\n }).subscribe());\n\n\n Observable.defer(() -> Observable.just(getAllMarketTypes()))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnNext(orders -> MarketTypeEntry.addNewMarketTypes(orders, subject))\n .subscribe();\n }\n\n private void updateRegions() {\n publicCrest.getRegions()\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(error -> {\n updateFailed = true;\n loadFailed(\"Failed to update cached regions.\");\n decrementUpdatingCount();\n loadFinished();\n })\n .doOnNext(crestResponse -> {\n if (crestResponse.isSuccessful() && crestResponse.body() != null) {\n CrestDictionary<CrestItem> regions = crestResponse.body();\n\n RegionEntry.addRegions(regions.getItems());\n decrementUpdatingCount();\n updateFinished();\n }\n else {\n updateFailed = true;\n loadFailed(\"Failed to update cached regions.\");\n decrementUpdatingCount();\n updateFinished();\n }\n }).subscribe();\n }\n\n public void loadMarketGroups(Long parentId) {\n loadStarted();\n incrementLoadingCount();\n onDataLoaded(MarketGroupEntry.getMarketGroupsForParent(parentId));\n decrementLoadingCount();\n loadFinished();\n }\n\n public void loadMarketTypes(long groupId) {\n loadStarted();\n incrementLoadingCount();\n onDataLoaded(MarketTypeEntry.getMarketTypes(groupId));\n decrementLoadingCount();\n loadFinished();\n }\n\n public void searchMarketTypes(String queryString) {\n loadStarted();\n incrementLoadingCount();\n onDataLoaded(MarketTypeEntry.searchMarketTypes(queryString));\n decrementLoadingCount();\n loadFinished();\n }\n}", "public abstract class OrdersLoader extends BaseDataManager {\n\n @Inject CrestService publicCrest;\n @Inject SharedPreferences sharedPreferences;\n\n private Context context;\n\n public OrdersLoader(Context context) {\n super(context);\n\n MarketBot.createNewStorageSession().inject(this);\n this.context = context;\n }\n\n public abstract void onSellOrdersLoaded(List<MarketOrder> orders);\n public abstract void onBuyOrdersLoaded(List<MarketOrder> orders);\n public abstract void onMarginsLoaded(List<StationMargin> orders);\n public abstract void onHistoryLoaded(List<MarketHistory> historyEntries);\n\n public void loadMarketOrders(long regionId, Type type) {\n loadStarted();\n incrementLoadingCount(3);\n\n publicCrest.getMarketOrders(regionId, type.getHref())\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(exception -> Log.e(\"OrdersLoader\", exception.getCause().getMessage()))\n .doOnNext(crestResponse -> {\n if (crestResponse.isSuccessful() && crestResponse.body() != null) {\n List<CrestMarketOrder> orders = crestResponse.body().getItems();\n\n int size = orders.size();\n List<MarketOrder> marketOrders = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n marketOrders.add(CrestMapper.map(orders.get(i)));\n }\n\n buildSellOrders(marketOrders);\n buildBuyOrders(marketOrders);\n buildMargins(marketOrders);\n }\n })\n .subscribe();\n }\n\n private void buildSellOrders(List<MarketOrder> orders) {\n int size = orders.size();\n List<MarketOrder> sellOrders = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n MarketOrder order = orders.get(i);\n if (!order.isBuyOrder()) {\n sellOrders.add(order);\n }\n }\n\n onSellOrdersLoaded(sellOrders);\n decrementLoadingCount();\n loadFinished();\n }\n\n public void loadSellOrders(final long regionId, final Type type) {\n loadStarted();\n incrementLoadingCount();\n\n publicCrest.getMarketOrders(regionId, type.getHref(), \"sell\")\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(exception -> Log.e(\"OrdersLoader\", exception.getCause().getMessage()))\n .doOnNext(crestResponse -> {\n if (crestResponse.isSuccessful() && crestResponse.body() != null) {\n List<CrestMarketOrder> orders = crestResponse.body().getItems();\n\n int size = orders.size();\n List<MarketOrder> marketOrders = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n marketOrders.add(CrestMapper.map(orders.get(i)));\n }\n\n onSellOrdersLoaded(marketOrders);\n\n decrementLoadingCount();\n loadFinished();\n }\n })\n .subscribe();\n }\n\n private void buildBuyOrders(List<MarketOrder> orders) {\n int size = orders.size();\n List<MarketOrder> sellOrders = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n MarketOrder order = orders.get(i);\n if (order.isBuyOrder()) {\n sellOrders.add(order);\n }\n }\n\n onBuyOrdersLoaded(sellOrders);\n decrementLoadingCount();\n loadFinished();\n }\n\n public void loadBuyOrders(final long regionId, final Type type) {\n loadStarted();\n incrementLoadingCount();\n\n publicCrest.getMarketOrders(regionId, type.getHref(), \"buy\")\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(exception -> Log.e(\"OrdersLoader\", exception.getCause().getMessage()))\n .doOnNext(crestResponse -> {\n if (crestResponse.isSuccessful() && crestResponse.body() != null) {\n List<CrestMarketOrder> orders = crestResponse.body().getItems();\n\n int size = orders.size();\n List<MarketOrder> marketOrders = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n marketOrders.add(CrestMapper.map(orders.get(i)));\n }\n\n onBuyOrdersLoaded(marketOrders);\n\n decrementLoadingCount();\n loadFinished();\n }\n })\n .subscribe();\n }\n\n public void loadMarginOrders(final long regionId, final Type type){\n loadStarted();\n incrementLoadingCount();\n\n publicCrest.getMarketOrders(regionId, type.getHref())\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(exception -> Log.e(\"OrdersLoader\", exception.getCause().getMessage()))\n .doOnNext(crestResponse -> {\n if (crestResponse.isSuccessful() && crestResponse.body() != null) {\n List<CrestMarketOrder> orders = crestResponse.body().getItems();\n\n int size = orders.size();\n List<MarketOrder> marketOrders = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n marketOrders.add(CrestMapper.map(orders.get(i)));\n }\n\n buildMargins(marketOrders);\n }\n\n })\n .subscribe();\n }\n\n private void buildMargins(List<MarketOrder> orders) {\n ArrayMap<String, MarketOrder> buyMax = new ArrayMap<>();\n ArrayMap<String, MarketOrder> sellMax = new ArrayMap<>();\n int size = orders.size();\n\n for (int i = 0; i < size; i++) {\n MarketOrder order = orders.get(i);\n if (order.isBuyOrder()) {\n if (buyMax.containsKey(order.getLocation())) {\n if (buyMax.get(order.getLocation()).getPrice() > order.getPrice()) {\n continue;\n }\n }\n\n buyMax.put(order.getLocation(), order);\n }\n else {\n if (sellMax.containsKey(order.getLocation())) {\n if (sellMax.get(order.getLocation()).getPrice() > order.getPrice()) {\n continue;\n }\n }\n\n sellMax.put(order.getLocation(), order);\n }\n }\n\n size = sellMax.size();\n List<StationMargin> margins = new ArrayList<>(size > buyMax.size() ? size : buyMax.size());\n for (int i = 0; i < size; i++) {\n String key = sellMax.keyAt(i);\n if (buyMax.containsKey(key)) {\n MarketOrder buyOrder = buyMax.get(key);\n MarketOrder sellOrder = sellMax.get(key);\n\n margins.add(new StationMargin.Builder()\n .setMaxBuyPrice(buyOrder.getPrice())\n .setMaxSellPrice(sellOrder.getPrice())\n .setStation(key)\n .build());\n }\n }\n\n onMarginsLoaded(margins);\n decrementLoadingCount();\n loadFinished();\n }\n\n public void loadMarketHistory(final long regionId, final Type type) {\n Observable.defer(() -> Observable.just(getHistoryEntries(regionId, type)))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnNext(entries -> {\n int size = entries.size();\n List<MarketHistory> histories = new ArrayList<MarketHistory>(size);\n for (int i = 0; i < size; i++) {\n histories.add(CrestMapper.map(entries.get(i)));\n }\n\n onHistoryLoaded(histories);\n decrementLoadingCount();\n updateFinished();\n\n }).subscribe();\n }\n\n private List<CrestMarketHistory> getHistoryEntries(final long regionId, final Type type) {\n try {\n List<CrestMarketHistory> crestMarketTypes = new ArrayList<>();\n Response<CrestDictionary<CrestMarketHistory>> dictionary;\n\n dictionary = publicCrest.getMarketHistory(regionId, type.getHref()).execute();\n if (!dictionary.isSuccessful() || dictionary.body() == null) {\n return crestMarketTypes;\n }\n\n crestMarketTypes.addAll(dictionary.body().getItems());\n return crestMarketTypes;\n }\n catch(Exception ex) {\n loadFailed(\"Failed to retrieve items market history\");\n return new ArrayList<>();\n }\n }\n\n}", "public abstract class TypeLoader extends BaseDataManager {\n\n @Inject CrestService publicCrest;\n @Inject SharedPreferences sharedPreferences;\n\n private Context context;\n\n public TypeLoader(Context context) {\n super(context);\n\n MarketBot.createNewStorageSession().inject(this);\n this.context = context;\n }\n\n public abstract void onTypeInfoLoaded(TypeInfo info);\n public abstract void onRegionsLoaded(List<Region> regions);\n\n\n public void loadRegions(boolean includesWormholes) {\n onRegionsLoaded(RegionEntry.getAllRegions(includesWormholes));\n }\n\n public void loadTypeInfo(long typeId) {\n loadStarted();\n incrementLoadingCount();\n\n Observable.defer(() -> {\n try {\n return Observable.just(getTypeInfo(typeId));\n }\n catch(Exception ex) {\n return Observable.error(ex);\n }\n })\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .doOnError(error -> {\n decrementLoadingCount();\n loadFinished();\n loadFailed(error.getMessage());\n })\n .doOnNext(crestType -> {\n onTypeInfoLoaded(CrestMapper.map(crestType));\n decrementLoadingCount();\n loadFinished();\n }).subscribe();\n }\n\n private CrestType getTypeInfo(long typeId) throws Exception {\n Response<CrestType> response = publicCrest.getTypeInfo(typeId).execute();\n if (!response.isSuccessful() || response.body() == null) {\n throw new Exception(\"Unable to load type info\");\n }\n\n return response.body();\n }\n\n}", "public class InfoActivity extends AppCompatActivity {\n\n @Bind(R.id.rix_icon) ImageView rixxIcon;\n @Bind(R.id.me_icon) ImageView jeremyIcon;\n @Bind(R.id.crest_version) TextView crestVersionView;\n @Bind(R.id.application_version) TextView appVersionView;\n @Bind(R.id.base_view) CoordinatorLayout baseView;\n @Bind(R.id.toolbar) Toolbar toolbar;\n\n @Inject String crestVersion;\n\n private ActionBar actionBar;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_info);\n ButterKnife.bind(this);\n\n MarketBot.createNewStorageSession().inject(this);\n\n setSupportActionBar(toolbar);\n actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n actionBar.setDisplayShowHomeEnabled(true);\n actionBar.setTitle(\"MarketBot Info\");\n }\n\n crestVersionView.setText(crestVersion);\n\n try {\n PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);\n String version = pInfo.versionName;\n\n appVersionView.setText(version);\n }\n catch (Exception ex) {\n Snackbar.make(baseView, \"Error getting application version\", Snackbar.LENGTH_LONG)\n .show();\n }\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n\n Glide.with(this)\n .load(\"https://pbs.twimg.com/profile_images/708449861096460289/amHbjwSk.jpg\")\n .into(rixxIcon);\n\n Glide.with(this)\n .load(\"https://pbs.twimg.com/profile_images/535955002460622849/qvLXDlKY.png\")\n .into(jeremyIcon);\n }\n\n @OnClick(R.id.rixx_container)\n void onRixxClick() {\n openTwitterFeed(\"RixxJavix\");\n }\n\n @OnClick(R.id.jeremy_container)\n void onJeremyClick() {\n openTwitterFeed(\"xboxmusicn3rd\");\n }\n\n private void openTwitterFeed(String username) {\n Intent intent = null;\n try {\n this.getPackageManager().getPackageInfo(\"com.twitter.android\", 0);\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"twitter://user?screen_name=\" + username));\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n } catch (Exception e) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https://twitter.com/\" + username));\n }\n this.startActivity(intent);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n onBackPressed();\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n}", "public class ItemActivity extends AppCompatActivity implements DataLoadingSubject.DataLoadingCallbacks,\n DataLoadingSubject.DataUpdatingCallbacks {\n\n @Inject SharedPreferences sharedPreferences;\n\n @Bind(R.id.item_content) CoordinatorLayout baseView;\n @Bind(R.id.main_toolbar) Toolbar toolbar;\n @Bind(R.id.region_spinner) Spinner regionSpinner;\n @Bind(R.id.content_pager) ViewPager pager;\n @Bind(R.id.sliding_tabs) TabLayout tabLayout;\n\n private ProgressDialog progressDialog;\n private TypeLoader loader;\n private GroupsLoader updateLoader;\n private OrdersLoader ordersLoader;\n private Type currentType;\n private RegionAdapter regionAdapter;\n private BehaviorSubject<Map.Entry<Integer, List<?>>> subject;\n\n private long regionId;\n private boolean updateRun = false;\n private long typeIdExtra;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_market_item);\n ButterKnife.bind(this);\n\n MarketBot.createNewStorageSession().inject(this);\n subject = BehaviorSubject.create();\n regionId = sharedPreferences.getLong(\"regionId\", 10000002);\n\n setSupportActionBar(toolbar);\n ActionBar actionBar = getSupportActionBar();\n\n if (actionBar != null) {\n actionBar.setDisplayShowTitleEnabled(false);\n actionBar.setDisplayShowHomeEnabled(true);\n actionBar.setDisplayHomeAsUpEnabled(true);\n actionBar.setHomeButtonEnabled(true);\n }\n\n Intent intent = getIntent();\n typeIdExtra = intent.getLongExtra(\"typeId\", -1);\n regionId = intent.getLongExtra(\"regionId\", regionId);\n\n regionAdapter = new RegionAdapter(this);\n loader = new TypeLoader(this) {\n @Override\n public void onTypeInfoLoaded(TypeInfo info) {\n\n }\n\n @Override\n public void onRegionsLoaded(List<Region> regions) {\n regionAdapter.addAllItems(regions);\n regionSpinner.setSelection(regionAdapter.getPositionfromId((int)regionId), true);\n regionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {\n @Override\n public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {\n Region region = (Region) regionAdapter.getItem(position);\n regionId = region.getId();\n sharedPreferences.edit().putLong(\"regionId\", region.getId()).apply();\n\n ordersLoader.loadMarketOrders(regionId, currentType);\n ordersLoader.loadMarketHistory(regionId, currentType);\n }\n\n @Override\n public void onNothingSelected(AdapterView<?> parent) {\n // Never Happens\n }\n });\n }\n };\n\n ordersLoader = new OrdersLoader(this) {\n @Override\n public void onSellOrdersLoaded(List<MarketOrder> orders) {\n subject.onNext(new AbstractMap.SimpleEntry<>(1, orders));\n }\n\n @Override\n public void onBuyOrdersLoaded(List<MarketOrder> orders) {\n subject.onNext(new AbstractMap.SimpleEntry<>(2, orders));\n }\n\n @Override\n public void onMarginsLoaded(List<StationMargin> orders) {\n subject.onNext(new AbstractMap.SimpleEntry<>(3, orders));\n }\n\n @Override\n public void onHistoryLoaded(List<MarketHistory> historyEntries) {\n subject.onNext(new AbstractMap.SimpleEntry<>(4, historyEntries));\n }\n };\n\n updateLoader = new GroupsLoader(this) {\n @Override\n public void onProgressUpdate(int page, int totalPages, String message) {\n if (progressDialog.isIndeterminate()) {\n progressDialog.setOnDismissListener(dialog -> updateProgressDialog(page, totalPages, message));\n progressDialog.dismiss();\n }\n\n updateProgressDialog(page, totalPages, message);\n }\n\n @Override\n public void onDataLoaded(List<? extends MarketItemBase> data) {\n\n }\n };\n\n loader.registerLoadingCallback(this);\n updateLoader.registerUpdatingCallback(this);\n regionSpinner.setAdapter(regionAdapter);\n\n checkExtras();\n }\n\n private void updateProgressDialog(int page, int max, @Nullable String message) {\n progressDialog.setMax(max);\n progressDialog.setProgress(page);\n\n if (message != null) {\n progressDialog.setMessage(message);\n }\n\n if (!progressDialog.isShowing()) {\n progressDialog = new ProgressDialog(this);\n progressDialog.setIndeterminate(false);\n progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n progressDialog.setMessage(\"Retrieving updated items list...\");\n progressDialog.setCanceledOnTouchOutside(false);\n progressDialog.setCancelable(false);\n progressDialog.show();\n }\n }\n\n private void checkExtras() {\n if (!sharedPreferences.getBoolean(\"isFirstRun\", true)) {\n if (typeIdExtra != -1) {\n currentType = MarketTypeEntry.getType(typeIdExtra);\n } else {\n currentType = getIntent().getParcelableExtra(\"currentType\");\n }\n\n loadTypeData();\n }\n else if (!updateRun) {\n updateLoader.update();\n }\n else {\n Snackbar.make(baseView, \"Update failed, Please try again.\", Snackbar.LENGTH_LONG).show();\n }\n }\n\n private void loadTypeData() {\n loader.loadRegions(false);\n\n TypeTabAdapter tabAdapter = new TypeTabAdapter(getSupportFragmentManager(),\n this, currentType, subject);\n pager.setOffscreenPageLimit(4);\n pager.setAdapter(tabAdapter);\n tabLayout.setupWithViewPager(pager);\n\n ordersLoader.loadMarketOrders(regionId, currentType);\n ordersLoader.loadMarketHistory(regionId, currentType);\n }\n\n @Override\n public boolean onNavigateUp() {\n finishAfterTransition();\n return true;\n }\n\n @Override\n public void dataUpdatingStarted() {\n progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Updating Market Cache...\");\n progressDialog.setCancelable(false);\n progressDialog.setIndeterminate(true);\n progressDialog.setCanceledOnTouchOutside(false);\n progressDialog.show();\n }\n\n @Override\n public void dataUpdatingFinished() {\n progressDialog.dismiss();\n updateRun = true;\n checkExtras();\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n onBackPressed();\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n\n @Override\n public void dataStartedLoading() {\n\n }\n\n @Override\n public void dataFinishedLoading() {\n\n }\n\n @Override\n public void dataFailedLoading(String errorMessage) {\n\n }\n}", "@Module\npublic class StorageModule {\n\n public StorageModule() {\n\n }\n\n @Provides\n @StorageScope\n String provideServerVersion(SharedPreferences sharedPreferences) {\n return sharedPreferences.getString(\"serverVersion\", \"\");\n }\n\n @Provides\n @StorageScope\n boolean provideFirstRun(SharedPreferences sharedPreferences) {\n return sharedPreferences.getBoolean(\"isFirstRun\", true);\n }\n\n @Provides\n @StorageScope\n long provideRegionId(SharedPreferences sharedPreferences) {\n return sharedPreferences.getLong(\"regionId\", 10000002);\n }\n\n}" ]
import com.w9jds.marketbot.data.loader.GroupsLoader; import com.w9jds.marketbot.data.loader.OrdersLoader; import com.w9jds.marketbot.data.loader.TypeLoader; import com.w9jds.marketbot.ui.InfoActivity; import com.w9jds.marketbot.ui.ItemActivity; import com.w9jds.marketbot.classes.StorageScope; import com.w9jds.marketbot.classes.modules.StorageModule; import dagger.Component;
package com.w9jds.marketbot.classes.components; @StorageScope @Component(dependencies = BaseComponent.class, modules = StorageModule.class) public interface StorageComponent { void inject(GroupsLoader groupsLoader); void inject(OrdersLoader tabsLoader);
void inject(TypeLoader typeLoader);
2
zozoh/zdoc
java/src/org/nutz/zdoc/am/ZDocParallelAm.java
[ "public abstract class AmStack<T> {\n\n /**\n * 消费字符\n * \n * @param c\n * 字符\n * @return 返回 false 表示不能消费了\n */\n public AmStatus eat(char c) {\n if (isQuit(c))\n return AmStatus.DONE;\n\n Am<T> am = peekAm();\n AmStatus st = am.eat(this, c);\n if (st == AmStatus.CONTINUE) {\n return st;\n }\n if (st == AmStatus.DROP) {\n return st;\n }\n // 如果栈顶自动机完成了,那么调用它的 done\n // 是否能继续消费字符,取决于操作栈里是否还有自动机\n if (st == AmStatus.DONE) {\n done();\n return i_am >= 0 ? AmStatus.CONTINUE : AmStatus.DONE;\n }\n if (st == AmStatus.DONE_BACK) {\n done();\n if (i_am >= 0)\n return eat(c);\n return st;\n }\n throw Lang.impossible();\n }\n\n /**\n * 调用栈顶自动机的 done\n */\n public void done() {\n Am<T> am = peekAm();\n am.done(this);\n }\n\n @SuppressWarnings(\"unchecked\")\n public T close() {\n // 按顺序,从栈头到尾依次调用自动机的 done\n Am<T>[] theAms = new Am[i_am + 1];\n for (int i = 0; i < theAms.length; i++) {\n theAms[i] = ams[i_am - i];\n }\n for (Am<T> am : theAms)\n am.done(this);\n\n // 最后从头到尾,依次调用对象的融合\n while (i_obj > 0) {\n T o = popObj();\n this.mergeHead(o);\n }\n\n // 弹出并返回根对象\n return popObj();\n }\n\n // 平行自动机会在这里记录自己所接受的字符,以便没有可选自动机时用作默认处理\n public LinkedCharArray raw;\n\n // 给自动机用的解析临时堆栈\n public LinkedCharArray buffer;\n\n protected T[] objs;\n protected Am<T>[] ams;\n private char[] qcs;\n private int[] sis;\n\n // 指向当前,初始为 -1\n private int i_obj;\n private int i_am;\n private int i_qc;\n private int i_si;\n\n // 堆栈项目最大深度\n protected int maxDepth;\n\n public String toString() {\n return toString(0);\n }\n\n public String toString(int indent) {\n StringBuilder sb = new StringBuilder();\n String inds = Strings.dup(\" \", indent);\n\n // raw\n sb.append(inds).append(\"Raw: |\");\n for (int i = 0; i < raw.size(); i++)\n sb.append(raw.get(i));\n sb.append(\"|< \").append('\\n');\n // 字符串缓冲\n sb.append(inds).append(\"Buf: |\");\n for (int i = 0; i < buffer.size(); i++)\n sb.append(buffer.get(i));\n sb.append(\"|< \").append('\\n');\n\n // 对象\n sb.append(inds).append(\"Obj:\");\n for (int i = i_obj; i >= 0; i--) {\n sb.append('[');\n sb.append(objBrief(objs[i]));\n sb.append(']');\n }\n sb.append(\" < \").append('\\n');\n\n // 操作栈\n sb.append(inds).append(\"Ams:\");\n for (int i = i_am; i >= 0; i--) {\n sb.append('[');\n sb.append(ams[i].name());\n sb.append(']');\n }\n sb.append(\" < \").append('\\n');\n\n // QC\n sb.append(inds).append(\" Qc:\");\n for (int i = i_qc; i >= 0; i--) {\n char c = qcs[i];\n if (c == 0) {\n sb.append(\" 0 \");\n } else {\n sb.append('\\'').append(c).append('\\'');\n }\n }\n sb.append(\" < \").append('\\n');\n\n // SI\n sb.append(inds).append(\" Si:\");\n for (int i = i_si; i >= 0; i--) {\n if (sis[i] >= 0) {\n sb.append(\" \").append(sis[i]);\n } else {\n sb.append(\" \").append(sis[i]);\n }\n }\n sb.append(\" < \").append('\\n');\n\n // 子堆栈\n indent++;\n if (this.hasCandidates()) {\n for (AmStack<T> stack : candidates)\n sb.append(stack.toString(indent));\n }\n\n return sb.toString();\n }\n\n public List<AmStack<T>> candidates;\n\n public boolean hasCandidates() {\n return null != candidates && !candidates.isEmpty();\n }\n\n /**\n * @return 是否有一个候选堆栈胜出\n */\n public boolean hasWinner() {\n return null != candidates && candidates.size() == 1;\n }\n\n public boolean hasSi() {\n return i_si >= 0;\n }\n\n public boolean hasQc() {\n return i_qc >= 0;\n }\n\n public void addCandidate(AmStack<T> stack) {\n if (null == candidates)\n candidates = new LinkedList<AmStack<T>>();\n candidates.add(stack);\n }\n\n public AmStack(int maxDepth) {\n this.maxDepth = maxDepth;\n this.raw = new LinkedCharArray();\n this.buffer = new LinkedCharArray();\n this.qcs = new char[maxDepth];\n this.sis = new int[maxDepth];\n this.i_obj = -1;\n this.i_am = -1;\n this.i_qc = -1;\n this.i_si = -1;\n\n }\n\n protected abstract void merge(T a, T b);\n\n protected abstract AmStack<T> born();\n\n public abstract T bornObj();\n\n protected abstract String objBrief(T o);\n\n public void mergeHead(T o) {\n if (null != o) {\n if (hasObj()) {\n T head = peekObj();\n if (null != head) {\n merge(head, o);\n }\n } else {\n pushObj(o);\n }\n }\n }\n\n public AmStack<T> pushSi(int n) {\n sis[++i_si] = n;\n return this;\n }\n\n public int popSi() {\n int n = sis[i_si];\n sis[i_si] = 0;\n i_si--;\n return n;\n }\n\n public int si() {\n return sis[i_si];\n }\n\n public void setSi(int n) {\n sis[i_si] = n;\n }\n\n public int si_size() {\n return i_si + 1;\n }\n\n public AmStack<T> pushQc(char c) {\n qcs[++i_qc] = c;\n return this;\n }\n\n public char popQc() {\n char c = qcs[i_qc];\n qcs[i_qc] = 0;\n i_qc--;\n return c;\n }\n\n public char qc() {\n return qcs[i_qc];\n }\n\n public boolean isQuit(char c) {\n if (i_qc >= 0)\n return qcs[i_qc] == c;\n return false;\n }\n\n public int qc_size() {\n return i_qc + 1;\n }\n\n public AmStack<T> pushObj(T obj) {\n objs[++i_obj] = obj;\n return this;\n }\n\n public T popObj() {\n T obj = objs[i_obj];\n objs[i_obj] = null;\n i_obj--;\n return obj;\n }\n\n public boolean hasObj() {\n return i_obj >= 0;\n }\n\n public int getObjSize() {\n return i_obj + 1;\n }\n\n public T peekObj() {\n return objs[i_obj];\n }\n\n public AmStack<T> pushAm(Am<T> am) {\n ams[++i_am] = am;\n return this;\n }\n\n public Am<T> popAm() {\n Am<T> am = ams[i_am];\n ams[i_am] = null;\n i_am--;\n return am;\n }\n\n public Am<T> peekAm() {\n return ams[i_am];\n }\n}", "public enum AmStatus {\n /**\n * 丢弃当前堆栈\n */\n DROP,\n /**\n * 继续,读取下一个字符,执行栈顶自动机的 run 方法\n */\n CONTINUE,\n /**\n * 将弹出操作栈顶自动机,并执行它的 done 方法\n */\n DONE,\n /**\n * 执行 DONE 操作,并重新进入下一个可能的自动机\n */\n DONE_BACK\n}", "public abstract class ParallelAm<T> extends ComposAm<T> {\n\n /**\n * 是否为受限的平行自动机\n * <ul>\n * <li>如果为 true,必须有一个子机接受了字符才可进入\n * <li>否则,任何字符都是可入的,将会依靠 as.raw 字段继续消费字符\n * </ul>\n */\n private boolean limited;\n\n @Override\n public AmStatus enter(AmStack<T> as, char c) {\n // 如果用退出字符进入,直接返回完成\n if (c == theChar) {\n // as.pushAm(this).pushQc(theChar);\n return AmStatus.DONE;\n }\n\n // 尝试选择几个候选堆栈\n selectCandidates(as, c);\n\n // 选择完了候选堆栈,如果有,那么就表示可以继续消费字符\n if (as.hasCandidates()) {\n // 处理之前积累下来的字符\n whenNoCandidate(as);\n\n // 那么就会将自身压入母堆栈,同时也要在母堆栈标识退出字符\n // []\n // [] ...\n // [+]... # 仅仅在当前堆栈压入自身\n // ']'... # 压入自己的退出字符\n as.pushQc(theChar).pushAm(this);\n as.raw.push(c);\n return AmStatus.CONTINUE;\n }\n // 没有退出字符的平行自动机,即使没有候选堆栈,也可以接受任何字符\n // 待遇到了生成候选堆栈的字符,之前接受的字符(as.raw)则会被子类虚函数处理\n if (!limited) {\n as.pushQc(theChar).pushAm(this);\n as.raw.push(c);\n return AmStatus.CONTINUE;\n }\n // 否则就表示本自动机遇到意外字符,必须 drop\n return AmStatus.DROP;\n }\n\n private void selectCandidates(AmStack<T> as, char c) {\n // 构建新堆栈:\n // [C]\n // [] .# 不要准备对象\n // [@] # 表示有子自动机进入了\n // ']' # 自己的退出字符\n AmStack<T> stack = as.born().pushQc(theChar);\n\n //\n // 如果超过一个自动机进入了,那么将堆栈变成\n //\n // {候选堆栈A} \\\n // {候选堆栈B} -?- {并联自动机所在的堆栈}\n // {候选堆栈C} /\n // ...\n for (Am<T> am : ams) {\n if (AmStatus.DROP != am.enter(stack, c)) {\n as.addCandidate(stack);\n stack = as.born().pushQc(theChar);\n }\n }\n }\n\n @Override\n public AmStatus eat(AmStack<T> as, char c) {\n // 如果没有候选堆栈,则本自动机将执行选择一个候选堆栈\n if (!as.hasCandidates()) {\n if (theChar == c) {\n return AmStatus.DONE;\n }\n\n // 如果是转移字符,不需要选择候选堆栈\n if (as.raw.last() == '\\\\') {\n as.raw.push(c);\n return AmStatus.CONTINUE;\n }\n\n // 试图看看有木有子机可以进入 ...\n this.selectCandidates(as, c);\n\n // 如果有候选就返回继续\n if (as.hasCandidates()) {\n // 处理之前积累下来的字符\n whenNoCandidate(as);\n\n // 继续处理\n as.raw.push(c);\n return AmStatus.CONTINUE;\n }\n\n if (!limited) {\n as.raw.push(c);\n return AmStatus.CONTINUE;\n }\n\n return AmStatus.DROP;\n }\n\n // 记录自己接受的字符\n as.raw.push(c);\n\n // 依次处理所有的候选堆栈\n T o;\n List<AmStack<T>> dels = new ArrayList<AmStack<T>>(as.candidates.size());\n for (AmStack<T> stack : as.candidates) {\n AmStatus st = stack.eat(c);\n switch (st) {\n case DROP:\n dels.add(stack);\n break;\n case CONTINUE:\n break;\n case DONE:\n o = stack.close();\n as.mergeHead(o);\n as.candidates.clear();\n as.raw.clear();\n return st;\n case DONE_BACK:\n o = stack.close();\n as.mergeHead(o);\n as.candidates.clear();\n as.raw.clear();\n // 判断是不是退出字符\n if (theChar == c) {\n return AmStatus.DONE;\n }\n // 选择候选堆栈\n this.selectCandidates(as, c);\n\n // 如果有候选就返回继续\n if (as.hasCandidates())\n return AmStatus.CONTINUE;\n\n return AmStatus.DROP;\n }\n }\n\n // 清除需要删除的候选堆栈\n as.candidates.removeAll(dels);\n\n // 还有候选的话,就继续\n if (as.hasCandidates())\n return AmStatus.CONTINUE;\n\n return whenNoCandidate(as);\n }\n\n abstract protected AmStatus whenNoCandidate(AmStack<T> as);\n\n @Override\n public void done(AmStack<T> as) {\n // 如果没有候选堆栈,那么就什么也不做\n // 如果有多个候选堆栈,并联自动机会首先调用候选A的栈顶自动机的 done\n //\n // {候选堆栈A}.close() => T\n // {self}.mergeHead(T)\n // {self}.pushQc({候选堆栈A}.popQc())\n //\n // 并将其压入自己所在堆栈,否则,就会调用自己堆栈栈顶自动机的 done,\n // 让自己的的堆栈状态为:\n // [] # 字符缓冲\n // [] ... # 这个是自己的对象\n // [+] ... # 头部就只有自己\n // ']' ... # 自己的退出字符在顶部\n if (as.hasWinner()) {\n AmStack<T> stack = as.candidates.get(0);\n T o = stack.close();\n as.mergeHead(o);\n as.candidates.clear();\n\n // 执行堆栈的真正弹出\n // []\n // [] ... # 将 T 组合到之前的对象中\n // [] ... # 清除了自动机\n // ...... # 清除了退出字符\n as.popAm();\n }\n // 没有候选的话 ...\n else {\n whenNoCandidate(as);\n }\n\n }\n\n}", "public class ZDocEle {\n\n private ZDocNode myNode;\n\n private ZDocEleType type;\n\n private String text;\n\n private ZDocAttrs attrs;\n\n /**\n * 给 HTML 解析器专用的属性\n */\n private String tagName;\n\n private ZDocEle parent;\n\n private List<ZDocEle> children;\n\n public String toString() {\n return toString(0);\n }\n\n public String toBrief() {\n return String.format(\"{%s'%s'[%s](%s)|%d}\",\n type,\n Strings.sNull(text(), \"\"),\n Strings.sNull(href(), \"\"),\n Strings.sNull(src(), \"\"),\n children.size());\n }\n\n public String toString(int indent) {\n StringBuilder sb = new StringBuilder();\n String inds = Strings.dup(\" \", indent);\n sb.append(inds);\n sb.append(toBrief());\n indent++;\n for (ZDocEle child : children) {\n sb.append('\\n').append(child.toString(indent));\n }\n return sb.toString();\n }\n\n public ZDocEle() {\n this.type = ZDocEleType.NEW;\n this.attrs = new ZDocAttrs();\n this.tagName = \"\";\n // this.children = new ArrayList<ZDocEle>(5);\n this.children = new LinkedList<ZDocEle>();\n }\n\n public ZDocNode myNode() {\n return myNode;\n }\n\n public ZDocEle myNode(ZDocNode myNode) {\n this.myNode = myNode;\n return this;\n }\n\n public ZDocEleType type() {\n return type;\n }\n\n public ZDocEle type(ZDocEleType type) {\n this.type = type;\n return this;\n }\n\n public boolean is(ZDocEleType type) {\n return this.type == type;\n }\n\n /**\n * @return 本元素是否仅仅是一组元素的包裹。<br>\n * 实际上,如果自己没有任何属性,并且文字为空,那么就是了\n */\n public boolean isWrapper() {\n return null == text && (null == attrs || attrs.isEmpty());\n }\n\n /**\n * 尽力减低本身树的层级\n * \n * @return 自身\n */\n public ZDocEle normalize() {\n // 确保自己的类型有意义\n if (ZDocEleType.NEW == this.type) {\n this.type = hasAttr(\"src\") ? ZDocEleType.IMG : ZDocEleType.INLINE;\n }\n // 向下与自己的唯一 child 合并\n if (children.size() == 1) {\n ZDocEle child = children.remove(0);\n child.normalize();\n margeAttrs(child);\n if (ZDocEleType.NEW != child.type)\n this.type = child.type;\n this.text = Strings.sBlank(child.text(), this.text);\n this.children().addAll(child.children);\n }\n // 整理自己所有的 child\n else if (!children.isEmpty()) {\n for (ZDocEle child : children) {\n child.normalize();\n }\n }\n return this;\n }\n\n public ZDocEle margeAttrs(ZDocEle ele) {\n this.attrs.putAll(ele.attrs);\n return this;\n }\n\n public Object attr(String name) {\n return attrs.get(name);\n }\n\n public String attrString(String name) {\n return attrs.getString(name);\n }\n\n public int attrInt(String name) {\n return attrs.getInt(name);\n }\n\n public <T> T attrAs(Class<T> type, String name) {\n return attrs.getAs(type, name);\n }\n\n public boolean hasAttr(String name) {\n return attrs.has(name);\n }\n\n public boolean hasAttrAs(String name, String value) {\n return hasAttrAs(name, value, true);\n }\n\n public boolean hasAttrAs(String name, String value, boolean ignoreCase) {\n if (null == value)\n return !hasAttr(name);\n String v = attrString(name);\n if (null == v)\n return false;\n if (ignoreCase)\n return v.equalsIgnoreCase(value);\n return v.equals(value);\n }\n\n public ZDocEle attr(String name, Object value) {\n attrs.set(name, value);\n return this;\n }\n\n public String attrsAsJson() {\n return Json.toJson(attrs.getInnerMap(), JsonFormat.compact());\n }\n\n public ZLinkInfo linkInfo(String attrName) {\n String key = attrString(attrName);\n if (null != key && key.startsWith(\"$\"))\n return myNode.root().links().get(key.substring(1));\n return null;\n }\n\n public String linkInfoString(String attrName) {\n String key = attrString(attrName);\n if (null != key && key.startsWith(\"$\")) {\n ZLinkInfo link = myNode.root().links().get(key.substring(1));\n return null == link ? key : link.link();\n }\n return key;\n }\n\n public String href() {\n return attrString(\"href\");\n }\n\n public ZDocEle href(String href) {\n return attr(\"href\", href);\n }\n\n public String src() {\n return attrString(\"src\");\n }\n\n public ZDocEle src(String src) {\n return attr(\"src\", src);\n }\n\n public String title() {\n return attrString(\"title\");\n }\n\n public ZDocEle title(String title) {\n return attr(\"title\", title);\n }\n\n public int width() {\n return attrInt(\"width\");\n }\n\n public ZDocEle width(int width) {\n return attr(\"width\", width);\n }\n\n public int height() {\n return attrInt(\"height\");\n }\n\n public ZDocEle height(int height) {\n return attr(\"height\", height);\n }\n\n public String text() {\n return text;\n }\n\n public ZDocEle text(String text) {\n this.text = text;\n return this;\n }\n\n public CssRule style() {\n CssRule style = this.attrAs(CssRule.class, \"style\");\n if (null == style) {\n style = new CssRule();\n attr(\"style\", style);\n }\n return style;\n }\n\n public ZDocEle style(String name, String value) {\n style().set(name, value);\n return this;\n }\n\n public String style(String name) {\n return style().getString(name);\n }\n\n public boolean hasStyle(String name) {\n return style().has(name);\n }\n\n public boolean hasStyleAs(String name, String value) {\n return hasStyleAs(name, value, true);\n }\n\n public boolean hasStyleAs(String name, String value, boolean ignoreCase) {\n if (null == value)\n return !hasStyle(name);\n String v = style(name);\n if (null == v)\n return false;\n if (ignoreCase)\n return v.equalsIgnoreCase(value);\n return v.equals(value);\n }\n\n public ZDocEle parent() {\n return parent;\n }\n\n public boolean isTop() {\n return null == parent;\n }\n\n public ZDocEle parent(ZDocEle p) {\n parent = p;\n if (null != parent) {\n parent.children.add(this);\n }\n return this;\n }\n\n public List<ZDocEle> children() {\n return this.children;\n }\n\n public String tagName() {\n return tagName;\n }\n\n public ZDocEle tagName(String tagName) {\n this.tagName = tagName.toUpperCase();\n return this;\n }\n\n /**\n * 根据一个子节点下标路径获取某个子孙节点 <br>\n * 比如:\n * \n * <pre>\n * tag(1,0) 得到当前节点第二个子节点的第一个子节点\n * tag() 得到当前节点\n * </pre>\n * \n * @param iPaths\n * 子节点的 index\n * @return 某子孙节点,null 表示不存在\n */\n public ZDocEle ele(int... iPaths) {\n ZDocEle tag = this;\n if (null != iPaths && iPaths.length > 0)\n try {\n for (int i = 0; i < iPaths.length; i++) {\n tag = tag.children().get(iPaths[i]);\n }\n }\n catch (Exception e) {\n return null;\n }\n return tag;\n }\n}", "public enum ZDocEleType {\n\n /**\n * 新元素\n */\n NEW,\n /**\n * 普通元素\n */\n INLINE,\n /**\n * 用反引号扩起来的元素\n */\n QUOTE,\n /**\n * 图片\n */\n IMG,\n /**\n * 段内换行\n */\n BR,\n /**\n * 标注\n */\n SUP,\n /**\n * 脚注\n */\n SUB\n\n}" ]
import org.nutz.am.AmStack; import org.nutz.am.AmStatus; import org.nutz.am.ParallelAm; import org.nutz.zdoc.ZDocEle; import org.nutz.zdoc.ZDocEleType;
package org.nutz.zdoc.am; public class ZDocParallelAm extends ParallelAm<ZDocEle> { @Override protected AmStatus whenNoCandidate(AmStack<ZDocEle> as) { if (!as.raw.isEmpty()) {
ZDocEle o = new ZDocEle().type(ZDocEleType.INLINE);
4
hanks-zyh/FlyWoo
app/src/main/java/com/zjk/wifiproject/socket/tcp/TcpService.java
[ "public class BaseApplication extends Application {\n\n public static boolean isDebugmode = true;\n private boolean isPrintLog = true;\n\n /** 静音、震动默认开关 **/\n private static boolean isSlient = false;\n private static boolean isVIBRATE = true;\n\n /** 新消息提醒 **/\n private static int notiSoundPoolID;\n private static SoundPool notiMediaplayer;\n private static Vibrator notiVibrator;\n\n /** 缓存 **/\n private Map<String, SoftReference<Bitmap>> mAvatarCache;\n\n public static HashMap<String, FileState> sendFileStates;\n public static HashMap<String, FileState> recieveFileStates;\n\n /** 本地图像、缩略图、声音、文件存储路径 **/\n public static String IMAG_PATH;\n public static String THUMBNAIL_PATH;\n public static String VOICE_PATH;\n public static String VEDIO_PATH;\n public static String APK_PATH;\n public static String MUSIC_PATH;\n public static String FILE_PATH;\n public static String SAVE_PATH;\n public static String CAMERA_IMAGE_PATH;\n\n /** mEmoticons 表情 **/\n public static Map<String, Integer> mEmoticonsId;\n public static List<String> mEmoticons;\n public static List<String> mEmoticons_Zem;\n\n\n private static BaseApplication instance;\n\n private Bus bus;\n\n\n\n private static boolean isClient = true;\n\n /**\n * <p>\n * 获取BaseApplication实例\n * <p>\n * 单例模式,返回唯一实例\n * \n * @return instance\n */\n public static BaseApplication getInstance() {\n return instance;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n if (instance == null) {\n instance = this;\n }\n sendFileStates = new HashMap<String, FileState>();\n recieveFileStates = new HashMap<String, FileState>();\n mAvatarCache = new HashMap<String, SoftReference<Bitmap>>();\n // ActivitiesManager.init(getApplicationContext()); // 初始化活动管理器\n // L.setLogStatus(isPrintLog); // 设置是否显示日志\n\n //初始化Fresco库\n Fresco.initialize(this);\n\n initEmoticons();\n initNotification();\n initFolder();\n\n // bus = new Bus();\n }\n\n /* public Bus getBus() {\n return bus;\n }\n\n public void setBus(Bus bus) {\n this.bus = bus;\n }*/\n\n private void initEmoticons() {\n mEmoticonsId = new HashMap<String, Integer>();\n mEmoticons = new ArrayList<String>();\n mEmoticons_Zem = new ArrayList<String>();\n\n // 预载表情\n for (int i = 1; i < 64; i++) {\n String emoticonsName = \"[zem\" + i + \"]\";\n int emoticonsId = getResources().getIdentifier(\"zem\" + i, \"drawable\", getPackageName());\n mEmoticons.add(emoticonsName);\n mEmoticons_Zem.add(emoticonsName);\n mEmoticonsId.put(emoticonsName, emoticonsId);\n }\n }\n\n private void initNotification() {\n notiMediaplayer = new SoundPool(3, AudioManager.STREAM_SYSTEM, 5);\n // notiSoundPoolID = notiMediaplayer.load(this, R.raw.crystalring, 1);\n notiVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);\n }\n\n @Override\n public void onLowMemory() {\n super.onLowMemory();\n L.e(\"BaseApplication\", \"onLowMemory\");\n }\n\n @Override\n public void onTerminate() {\n super.onTerminate();\n L.e(\"BaseApplication\", \"onTerminate\");\n }\n\n // 函数创建文件存储目录\n private void initFolder() {\n if (null == IMAG_PATH) {\n SAVE_PATH = FileUtils.getSDPath();// 获取SD卡的根目录路径,如果不存在就返回Null\n if (null == SAVE_PATH) {\n SAVE_PATH = instance.getFilesDir().toString();// 获取内置存储区目录\n }\n SAVE_PATH += File.separator + \"WifiProject\";\n IMAG_PATH = SAVE_PATH + File.separator + \"image\";\n THUMBNAIL_PATH = SAVE_PATH + File.separator + \"thumbnail\";\n VOICE_PATH = SAVE_PATH + File.separator + \"voice\";\n FILE_PATH = SAVE_PATH + File.separator + \"file\";\n VEDIO_PATH = SAVE_PATH + File.separator + \"vedio\";\n APK_PATH = SAVE_PATH + File.separator + \"apk\";\n MUSIC_PATH = SAVE_PATH + File.separator + \"music\";\n CAMERA_IMAGE_PATH = IMAG_PATH + File.separator;\n if (!FileUtils.isFileExists(IMAG_PATH))\n FileUtils.createDirFile(BaseApplication.IMAG_PATH);\n if (!FileUtils.isFileExists(THUMBNAIL_PATH))\n FileUtils.createDirFile(BaseApplication.THUMBNAIL_PATH);\n if (!FileUtils.isFileExists(VOICE_PATH))\n FileUtils.createDirFile(BaseApplication.VOICE_PATH);\n if (!FileUtils.isFileExists(VEDIO_PATH))\n FileUtils.createDirFile(BaseApplication.VEDIO_PATH);\n if (!FileUtils.isFileExists(APK_PATH))\n FileUtils.createDirFile(BaseApplication.APK_PATH);\n if (!FileUtils.isFileExists(MUSIC_PATH))\n FileUtils.createDirFile(BaseApplication.MUSIC_PATH);\n if (!FileUtils.isFileExists(FILE_PATH))\n FileUtils.createDirFile(BaseApplication.FILE_PATH);\n\n }\n }\n\n\n /* 设置声音提醒 */\n public static boolean getSoundFlag() {\n return !isSlient;\n }\n\n public static void setSoundFlag(boolean pIsSlient) {\n isSlient = pIsSlient;\n }\n\n /* 设置震动提醒 */\n public static boolean getVibrateFlag() {\n return isVIBRATE;\n }\n\n public static void setVibrateFlag(boolean pIsvibrate) {\n isVIBRATE = pIsvibrate;\n }\n\n /**\n * 新消息提醒 - 声音提醒、振动提醒\n */\n public static void playNotification() {\n if (!isSlient) {\n notiMediaplayer.play(notiSoundPoolID, 1, 1, 0, 0, 1);\n }\n if (isVIBRATE) {\n notiVibrator.vibrate(200);\n }\n\n }\n\n public boolean isClient() {\n return isClient;\n }\n public void setIsClient(boolean isClient) {\n this.isClient = isClient;\n }\n}", "public class ConfigBroadcast {\n public static final String ACTION_CLEAR_SEND_FILES = \"action.CLEAR_SEND_FILES\" ;\n public static final String ACTION_NEW_MSG = \"action.NEW_MSG\";\n public static final String ACTION_UPDATE_BOTTOM = \"action.UPDATE_BOTTOM\";\n}", "public class ConfigIntent {\n\n /**\n * 展示创建,加入按钮\n */\n public static final int REQUEST_SHOW_CREATE = 0x01;\n\n /**\n * 展示正在创建\n */\n public static final int REQUEST_SHOW_CREATING = 0x02;\n\n /**\n * 模糊后图片的存储地址\n */\n public static final String EXTRA_BLUR_PATH = \"blur_path\";\n\n\n public static final String EXTRA_SENDER_IP = \"sender_ip\";\n\n public static final String EXTRA_CHAT_USER = \"chat_user\";\n\n public static final String EXTRA_NEW_MSG_CONTENT = \"new_msg_content\";\n public static final String EXTRA_NEW_MSG_TYPE = \"new_msg_type\";\n public static final int NEW_MSG_TYPE_TXT = 0x401;\n public static final int NEW_MSG_TYPE_IMAGE = 0x402;\n public static final int NEW_MSG_TYPE_VOICE = 0x403;\n public static final int NEW_MSG_TYPE_FILE = 0x404;\n public static final int NEW_MSG_TYPE_VEDIO = 0x405;\n public static final int NEW_MSG_TYPE_MUSIC = 0x406;\n public static final int NEW_MSG_TYPE_APK = 0x407;\n\n\n /**\n * 获取图片\n */\n public static final int REQUEST_PICK_IMAGE = 0x000300;\n\n /**\n * 获取文件\n */\n public static final int REQUEST_PICK_FILE = 0x000301;\n public static final int REQUEST_PICK_APK = 0x000302;\n public static final int REQUEST_PICK_MUSIC = 0x000303;\n public static final int REQUEST_PICK_VEDIO = 0x000304;\n}", "public class Constant {\n\n public static final int TCP_SERVER_RECEIVE_PORT = 4447; // 主机接收端口\n public static int READ_BUFFER_SIZE = 1024*4;// 文件流缓冲大小\n}", "public class FileState {\n public long fileSize = 0;\n public long currentSize = 0;\n public int percent = 0;\n public Message.CONTENT_TYPE type = Message.CONTENT_TYPE.TEXT;\n public String filePath;\n\n public FileState() {\n }\n\n public FileState(String fileFullPath) {\n this.filePath = fileFullPath;\n }\n\n public FileState(String fileFullPath, Message.CONTENT_TYPE type) {\n this(fileFullPath);\n this.type = type;\n }\n\n public FileState(long fileSize, long currentSize, String fileName) {\n this.fileSize = fileSize;\n this.currentSize = currentSize;\n this.filePath = fileName;\n }\n\n public FileState(long fileSize, long currentSize, String fileName, Message.CONTENT_TYPE type) {\n this(fileSize, currentSize, fileName);\n this.type = type;\n }\n}", "public class Message extends Entity {\n\n private String senderIMEI;\n private String sendTime;\n private String msgContent;\n private CONTENT_TYPE contentType;\n private int percent;\n\n public int getLength() {\n return length;\n }\n\n public void setLength(int length) {\n this.length = length;\n }\n\n private int length;\n\n\n public Message(String paramSenderIMEI, String paramSendTime, String paramMsgContent,\n CONTENT_TYPE paramContentType) {\n this.senderIMEI = paramSenderIMEI;\n this.sendTime = paramSendTime;\n this.msgContent = paramMsgContent;\n this.contentType = paramContentType;\n }\n public Message(){\n\n }\n\n /** 消息内容类型 **/\n public enum CONTENT_TYPE {\n TEXT, IMAGE, FILE, VOICE, VEDIO, MUSIC,APK, type;\n }\n\n /**\n * 获取消息发送方IMEI\n *\n * @return\n */\n\n public String getSenderIMEI() {\n return senderIMEI;\n }\n\n /**\n * 设置消息发送方IMEI\n *\n * @param paramSenderIMEI\n *\n */\n public void setSenderIMEI(String paramSenderIMEI) {\n this.senderIMEI = paramSenderIMEI;\n }\n\n /**\n * 获取消息内容类型\n *\n * @return\n * @see CONTENT_TYPE\n */\n public CONTENT_TYPE getContentType() {\n return contentType;\n }\n\n /**\n * 设置消息内容类型\n *\n * @param paramContentType\n * @see CONTENT_TYPE\n */\n public void setContentType(CONTENT_TYPE paramContentType) {\n this.contentType = paramContentType;\n }\n\n /**\n * 获取消息发送时间\n *\n * @return\n */\n public String getSendTime() {\n return sendTime;\n }\n\n /**\n * 设置消息发送时间\n *\n * @param paramSendTime\n * 发送时间,格式 xx年xx月xx日 xx:xx:xx\n */\n public void setSendTime(String paramSendTime) {\n this.sendTime = paramSendTime;\n }\n\n /**\n * 获取消息内容\n *\n * @return\n */\n public String getMsgContent() {\n return msgContent;\n }\n\n /**\n * 设置消息内容\n *\n * @param paramMsgContent\n */\n public void setMsgContent(String paramMsgContent) {\n this.msgContent = paramMsgContent;\n }\n\n /**\n * 克隆对象\n *\n * @param\n */\n\n public Message clone() {\n return new Message(senderIMEI, sendTime, msgContent, contentType);\n }\n\n // @JSONField(serialize = false)\n public int getPercent() {\n return percent;\n }\n\n public void setPercent(int percent) {\n this.percent = percent;\n }\n\n}", "public class IPMSGConst {\n\tpublic static final int VERSION = 0x001;\t\t// 版本号\n\tpublic static final int PORT = 0x0979;\t\t\t// 端口号,飞鸽协议默认端口2425\n\t\n\tpublic static final int IPMSG_NOOPERATION\t\t = 0x00000000;\t//不进行任何操作\n\tpublic static final int IPMSG_BR_ENTRY\t\t\t = 0x00000001;\t//用户上线\n\tpublic static final int IPMSG_BR_EXIT\t\t \t = 0x00000002;\t//用户退出\n\tpublic static final int IPMSG_ANSENTRY\t\t\t = 0x00000003;\t//通报在线\n\tpublic static final int IPMSG_BR_ABSENCE\t\t = 0x00000004;\t//改为缺席模式\n\t\n\tpublic static final int IPMSG_BR_ISGETLIST\t\t = 0x00000010;\t//寻找有效的可以发送用户列表的成员\n\tpublic static final int IPMSG_OKGETLIST\t\t\t = 0x00000011;\t//通知用户列表已经获得\n\tpublic static final int IPMSG_GETLIST\t\t\t = 0x00000012;\t//用户列表发送请求\n\tpublic static final int IPMSG_ANSLIST\t\t\t = 0x00000013;\t//应答用户列表发送请求\n\t\n\tpublic static final int IPMSG_SENDMSG \t\t = 0x00000020;\t//发送消息\n\tpublic static final int IPMSG_RECVMSG \t\t\t = 0x00000021;\t//通报收到消息\n\tpublic static final int IPMSG_READMSG \t\t\t = 0x00000030;\t//消息打开通知\n\tpublic static final int IPMSG_DELMSG \t\t\t = 0x00000031;\t//消息丢弃通知\n\tpublic static final int IPMSG_ANSREADMSG\t\t = 0x00000032;\t//消息打开确认通知\n\t\n\tpublic static final int IPMSG_GETINFO\t\t\t = 0x00000040;\t//获得IPMSG版本信息\n\tpublic static final int IPMSG_SENDINFO\t\t\t = 0x00000041;\t//发送IPMSG版本信息\n\t\n\tpublic static final int IPMSG_GETABSENCEINFO\t = 0x00000050;\t//获得缺席信息\n\tpublic static final int IPMSG_SENDABSENCEINFO\t = 0x00000051;\t//发送缺席信息\n\n public static final int IPMSG_UPDATE_FILEPROCESS = 0x00000060; //更新文件传输进度\n public static final int IPMSG_SEND_FILE_SUCCESS = 0x00000061; //文件发送成功 \n public static final int IPMSG_GET_FILE_SUCCESS = 0x00000062; //文件接收成功\n \n\tpublic static final int IPMSG_REQUEST_IMAGE_DATA = 0x00000063; //图片发送请求\n\tpublic static final int IPMSG_CONFIRM_IMAGE_DATA = 0x00000064; //图片接收确认\n\tpublic static final int IPMSG_SEND_IMAGE_SUCCESS = 0x00000065; //图片发送成功\n\tpublic static final int IPMSG_REQUEST_VOICE_DATA = 0x00000066; //录音发送请求\n\tpublic static final int IPMSG_CONFIRM_VOICE_DATA = 0x00000067; //录音接收确认\n\tpublic static final int IPMSG_SEND_VOICE_SUCCESS = 0x00000068; //录音发送成功\n\tpublic static final int IPMSG_REQUEST_FILE_DATA = 0x00000069; //文件发送请求\n\tpublic static final int IPMSG_CONFIRM_FILE_DATA = 0x00000070; //文件接收确认\n\t\n\tpublic static final int IPMSG_GETPUBKEY\t\t\t = 0x00000072;\t//获得RSA公钥\n\tpublic static final int IPMSG_ANSPUBKEY\t\t\t = 0x00000073;\t//应答RSA公钥\n\t\n\t/* option for all command */\n\tpublic static final int IPMSG_ABSENCEOPT \t\t = 0x00000100;\t//缺席模式\n\tpublic static final int IPMSG_SERVEROPT \t\t = 0x00000200;\t//服务器(保留)\n\tpublic static final int IPMSG_DIALUPOPT \t\t = 0x00010000;\t//发送给个人\n\tpublic static final int IPMSG_FILEATTACHOPT \t = 0x00200000;\t//附加文件\n\tpublic static final int IPMSG_ENCRYPTOPT\t\t = 0x00400000;\t//加密\n\n\t//NO_代表请求 AN_代表应答\n\tpublic static final int NO_CONNECT_SUCCESS = 0x00000200;\t//连接服务器成功;\n\tpublic static final int AN_CONNECT_SUCCESS = 0x00000201; //服务器确认连接成功;\n\tpublic static final int NO_SEND_TXT = 0x00000202; //发送文本消息;\n\tpublic static final int AN_SEND_TXT = 0x00000203; //确认接收到了文本消息;\n\tpublic static final int NO_SEND_IMAGE = 0x00000204; //发送图片\n\tpublic static final int AN_SEND_IMAGE = 0x00000205; //确认接收图片\n\tpublic static final int NO_SEND_VOICE = 0x00000206; //发送语音;\n\tpublic static final int AN_SEND_VOICE = 0x00000207; //确认接收语音;\n\tpublic static final int NO_SEND_FILE = 0x00000208; //发送文件\n\tpublic static final int AN_SEND_FILE = 0x00000209; //确认接收文件\n\tpublic static final int NO_SEND_VEDIO = 0x0000020a; //发送视频\n\tpublic static final int AN_SEND_VEDIO = 0x0000020b; //确认接收发送视频\n\tpublic static final int NO_SEND_MUSIC \t\t\t = 0x0000020c; //发送音乐\n\tpublic static final int AN_SEND_MUSIC \t\t\t = 0x0000020d; //确认接受音乐\n\tpublic static final int NO_SEND_APK \t\t\t = 0x0000020e; //发送APK\n\tpublic static final int AN_SEND_APK \t\t\t = 0x0000020f; //确认接APK\n\n\t/**\n\t * Message .what\n\t */\n\tpublic static final int WHAT_FILE_SENDING = 0x00000400; //文件发送中;\n\tpublic static final int WHAT_FILE_RECEIVING = 0x00000401; //文件接收中;\n\n}", "public class L {\n public static boolean isDebug = true; // 是否需要打印bug,可以在application的onCreate函数里面初始化\n private static final String TAG = \"WifiLog\";\n\n public static String fromHere() {\n String ret = \"\";\n if (isDebug) {\n StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];\n StringBuffer toStringBuffer = new StringBuffer(\"[\").append(traceElement.getFileName())\n .append(\" | \").append(traceElement.getMethodName()).append(\" | \")\n .append(traceElement.getLineNumber()).append(\"]\");\n ret = toStringBuffer.toString();\n }\n return ret;\n }\n\n // 下面四个是默认tag的函数\n public static void i(String msg) {\n if (isDebug)\n Log.i(TAG, \"...............\" + msg);\n }\n\n public static void d(String msg) {\n if (isDebug)\n Log.d(TAG, \"...............\" + msg);\n }\n\n public static void e(String msg) {\n if (isDebug)\n Log.e(TAG, \"...............\" + msg);\n }\n\n public static void v(String msg) {\n if (isDebug)\n Log.v(TAG, \"...............\" + msg);\n }\n\n // 下面是传入自定义tag的函数\n public static void i(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n\n public static void d(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n\n public static void e(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n\n public static void v(String tag, String msg) {\n if (isDebug)\n Log.i(tag, \"...............\" + msg);\n }\n}" ]
import android.content.Context; import android.content.Intent; import android.os.Handler; import com.orhanobut.logger.Logger; import com.zjk.wifiproject.BaseApplication; import com.zjk.wifiproject.config.ConfigBroadcast; import com.zjk.wifiproject.config.ConfigIntent; import com.zjk.wifiproject.entity.Constant; import com.zjk.wifiproject.entity.FileState; import com.zjk.wifiproject.entity.Message; import com.zjk.wifiproject.socket.udp.IPMSGConst; import com.zjk.wifiproject.util.L; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList;
package com.zjk.wifiproject.socket.tcp; public class TcpService implements Runnable { private static final String TAG = "SZU_TcpService"; private ServerSocket serviceSocket; private boolean SCAN_FLAG = false; // 接收扫描标识 private Thread mThread; ArrayList<FileState> receivedFileNames; ArrayList<SaveFileToDisk> saveFileToDisks; private static Handler mHandler; private String filePath = null; // 存放接收文件的路径 private static Context mContext; private static TcpService instance; // 唯一实例 private boolean IS_THREAD_STOP = false; // 是否线程开始标志 private TcpService() { try {
serviceSocket = new ServerSocket(Constant.TCP_SERVER_RECEIVE_PORT);
3
ustream/yolo
src/main/java/tv/ustream/yolo/module/ModuleChain.java
[ "public class ConfigException extends Exception\n{\n\n public ConfigException(final String message)\n {\n super(\"Configuration error: \" + message);\n }\n\n}", "public class ConfigMap implements IConfigEntry<Map<String, Object>>\n{\n\n private final Map<String, IConfigEntry> config = new HashMap<String, IConfigEntry>();\n\n public void addConfigEntry(final String name, final IConfigEntry configValue)\n {\n config.put(name, configValue);\n }\n\n public <T> void addConfigValue(final String name, final Class<T> type)\n {\n addConfigValue(name, type, true, null);\n }\n\n public <T> void addConfigValue(final String name, final Class<T> type, final boolean required, final T defaultValue)\n {\n config.put(name, new ConfigValue<T>(type, required, defaultValue));\n }\n\n public void addConfigList(final String name, final ConfigMap configMap)\n {\n config.put(name, new ConfigList(configMap));\n }\n\n public ConfigMap merge(final ConfigMap configMap)\n {\n if (null != configMap)\n {\n for (Map.Entry<String, IConfigEntry> configEntry : configMap.config.entrySet())\n {\n addConfigEntry(configEntry.getKey(), configEntry.getValue());\n }\n }\n return this;\n }\n\n public boolean isEmpty()\n {\n return config.isEmpty();\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public Map<String, Object> parse(final String name, final Object data) throws ConfigException\n {\n if (!(data instanceof Map))\n {\n throw new ConfigException(name + \" should be a map\");\n }\n Map<String, Object> map = (Map<String, Object>) data;\n for (Map.Entry<String, IConfigEntry> configEntry : config.entrySet())\n {\n Object value = map.get(configEntry.getKey());\n map.put(configEntry.getKey(), configEntry.getValue().parse(name + \".\" + configEntry.getKey(), value));\n }\n return map;\n }\n\n public String getDescription(String indent)\n {\n String result = String.format(\"Map {%n\");\n for (Map.Entry<String, IConfigEntry> configEntry : config.entrySet())\n {\n result += String.format(\n \"%s%s: %s\",\n indent + \" \", configEntry.getKey(),\n configEntry.getValue().getDescription(indent + \" \")\n );\n }\n result += String.format(\"%s}%n\", indent);\n return result;\n }\n\n}", "public class ConfigPattern\n{\n\n private static final Pattern PARAMS_PATTERN = Pattern.compile(\"#([a-zA-Z0-9_\\\\-\\\\.]+)#\");\n\n private final String pattern;\n\n private final List<String> parameters = new ArrayList<String>();\n\n private static Map<String, String> globalParameters = new HashMap<String, String>();\n\n private final boolean simplePattern;\n\n public ConfigPattern(final String pattern)\n {\n this.pattern = pattern;\n Matcher matcher = PARAMS_PATTERN.matcher(pattern);\n while (matcher.find())\n {\n parameters.add(matcher.group(1));\n }\n\n simplePattern = parameters.size() == 1 && pattern.startsWith(\"#\") && pattern.endsWith(\"#\");\n }\n\n public static boolean applicable(final Object pattern)\n {\n if (!(pattern instanceof String))\n {\n return false;\n }\n Matcher matcher = PARAMS_PATTERN.matcher((String) pattern);\n return matcher.find();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static Object replacePatterns(final Object data, final List<String> validKeys) throws ConfigException\n {\n if (data instanceof Map)\n {\n Map<String, Object> map = ((Map<String, Object>) data);\n for (Map.Entry<String, Object> entry : map.entrySet())\n {\n map.put(entry.getKey(), replacePatterns(entry.getValue(), validKeys));\n }\n }\n if (data instanceof List)\n {\n List<Object> list = (List<Object>) data;\n for (int i = 0; i < list.size(); i++)\n {\n list.set(i, replacePatterns(list.get(i), validKeys));\n }\n }\n if (applicable(data))\n {\n ConfigPattern pattern = new ConfigPattern((String) data);\n if (null != validKeys)\n {\n for (String key : pattern.getParameters())\n {\n if (!validKeys.contains(key) && !globalParameters.containsKey(key))\n {\n throw new ConfigException(\"#\" + key + \"# parameter is missing from parser output!\");\n }\n }\n }\n return pattern;\n }\n else\n {\n return data;\n }\n }\n\n public String applyValues(final Map<String, Object> values)\n {\n if (simplePattern)\n {\n return (String) values.get(parameters.get(0));\n }\n else\n {\n String result = pattern;\n for (String parameter : parameters)\n {\n\n if (globalParameters.containsKey(parameter))\n {\n result = result.replace(\"#\" + parameter + \"#\", globalParameters.get(parameter));\n }\n else if (values.containsKey(parameter))\n {\n result = result.replace(\"#\" + parameter + \"#\", (String) values.get(parameter));\n }\n else\n {\n return null;\n }\n }\n return result;\n }\n }\n\n public List<String> getParameters()\n {\n return parameters;\n }\n\n public static void addGlobalParameter(final String key, final String value)\n {\n globalParameters.put(key, value);\n }\n\n @Override\n public boolean equals(final Object o)\n {\n if (this == o)\n {\n return true;\n }\n if (o == null || getClass() != o.getClass())\n {\n return false;\n }\n\n ConfigPattern that = (ConfigPattern) o;\n\n return pattern.equals(that.pattern);\n\n }\n\n @Override\n public int hashCode()\n {\n return pattern.hashCode();\n }\n\n @Override\n public String toString()\n {\n return \"ConfigPattern('\" + pattern + \"')\";\n }\n}", "public interface ILineHandler\n{\n\n void handle(String line);\n\n}", "public interface IParser extends IModule\n{\n\n Map<String, Object> parse(String line);\n\n boolean runAlways();\n\n List<String> getOutputKeys();\n\n}", "public interface ICompositeProcessor extends IProcessor\n{\n\n void addProcessor(IProcessor processor);\n\n}", "public interface IProcessor extends IModule\n{\n\n ConfigMap getProcessParamsConfig();\n\n void process(Map<String, Object> parserOutput, Map<String, Object> processParams);\n\n void stop();\n\n}" ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tv.ustream.yolo.config.ConfigException; import tv.ustream.yolo.config.ConfigMap; import tv.ustream.yolo.config.ConfigPattern; import tv.ustream.yolo.handler.ILineHandler; import tv.ustream.yolo.module.parser.IParser; import tv.ustream.yolo.module.processor.ICompositeProcessor; import tv.ustream.yolo.module.processor.IProcessor; import java.util.HashMap; import java.util.List; import java.util.Map;
package tv.ustream.yolo.module; /** * @author bandesz */ public class ModuleChain implements ILineHandler { private static final Logger LOG = LoggerFactory.getLogger(ModuleChain.class); private final ModuleFactory moduleFactory; private final Map<String, IParser> parsers = new HashMap<String, IParser>(); private final Map<String, IProcessor> processors = new HashMap<String, IProcessor>(); private final Map<String, Map<String, Map<String, Object>>> transitions = new HashMap<String, Map<String, Map<String, Object>>>(); private Map<String, Object> config = null; public ModuleChain(final ModuleFactory moduleFactory) { this.moduleFactory = moduleFactory; } private ConfigMap getMainConfig() { ConfigMap mainConfig = new ConfigMap(); mainConfig.addConfigValue("processors", Map.class); mainConfig.addConfigValue("parsers", Map.class); return mainConfig; } public void updateConfig(final Map<String, Object> config, final boolean instant) throws ConfigException { this.config = config; getMainConfig().parse("[root]", config); if (instant) { update(); } } private void update() throws ConfigException { if (config == null) { return; } stop(); reset(); Map<String, Object> processorsEntry = (Map<String, Object>) config.get("processors"); for (Map.Entry<String, Object> processor : processorsEntry.entrySet()) { addProcessor(processor.getKey(), (Map<String, Object>) processor.getValue()); } for (Map.Entry<String, Object> processor : processorsEntry.entrySet()) { setupCompositeProcessor(processors.get(processor.getKey()), (Map<String, Object>) processor.getValue()); } Map<String, Object> parsersEntry = (Map<String, Object>) config.get("parsers"); for (Map.Entry<String, Object> parser : parsersEntry.entrySet()) { addParser(parser.getKey(), (Map<String, Object>) parser.getValue()); } config = null; } @SuppressWarnings("unchecked") private void addProcessor(String name, Map<String, Object> config) throws ConfigException { LOG.info("Adding {} processor {}", name, config); IProcessor processor = moduleFactory.createProcessor(name, config); if (processor == null) { return; } processors.put(name, processor); } private void setupCompositeProcessor(IProcessor processor, Map<String, Object> config) throws ConfigException {
if (!(processor instanceof ICompositeProcessor))
5
quartzweb/quartz-web
src/main/java/com/github/quartzweb/service/strategy/TriggerServiceStrategyParameter.java
[ "public class UnsupportedTranslateException extends RuntimeException {\n\n public UnsupportedTranslateException() {\n }\n\n public UnsupportedTranslateException(String message) {\n super(message);\n }\n\n public UnsupportedTranslateException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public UnsupportedTranslateException(Throwable cause) {\n super(cause);\n }\n\n}", "public abstract class HttpParameterNameConstants {\n\n /**\n * 关于Scheduler\n */\n public static class Scheduler {\n\n /** Scheduler - schedule名称 */\n public static final String NAME = \"schedulerName\";\n\n /** Scheduler - 延时秒数 - 单位(秒) */\n public static final String DELAYED = \"delayed\";\n\n }\n\n\n /**\n * 关于Job操作\n */\n public static class Job {\n /** Job操作 - job名称 */\n public static final String NAME = \"jobName\";\n\n /** Job操作 - job分组 */\n public static final String GROUP = \"jobGroup\";\n\n /** Job操作 - jobDataMap数据 -key值 */\n public static final String DATA_MAP_KEY_PREFIX = \"jobDataMapKey_\";\n\n /** Job操作 - jobDataMap数据 -value值 */\n public static final String DATA_MAP_VALUE_PREFIX = \"jobDataMapValue_\";\n\n /** Job操作 - JobClass,*/\n public static final String JOB_CLASS = \"jobClass\";\n\n /** Job操作 - Job类型*/\n public static final String JOB_TYPE = \"jobType\";\n\n /** Job操作 - job描述 */\n public static final String DESCRIPTION = \"description\";\n\n /** Job操作 - JobClass参数名称前缀 */\n public static final String JOB_CLASS_PARAM_TYPE_NAME_PREFIX = \"jobClassParamType_\";\n\n /** Job操作 - JobClass参数值前缀 */\n public static final String JOB_CLASS_PARAM_TYPE_VALUE_PREFIX = \"jobClassParamTypeValue_\";\n\n /** Job操作 - 执行方法类型 */\n public static final String METHOD_INVOKER_TYPE = \"methodInvokerType\";\n\n /** Job操作 - 执行方法名称 */\n public static final String JOB_CLASS_METHOD_NAME = \"jobClassMethodName\";\n /** Job操作 - 执行method类型前缀*/\n public static final String JOB_CLASS_METHOD_PARAM_TYPE_NAME_PREFIX = \"jobClassMethodParamType_\";\n\n /** Job操作 - 执行method参数值前缀 */\n public static final String JOB_CLASS_METHOD_PARAM_TYPE_VALUE_PREFIX = \"jobClassMethodParamTypeValue_\";\n\n }\n\n\n public static class Trigger {\n\n /** Trigger操作 - trigger名称 */\n public static final String NAME = \"triggerName\";\n\n\n /** HTTP参数名称 - Trigger操作 - job分组 */\n public static final String GROUP = \"triggerGroup\";\n\n /** trigger描述 */\n public static final String DESCRIPTION = \"description\";\n\n /** 优先级 */\n public static final String PRIORITY = \"priority\";\n\n /** cron表达式 */\n public static final String CRONEXPRESSION = \"cronExpression\";\n\n /** trigger 开始时间 */\n public static final String START_DATE = \"startDate\";\n\n /** trigger 结束时间 */\n public static final String END_DATE = \"endDate\";\n\n }\n\n\n public static class Validate{\n /** 对比是否为子类的Class名称 */\n public static final String ASSIGNABLE_CLASS_NAME= \"assignableClassName\";\n\n /** Class名称 */\n public static final String CLASS_NAME= \"className\";\n\n /** cron表达式 */\n public static final String CRON_EXPRESSION= \"cronExpression\";\n }\n\n\n}", "public class DateUtils {\n\n\n\n private static Date startTime;\n\n /**\n * 获取jvm启动时间\n * @return 启动时间\n */\n public final static Date getVMStartTime() {\n if (startTime == null) {\n startTime = new Date(ManagementFactory.getRuntimeMXBean().getStartTime());\n }\n return startTime;\n }\n\n /**\n * 格式化时间\n * @param date\n * @return yyyy-MM-dd HH:mm:ss 的时间\n */\n public static String formart(Date date) {\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n return format.format(date);\n }\n\n public static Date parse(String date) {\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n try {\n return format.parse(date);\n } catch (ParseException e) {\n return null;\n }\n }\n\n}", "public class RequestUtils {\n\n /**\n * 获取reuqest中的map数据\n * 数据结构 mapKeyPrefix_index,value\n *\n * @param request request请求\n * @param mapKeyPrefix key前缀\n * @return map数据\n */\n public static Map<String, String> getMapData(HttpServletRequest request, String mapKeyPrefix,String mapValuePrefix) {\n\n Map<String,String> mapData = new LinkedHashMap<String, String>();\n Map<String, String[]> requestParameterMap = request.getParameterMap();\n\n for (Map.Entry<String, String[]> dataEntry : requestParameterMap.entrySet()) {\n String key = dataEntry.getKey();\n // 是否为构造函数参数\n if (key.startsWith(mapKeyPrefix)) {\n\n String[] dataMapKeyInfo = key.split(\"_\");\n\n //参数名称是否正确\n if (dataMapKeyInfo.length != 2) {\n throw new UnsupportedTranslateException(\"resolve request map data format exception\");\n }\n //序号\n String index = dataMapKeyInfo[1];\n if (!StringUtils.isIntegerGTNumber(index, -1)) {\n throw new UnsupportedTranslateException(\"resolve request map data format exception\");\n }\n\n mapData.put(request.getParameter(mapKeyPrefix + index), request.getParameter(mapValuePrefix + index));\n }\n }\n return mapData;\n }\n\n /**\n * 将request转换成所需要的map类型\n *\n * @param request request实体类\n * @param classTypePrefix 类型前缀\n * @param argsPrefix 参数前缀\n * @param classList class类型集合\n * @param argList 参数集合\n */\n public static void getClassTypesAndArgs(HttpServletRequest request, String classTypePrefix, String argsPrefix,\n List<Class> classList,List<Object> argList) {\n Map<String, String[]> requestParameterMap = request.getParameterMap();\n Map<String, String> jobClassParamType = new LinkedHashMap<String, String>();\n // 获取class类型的Map\n for (Map.Entry<String, String[]> parameterEntry : requestParameterMap.entrySet()) {\n String key = parameterEntry.getKey();\n if (key.startsWith(classTypePrefix)) {\n jobClassParamType.put(key, request.getParameter(key));\n }\n }\n\n Class[] classTypes = new Class[jobClassParamType.size()];\n Object[] args = new Object[jobClassParamType.size()];\n for (Map.Entry<String, String> jobClassParamTypeEntry : jobClassParamType.entrySet()) {\n // 获取参数名称_index\n String key = jobClassParamTypeEntry.getKey();\n String paramClassName = jobClassParamTypeEntry.getValue();\n String[] jobClassParamTypeInfo = key.split(\"_\");\n\n //参数名称是否正确\n if (jobClassParamTypeInfo.length != 2) {\n throw new UnsupportedTranslateException(\"resolve request class format exception\");\n }\n //序号\n String paramIndex = jobClassParamTypeInfo[1];\n // 校验序号\n if (!StringUtils.isIntegerGTNumber(paramIndex, -1)) {\n throw new UnsupportedTranslateException(\"resolve request class format exception\");\n }\n // 校验class是否合法\n // 不是基础类型\n if (!BasicTypeUtils.checkBasicType(paramClassName)) {\n // 类型不存在\n if (!QuartzWebManager.checkClass(paramClassName)) {\n throw new UnsupportedTranslateException(\"class no class found [\" + paramClassName + \"] exception\");\n }\n }\n\n //获取class的实例对象值\n String paramClassValue = request.getParameter(argsPrefix + paramIndex);\n try {\n Integer index = Integer.parseInt(paramIndex);\n if (index > jobClassParamType.size()) {\n throw new UnsupportedTranslateException(\"resolve request class format exception\");\n }\n if (BasicTypeUtils.checkBasicType(paramClassName)||BasicTypeUtils.checkBasicTypeObj(paramClassName)) {\n classTypes[index] = BasicTypeUtils.getClass(paramClassName);\n } else {\n classTypes[index] = QuartzWebManager.getBean(paramClassName).getClass();\n }\n if (classTypes[index].isAssignableFrom(Integer.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n paramClassValue = \"0\";\n }\n args[index] = Integer.valueOf(paramClassValue);\n } else if (classTypes[index].isAssignableFrom(int.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n paramClassValue = \"0\";\n }\n args[index] = Integer.parseInt(paramClassValue);\n } else if (classTypes[index].isAssignableFrom(Double.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n paramClassValue = \"0\";\n }\n args[index] = Double.valueOf(paramClassValue);\n } else if (classTypes[index].isAssignableFrom(double.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n paramClassValue = \"0\";\n }\n args[index] = Double.parseDouble(paramClassValue);\n } else if (classTypes[index].isAssignableFrom(Float.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n paramClassValue = \"0\";\n }\n args[index] = Float.valueOf(paramClassValue);\n } else if (classTypes[index].isAssignableFrom(float.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n paramClassValue = \"0\";\n }\n args[index] = Float.parseFloat(paramClassValue);\n } else if (classTypes[index].isAssignableFrom(Date.class)) {\n if (StringUtils.isEmpty(paramClassValue)) {\n args[index] = null;\n }else{\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n Date date = sdf.parse(paramClassValue);\n args[index] = date;\n }\n\n } else if (classTypes[index].isAssignableFrom(String.class)) {\n args[index] = paramClassValue;\n } else {\n if (!StringUtils.isEmpty(paramClassValue)) {\n boolean sourceCheck = QuartzWebManager.checkClass(paramClassName);\n boolean targetCheck = QuartzWebManager.checkClass(paramClassValue);\n if (sourceCheck && targetCheck) {\n Object source = QuartzWebManager.getBean(paramClassName);\n Object target = QuartzWebManager.getBean(paramClassValue);\n boolean assignableFrom = ClassUtils.isAssignableFrom(source, target);\n if (assignableFrom) {\n args[index] = QuartzWebManager.getBean(paramClassValue);\n }\n }\n throw new UnsupportedTranslateException(\"class not found or class cast exception\");\n\n }\n\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n throw new UnsupportedTranslateException(\"class not found or class cast exception\");\n }\n }\n Collections.addAll(classList, classTypes);\n Collections.addAll(argList, args);\n }\n\n\n\n}", "public class StringUtils {\n\n /**\n * 判断两个字符串是否相等\n * @param a 字符\n * @param b 字符\n * @return true相等,false不相等\n */\n public static boolean equals(String a, String b) {\n if (a == null) {\n return b == null;\n }\n return a.equals(b);\n }\n\n /**\n * 忽略大小写判断两个字符串是否相等\n * @param a 字符\n * @param b 字符\n * @return true相等,false不相等\n */\n public static boolean equalsIgnoreCase(String a, String b) {\n if (a == null) {\n return b == null;\n }\n return a.equalsIgnoreCase(b);\n }\n\n /**\n * 判断字符串是否为空(NULL或空串\"\")\n * @param value 字符串\n * @return true为空,false不为空\n */\n public static boolean isEmpty(CharSequence value) {\n if (value == null || value.length() == 0) {\n return true;\n }\n return false;\n }\n\n /**\n * 是否为整数\n * @param str\n * @return\n */\n public static boolean isInteger(String str) {\n Pattern pattern = Pattern.compile(\"^[-\\\\+]?[\\\\d]*$\");\n return pattern.matcher(str).matches();\n }\n\n /**\n * 判断是否为大于某个数字的整数\n * @param str\n * @param integer\n * @return\n */\n public static boolean isIntegerGTNumber(String str,Integer integer) {\n // 是整数\n if (isInteger(str)) {\n int source = Integer.parseInt(str);\n return source > integer;\n } else {\n return false;\n }\n }\n}" ]
import com.github.quartzweb.exception.UnsupportedTranslateException; import com.github.quartzweb.service.HttpParameterNameConstants; import com.github.quartzweb.utils.DateUtils; import com.github.quartzweb.utils.RequestUtils; import com.github.quartzweb.utils.StringUtils; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map;
/** * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.github.quartzweb.service.strategy; /** * @author 曲修成 * @author quxiucheng [[email protected]] */ public class TriggerServiceStrategyParameter implements ServiceStrategyParameter { /** * scheduler名称 */ private String schedulerName; /** * jobName */ private String jobName; /** * jobGroup */ private String jobGroup; /** * triggerName */ private String triggerName; /** * triggerGroup */ private String triggerGroup; /** * cron表达式 */ private String cronExpression; /** * 描述 */ private String description; /** * 优先级 */ private String priority; /** * 开始时间 */ private Date startDate; /** * 结束时间 */ private Date endDate; /** * 附件data */ private Map<String, String> jobDataMap; /** * 获取 scheduler名称 * * @return schedulerName scheduler名称 */ public String getSchedulerName() { return this.schedulerName; } /** * 设置 scheduler名称 * * @param schedulerName scheduler名称 */ public void setSchedulerName(String schedulerName) { this.schedulerName = schedulerName; } /** * 获取 jobName * * @return jobName jobName */ public String getJobName() { return this.jobName; } /** * 设置 jobName * * @param jobName jobName */ public void setJobName(String jobName) { this.jobName = jobName; } /** * 获取 jobGroup * * @return jobGroup jobGroup */ public String getJobGroup() { return this.jobGroup; } /** * 设置 jobGroup * * @param jobGroup jobGroup */ public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } /** * 获取 triggerName * * @return triggerName triggerName */ public String getTriggerName() { return this.triggerName; } /** * 设置 triggerName * * @param triggerName triggerName */ public void setTriggerName(String triggerName) { this.triggerName = triggerName; } /** * 获取 triggerGroup * * @return triggerGroup triggerGroup */ public String getTriggerGroup() { return this.triggerGroup; } /** * 设置 triggerGroup * * @param triggerGroup triggerGroup */ public void setTriggerGroup(String triggerGroup) { this.triggerGroup = triggerGroup; } /** * 获取 cron表达式 * @return cronExpression cron表达式 */ public String getCronExpression() { return this.cronExpression; } /** * 设置 cron表达式 * @param cronExpression cron表达式 */ public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } /** * 获取 描述 * @return description 描述 */ public String getDescription() { return this.description; } /** * 设置 描述 * @param description 描述 */ public void setDescription(String description) { this.description = description; } /** * 获取 优先级 * @return priority 优先级 */ public String getPriority() { return this.priority; } /** * 设置 优先级 * @param priority 优先级 */ public void setPriority(String priority) { this.priority = priority; } /** * 获取 开始时间 * @return startDate 开始时间 */ public Date getStartDate() { return this.startDate; } /** * 设置 开始时间 * @param startDate 开始时间 */ public void setStartDate(Date startDate) { this.startDate = startDate; } /** * 获取 结束时间 * @return endDate 结束时间 */ public Date getEndDate() { return this.endDate; } /** * 设置 结束时间 * @param endDate 结束时间 */ public void setEndDate(Date endDate) { this.endDate = endDate; } /** * 获取 附件data * @return jobDataMap 附件data */ public Map<String, String> getJobDataMap() { return this.jobDataMap; } /** * 设置 附件data * @param jobDataMap 附件data */ public void setJobDataMap(Map<String, String> jobDataMap) { this.jobDataMap = jobDataMap; } @Override public void translate(Object object) throws UnsupportedTranslateException { if (object instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) object;
this.setSchedulerName(request.getParameter(HttpParameterNameConstants.Scheduler.NAME));
1
strepsirrhini-army/chaos-loris
src/main/java/io/pivotal/strepsirrhini/chaosloris/destroyer/StandardDestroyer.java
[ "@Entity\npublic class Application {\n\n @Column(nullable = false, unique = true)\n private UUID applicationId;\n\n @Column(nullable = false)\n @GeneratedValue\n @Id\n @JsonIgnore\n private Long id;\n\n /**\n * Create a new instance\n *\n * @param applicationId the Cloud Foundry application id\n */\n public Application(UUID applicationId) {\n this.applicationId = applicationId;\n }\n\n Application() {\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 Application that = (Application) o;\n return Objects.equals(this.applicationId, that.applicationId) &&\n Objects.equals(this.id, that.id);\n }\n\n /**\n * Returns the application id\n *\n * @return the application id\n */\n public UUID getApplicationId() {\n return this.applicationId;\n }\n\n /**\n * Returns the id\n *\n * @return the id\n */\n public Long getId() {\n return this.id;\n }\n\n /**\n * Sets the id\n *\n * @param id the id\n */\n public void setId(Long id) {\n this.id = id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.applicationId, this.id);\n }\n\n @Override\n public String toString() {\n return \"Application{\" +\n \"applicationId=\" + this.applicationId +\n \", id=\" + this.id +\n '}';\n }\n\n}", "@Entity\n@Table(uniqueConstraints = @UniqueConstraint(columnNames = {\"application_id\", \"schedule_id\"}))\npublic class Chaos {\n\n @JoinColumn(nullable = false)\n @JsonIgnore\n @ManyToOne\n private Application application;\n\n @Column(nullable = false)\n @GeneratedValue\n @Id\n @JsonIgnore\n private Long id;\n\n @Column(nullable = false)\n private Double probability;\n\n @JoinColumn(nullable = false)\n @JsonIgnore\n @ManyToOne\n private Schedule schedule;\n\n /**\n * Create a new instance\n *\n * @param application the application to apply chaos to\n * @param probability the probability of an instance being destroyed\n * @param schedule the schedule to apply chaos on\n */\n public Chaos(Application application, Double probability, Schedule schedule) {\n this.application = application;\n this.probability = probability;\n this.schedule = schedule;\n }\n\n Chaos() {\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 Chaos chaos = (Chaos) o;\n return Objects.equals(this.application, chaos.application) &&\n Objects.equals(this.id, chaos.id) &&\n Objects.equals(this.probability, chaos.probability) &&\n Objects.equals(this.schedule, chaos.schedule);\n }\n\n /**\n * Returns the application\n *\n * @return the application\n */\n public Application getApplication() {\n return this.application;\n }\n\n /**\n * Returns the id\n *\n * @return the id\n */\n public Long getId() {\n return this.id;\n }\n\n /**\n * Sets the id\n *\n * @param id the id\n */\n public void setId(Long id) {\n this.id = id;\n }\n\n /**\n * Returns the probability\n *\n * @return the probability\n */\n public Double getProbability() {\n return this.probability;\n }\n\n /**\n * Sets the probability\n *\n * @param probability the probability\n */\n public void setProbability(Double probability) {\n this.probability = probability;\n }\n\n /**\n * Returns the schedule\n *\n * @return the schedule\n */\n public Schedule getSchedule() {\n return this.schedule;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.application, this.id, this.probability, this.schedule);\n }\n\n @Override\n public String toString() {\n return \"Chaos{\" +\n \"application=\" + this.application +\n \", id=\" + this.id +\n \", probability=\" + this.probability +\n \", schedule=\" + this.schedule +\n '}';\n }\n\n}", "@Repository\npublic interface ChaosRepository extends JpaRepository<Chaos, Long> {\n\n /**\n * Find all of the {@link Chaos}es related to an {@link Application}\n *\n * @param application the {@link Application} that {@link Chaos}es are related to\n * @return a collection of {@link Chaos}es related to the {@link Application}\n */\n @Transactional(readOnly = true)\n List<Chaos> findByApplication(Application application);\n\n /**\n * Find all of the {@link Chaos}es related to a {@link Schedule}\n *\n * @param schedule the {@link Schedule} that {@link Chaos}es are related to\n * @return a collection of {@link Chaos}es related to the {@link Schedule}\n */\n @Transactional(readOnly = true)\n List<Chaos> findBySchedule(Schedule schedule);\n\n /**\n * Find all of the {@link Chaos}es related to a {@link Schedule}\n *\n * @param id the id of {@link Schedule} that {@link Chaos}es are related to\n * @return a collection of {@link Chaos}es related to the {@link Schedule}\n */\n @Transactional(readOnly = true)\n List<Chaos> findByScheduleId(Long id);\n\n}", "@Entity\npublic class Event {\n\n @JoinColumn(nullable = false)\n @ManyToOne\n @JsonIgnore\n private Chaos chaos;\n\n @Column(nullable = false)\n private Instant executedAt;\n\n @Column(nullable = false)\n @GeneratedValue\n @Id\n @JsonIgnore\n private Long id;\n\n @Column(nullable = false)\n @ElementCollection\n @OrderBy\n private List<Integer> terminatedInstances;\n\n @Column(nullable = false)\n private Integer totalInstanceCount;\n\n public Event(Chaos chaos, Instant executedAt, List<Integer> terminatedInstances, Integer totalInstanceCount) {\n this.chaos = chaos;\n this.executedAt = executedAt;\n this.terminatedInstances = terminatedInstances;\n this.totalInstanceCount = totalInstanceCount;\n }\n\n Event() {\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 Event event = (Event) o;\n return Objects.equals(this.chaos, event.chaos) &&\n Objects.equals(this.executedAt, event.executedAt) &&\n Objects.equals(this.id, event.id) &&\n Objects.equals(this.terminatedInstances, event.terminatedInstances) &&\n Objects.equals(this.totalInstanceCount, event.totalInstanceCount);\n }\n\n /**\n * Returns the chaos\n *\n * @return the chaos\n */\n public Chaos getChaos() {\n return this.chaos;\n }\n\n /**\n * Returns when the event was executed\n *\n * @return when the event was executed\n */\n public Instant getExecutedAt() {\n return this.executedAt;\n }\n\n /**\n * Returns the id\n *\n * @return the id\n */\n public Long getId() {\n return this.id;\n }\n\n /**\n * Sets the id\n *\n * @param id the id\n */\n public void setId(Long id) {\n this.id = id;\n }\n\n /**\n * Returns the number of instances terminated\n *\n * @return the number of instances terminated\n */\n public int getTerminatedInstanceCount() {\n return this.getTerminatedInstances().size();\n }\n\n /**\n * Returns the terminated instances\n *\n * @return the terminated instances\n */\n public List<Integer> getTerminatedInstances() {\n return this.terminatedInstances;\n }\n\n /**\n * Returns the total instance count\n *\n * @return the total instance count\n */\n public Integer getTotalInstanceCount() {\n return this.totalInstanceCount;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.chaos, this.executedAt, this.id, this.terminatedInstances, this.totalInstanceCount);\n }\n\n @Override\n public String toString() {\n return \"Event{\" +\n \"chaos=\" + this.chaos +\n \", executedAt=\" + this.executedAt +\n \", id=\" + this.id +\n \", terminatedInstances=\" + this.terminatedInstances +\n \", totalInstanceCount=\" + this.totalInstanceCount +\n '}';\n }\n\n}", "@Repository\npublic interface EventRepository extends JpaRepository<Event, Long> {\n\n /**\n * Find all of the {@link Event}s related to a {@link Chaos}\n *\n * @param chaos the {@link Chaos} that {@link Event}s are related to\n * @return a collection of {@link Event}s related to the {@link Chaos}\n */\n @Transactional(readOnly = true)\n List<Event> findByChaos(Chaos chaos);\n\n /**\n * Find all of the {@link Event}s that occurred before an {@link Instant}\n *\n * @param instant the {@link Instant} to find {@link Event}s before\n * @return a collection {@link Event}s that occurred before the {@link Instant}\n */\n @Transactional(readOnly = true)\n List<Event> findByExecutedAtBefore(Instant instant);\n\n}" ]
import io.pivotal.strepsirrhini.chaosloris.data.Application; import io.pivotal.strepsirrhini.chaosloris.data.Chaos; import io.pivotal.strepsirrhini.chaosloris.data.ChaosRepository; import io.pivotal.strepsirrhini.chaosloris.data.Event; import io.pivotal.strepsirrhini.chaosloris.data.EventRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Instant; import static io.pivotal.strepsirrhini.chaosloris.destroyer.FateEngine.Fate.THUMBS_DOWN;
/* * Copyright 2015-2018 the original author or authors. * * 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 io.pivotal.strepsirrhini.chaosloris.destroyer; final class StandardDestroyer implements Destroyer { private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ChaosRepository chaosRepository;
2
Lambda-3/DiscourseSimplification
src/main/java/org/lambda3/text/simplification/discourse/runner/discourse_tree/extraction/rules/NonRestrictiveRelativeClauseWhoWhichExtractor.java
[ "public enum Relation {\n\n UNKNOWN,\n\n // Coordinations\n UNKNOWN_COORDINATION, // the default for coordination\n CONTRAST,\n CAUSE_C,\n RESULT_C,\n LIST,\n DISJUNCTION,\n TEMPORAL_AFTER_C,\n TEMPORAL_BEFORE_C,\n\n // Subordinations\n UNKNOWN_SUBORDINATION, // the default for subordination\n ATTRIBUTION,\n BACKGROUND,\n CAUSE,\n RESULT,\n CONDITION,\n ELABORATION,\n PURPOSE,\n TEMPORAL_AFTER,\n TEMPORAL_BEFORE,\n\n // for sentence simplification\n NOUN_BASED,\n SPATIAL,\n TEMPORAL,\n TEMPORAL_TIME, // indicating a particular instance on a time scale (e.g. “Next Sunday 2 pm”).\n TEMPORAL_DURATION, // the amount of time between the two end-points of a time interval (e.g. “2 weeks\").\n TEMPORAL_DATE, // particular date (e.g. “On 7 April 2013”).\n TEMPORAL_SET, IDENTIFYING_DEFINITION, DESCRIBING_DEFINITION; // periodic temporal sets representing times that occur with some frequency (“Every Tuesday”).\n\n static {\n UNKNOWN_COORDINATION.coordination = true;\n CONTRAST.coordination = true;\n CAUSE_C.coordination = true;\n RESULT_C.coordination = true;\n LIST.coordination = true;\n DISJUNCTION.coordination = true;\n TEMPORAL_AFTER_C.coordination = true;\n TEMPORAL_BEFORE_C.coordination = true;\n\n CAUSE.coordinateVersion = CAUSE_C;\n RESULT.coordinateVersion = RESULT_C;\n TEMPORAL_AFTER.coordinateVersion = TEMPORAL_AFTER_C;\n TEMPORAL_BEFORE.coordinateVersion = TEMPORAL_BEFORE_C;\n\n CAUSE_C.subordinateVersion = CAUSE;\n RESULT_C.subordinateVersion = RESULT;\n TEMPORAL_AFTER_C.subordinateVersion = TEMPORAL_AFTER;\n TEMPORAL_BEFORE_C.subordinateVersion = TEMPORAL_BEFORE;\n\n CAUSE_C.inverse = RESULT_C;\n RESULT_C.inverse = CAUSE_C;\n TEMPORAL_AFTER_C.inverse = TEMPORAL_BEFORE_C;\n TEMPORAL_BEFORE_C.inverse = TEMPORAL_AFTER_C;\n CAUSE.inverse = RESULT;\n RESULT.inverse = CAUSE;\n TEMPORAL_AFTER.inverse = TEMPORAL_BEFORE;\n TEMPORAL_BEFORE.inverse = TEMPORAL_AFTER;\n }\n\n private boolean coordination;\n private Relation regular; // class of context span (in subordination) or right span (coordination)\n private Relation inverse; // class of core span (in subordination) or left span (coordination)\n private Relation coordinateVersion; // optional\n private Relation subordinateVersion; // optional\n\n Relation() {\n this.coordination = false;\n this.regular = this;\n this.inverse = this; // only used in coordinations\n this.coordinateVersion = null;\n this.subordinateVersion = null;\n }\n\n public boolean isCoordination() {\n return coordination;\n }\n\n public Relation getRegulatRelation() {\n return regular;\n }\n\n public Relation getInverseRelation() {\n return inverse;\n }\n\n public Optional<Relation> getCoordinateVersion() {\n return Optional.ofNullable(coordinateVersion);\n }\n\n public Optional<Relation> getSubordinateVersion() {\n return Optional.ofNullable(subordinateVersion);\n }\n}", "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 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.Arrays; 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.Relation; 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.model.Leaf; import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeException;
/* * ==========================License-Start============================= * DiscourseSimplification : SubordinationPostExtractor * * 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; /** * */ public class NonRestrictiveRelativeClauseWhoWhichExtractor extends ExtractionRule { @Override public Optional<Extraction> extract(Leaf leaf) throws ParseTreeException { TregexPattern p = TregexPattern.compile("ROOT <<: (S << (NP=head <, NP=np & < (/,/=comma $+ (SBAR=sbar <, (WHNP $+ S=s & <<: WP|WDT) & ?$+ /,/=comma2))))"); TregexMatcher matcher = p.matcher(leaf.getParseTree()); while (matcher.findAt(leaf.getParseTree())) { // the left, superordinate constituent List<Word> leftConstituentWords = new ArrayList<>(); leftConstituentWords.addAll(ParseTreeExtractionUtils.getPrecedingWords(leaf.getParseTree(), matcher.getNode("comma"), false)); if (matcher.getNode("comma2") != null) { leftConstituentWords.addAll(ParseTreeExtractionUtils.getFollowingWords(leaf.getParseTree(), matcher.getNode("comma2"), false)); } else { leftConstituentWords.addAll(ParseTreeExtractionUtils.getFollowingWords(leaf.getParseTree(), matcher.getNode("sbar"), false)); }
Leaf leftConstituent = new Leaf(getClass().getSimpleName(), WordsUtils.wordsToProperSentenceString(leftConstituentWords));
6
turbolocust/GZipper
src/main/java/org/gzipper/java/presentation/GZipper.java
[ "public enum OS {\r\n\r\n UNIX(\"Unix\", 3), WINDOWS(\"Windows\", 11);\r\n\r\n /**\r\n * The name of the operating system.\r\n */\r\n private final String _name;\r\n\r\n /**\r\n * The defined value as of {@link GzipParameters}.\r\n */\r\n private final int _value;\r\n\r\n OS(String name, int value) {\r\n _name = name;\r\n _value = value;\r\n }\r\n\r\n /**\r\n * Returns the name of the operating system.\r\n *\r\n * @return the name of the operating system.\r\n */\r\n public String getName() {\r\n return _name;\r\n }\r\n\r\n /**\r\n * Returns the value that is defined as of {@link GzipParameters}.\r\n *\r\n * @return the value that is defined as of {@link GzipParameters}.\r\n */\r\n public int getValue() {\r\n return _value;\r\n }\r\n}\r", "public class OperatingSystem {\r\n\r\n /**\r\n * The aggregated enumeration which represents the operating system.\r\n */\r\n protected final OS _operatingSystem;\r\n\r\n /**\r\n * Constructs a new instance of this class using the specified enumeration.\r\n *\r\n * @param operatingSystem the operating system to be aggregated.\r\n */\r\n public OperatingSystem(OS operatingSystem) {\r\n _operatingSystem = operatingSystem;\r\n }\r\n\r\n /**\r\n * Returns the default user directory of the system.\r\n *\r\n * @return the default user directory as string.\r\n */\r\n public String getDefaultUserDirectory() {\r\n return System.getProperty(\"user.home\");\r\n }\r\n\r\n /**\r\n * Returns the enumeration for the current operating system.\r\n *\r\n * @return the enumeration for the current operating system.\r\n */\r\n public OS getOsInfo() {\r\n return _operatingSystem;\r\n }\r\n}\r", "public final class AppUtils {\r\n\r\n private static final String JAVA_VERSION = determineJavaVersion();\r\n\r\n private AppUtils() {\r\n throw new AssertionError(\"Holds static members only\");\r\n }\r\n\r\n private static String determineJavaVersion() {\r\n\r\n String version = System.getProperty(\"java.version\");\r\n\r\n int pos = version.indexOf('.');\r\n if (pos != -1) { // found\r\n pos = version.indexOf('.', pos + 1);\r\n if (pos != -1) { // found\r\n version = version.substring(0, pos);\r\n }\r\n }\r\n\r\n return version;\r\n }\r\n\r\n /**\r\n * Determines the current Java version and returns the major version of Java\r\n * as string. For e.g. Java 8, this would return {@code 1.8}.\r\n *\r\n * @return the Java major version as string.\r\n */\r\n public static String getJavaVersion() {\r\n return JAVA_VERSION;\r\n }\r\n\r\n /**\r\n * Returns the resource path of the specified class as string. The file will\r\n * be stored in the system's temporary folder with the file extension\r\n * <b>.tmp</b>. The file will be deleted on JVM termination.\r\n *\r\n * @param clazz the class of which to receive the resource path.\r\n * @param name the name of the resource to receive.\r\n * @return the resource path of the specified class.\r\n * @throws URISyntaxException if URL conversion failed.\r\n */\r\n public static String getResource(Class<?> clazz, String name) throws URISyntaxException {\r\n\r\n String resource = null;\r\n\r\n final URL url = clazz.getResource(name);\r\n if (url.toString().startsWith(\"jar:\")) {\r\n\r\n String tempName = name.substring(name.lastIndexOf('/') + 1);\r\n\r\n try (BufferedInputStream bis = new BufferedInputStream(clazz.getResourceAsStream(name))) {\r\n\r\n File file = File.createTempFile(tempName, \".tmp\");\r\n try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {\r\n\r\n int readBytes;\r\n byte[] bytes = new byte[1024];\r\n\r\n while ((readBytes = bis.read(bytes)) != -1) {\r\n bos.write(bytes, 0, readBytes);\r\n }\r\n }\r\n\r\n resource = file.getPath();\r\n file.deleteOnExit();\r\n\r\n } catch (IOException ex) {\r\n Log.e(ex.getLocalizedMessage(), ex);\r\n }\r\n } else {\r\n resource = Paths.get(url.toURI()).toString();\r\n }\r\n\r\n return resource;\r\n }\r\n\r\n /**\r\n * Returns the decoded root path of the application's JAR-file.\r\n *\r\n * @param clazz the class of which to receive the root path.\r\n * @return the decoded root path of the JAR-file.\r\n */\r\n public static String getDecodedRootPath(Class<?> clazz) {\r\n\r\n String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();\r\n\r\n final File jarFile = new File(path);\r\n final int cutLength = determineCutLength(jarFile);\r\n\r\n String decPath; // to hold decoded path of JAR-file\r\n\r\n if (System.getProperty(\"os.name\").startsWith(\"Windows\")) {\r\n decPath = URLDecoder.decode(path.substring(1, path.length() - cutLength), StandardCharsets.UTF_8);\r\n } else {\r\n decPath = URLDecoder.decode(path.substring(0, path.length() - cutLength), StandardCharsets.UTF_8);\r\n }\r\n\r\n return decPath;\r\n }\r\n\r\n private static int determineCutLength(File f) {\r\n int cutLength = 0;\r\n if (!f.isDirectory()) {\r\n cutLength = f.getName().length();\r\n }\r\n return cutLength;\r\n }\r\n}\r", "public final class FileUtils {\n\n private FileUtils() {\n throw new AssertionError(\"Holds static members only\");\n }\n\n private static String getArchiveTypeExtensionName(String filename, List<ArchiveType> archiveTypes) {\n for (var archiveType : archiveTypes) {\n String[] extensionNames = archiveType.getExtensionNames(false);\n for (String extensionName : extensionNames) {\n if (filename.endsWith(extensionName)) return extensionName;\n }\n }\n\n return null;\n }\n\n private static String getArchiveTypeExtensionName(String filename) {\n\n var archiveTypes = ArchiveType.values();\n var tarArchiveTypes = new ArrayList<ArchiveType>();\n var nonTarArchiveTypes = new ArrayList<ArchiveType>();\n\n Arrays.stream(archiveTypes).forEach(type -> {\n if (type.getName().toLowerCase().startsWith(\"tar\")) {\n tarArchiveTypes.add(type);\n } else {\n nonTarArchiveTypes.add(type);\n }\n });\n\n String extensionName = getArchiveTypeExtensionName(filename, tarArchiveTypes);\n if (extensionName != null) return extensionName;\n\n return getArchiveTypeExtensionName(filename, nonTarArchiveTypes);\n }\n\n private static class SizeValueHolder {\n\n private long _size;\n\n SizeValueHolder() {\n _size = 0;\n }\n }\n\n /**\n * Validates the specified path, which has to exist.\n *\n * @param path the path as string to be validated.\n * @return true if file exists, false otherwise.\n */\n public static boolean isValid(String path) {\n final File file = new File(path);\n return file.exists();\n }\n\n /**\n * Validates the specified path, which has to be a normal file.\n *\n * @param path the path as string to be validated.\n * @return true if file is a file, false otherwise.\n */\n public static boolean isValidFile(String path) {\n final File file = new File(path);\n return file.isFile();\n }\n\n /**\n * Validates the specified path, which has to be the full name of a file\n * that shall be created and therefore does not exist yet.\n *\n * @param path the path as string to be validated.\n * @return true if the parent file is a directory, false otherwise.\n */\n public static boolean isValidOutputFile(String path) {\n final File file = new File(path);\n final File parentFile = file.getParentFile();\n return parentFile != null && parentFile.isDirectory() && !parentFile.getName().endsWith(\" \");\n }\n\n /**\n * Validates the specified path, which has to be the path of a directory.\n *\n * @param path the path as string to be validated.\n * @return true if file exists and is a directory, false otherwise.\n */\n public static boolean isValidDirectory(String path) {\n final File file = new File(path);\n return file.isDirectory();\n }\n\n /**\n * Checks whether the filename contains illegal characters.\n *\n * @param filename the name to be checked for illegal characters.\n * @return true if filename contains illegal characters, false otherwise.\n */\n public static boolean containsIllegalChars(String filename) {\n final File file = new File(filename);\n if (!file.isDirectory()) {\n final String name = file.getName();\n return name.contains(\"<\") || name.contains(\">\") || name.contains(\"/\")\n || name.contains(\"\\\\\") || name.contains(\"|\") || name.contains(\":\")\n || name.contains(\"*\") || name.contains(\"\\\"\") || name.contains(\"?\");\n }\n return filename.contains(\"<\") || filename.contains(\">\") || filename.contains(\"|\")\n || filename.contains(\"*\") || filename.contains(\"\\\"\") || filename.contains(\"?\");\n\n }\n\n /**\n * Concatenates two file names. Before doing so, a check will be performed\n * whether the first filename ends with a separator. If the separator is\n * missing it will be added.\n *\n * @param filename filename as string.\n * @param append the filename to be appended.\n * @return an empty string if either any of the parameters is {@code null}\n * or empty. Otherwise, the concatenated absolute path is returned.\n */\n public static String combine(String filename, String append) {\n if (StringUtils.isNullOrEmpty(filename) || StringUtils.isNullOrEmpty(append)) {\n return StringUtils.EMPTY;\n }\n\n filename = normalize(filename);\n final String absolutePath;\n\n if (filename.endsWith(\"/\")) {\n absolutePath = filename;\n } else {\n absolutePath = filename + \"/\";\n }\n return absolutePath + append;\n }\n\n /**\n * Returns the file name extension(s) of a specified filename.\n *\n * @param filename the name of the file as string.\n * @return file name extension(s) including period or an empty string if the\n * specified filename has no file name extension.\n */\n public static String getExtension(String filename) {\n return getExtension(filename, false);\n }\n\n /**\n * Returns the file name extension(s) of a specified filename.\n *\n * @param filename the name of the file as string.\n * @param considerArchiveTypeExtensions true to consider file name extensions of known archive types.\n * @return file name extension(s) including period or an empty string if the\n * specified filename has no file name extension.\n */\n public static String getExtension(String filename, boolean considerArchiveTypeExtensions) {\n final String normalizedFilename = normalize(filename);\n\n if (considerArchiveTypeExtensions) {\n String extensionName = getArchiveTypeExtensionName(normalizedFilename);\n if (extensionName != null) return extensionName;\n }\n\n final int lastIndexOfFileSeparator = normalizedFilename.lastIndexOf('/');\n final int indexOfPeriod = normalizedFilename.indexOf('.', lastIndexOfFileSeparator);\n\n return indexOfPeriod > 0 ? normalizedFilename.substring(indexOfPeriod) : StringUtils.EMPTY;\n }\n\n /**\n * Returns the name of the specified filename including its file name extension.\n *\n * @param filename the name of the file as string.\n * @return the name of the file including its file name extension.\n */\n public static String getName(String filename) {\n filename = normalize(filename);\n int lastSeparatorIndex = filename.lastIndexOf('/');\n\n if (lastSeparatorIndex == -1) {\n lastSeparatorIndex = 0; // no separator present\n } else {\n ++lastSeparatorIndex;\n }\n\n return filename.substring(lastSeparatorIndex);\n }\n\n /**\n * Returns the display name of the specified filename without its extension.\n *\n * @param filename the name of the file as string.\n * @return the display name of the file without its file name extension.\n */\n public static String getDisplayName(String filename) {\n final String normalizedFilename = normalize(filename);\n\n int lastIndexOfFileSeparator = normalizedFilename.lastIndexOf('/');\n int lastIndexOfPeriod = filename.lastIndexOf('.');\n\n if (lastIndexOfFileSeparator == -1) {\n lastIndexOfFileSeparator = 0; // no separator present\n } else {\n ++lastIndexOfFileSeparator;\n }\n\n if (lastIndexOfPeriod == -1) {\n lastIndexOfPeriod = normalizedFilename.length();\n }\n\n return normalizedFilename.substring(lastIndexOfFileSeparator, lastIndexOfPeriod);\n }\n\n /**\n * Returns the canonical path if possible or otherwise the absolute path.\n *\n * @param file the file of which to get the path of.\n * @return the canonical path if possible or otherwise the absolute path.\n */\n public static String getPath(File file) {\n try {\n return file.getCanonicalPath();\n } catch (IOException ex) {\n Log.e(\"Canonical path could not be computed\", ex);\n return file.getAbsolutePath();\n }\n }\n\n /**\n * Returns the full name of the parent directory of the specified file name.\n *\n * @param filename the file name of which to receive the parent directory.\n * @return the parent directory of the specified file name or an empty\n * string if the specified file name does not have a parent.\n */\n public static String getParent(String filename) {\n final File file = new File(filename);\n String parent = file.getParent();\n return parent != null ? parent : StringUtils.EMPTY;\n }\n\n /**\n * Copies a file from the specified source to destination. If no copy\n * options are specified, the file at the destination will not be replaced\n * in case it already exists.\n *\n * @param src the source path.\n * @param dst the destination path.\n * @param options optional copy options.\n * @throws IOException if an I/O error occurs.\n */\n public static void copy(String src, String dst, CopyOption... options) throws IOException {\n if (options == null) {\n options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES};\n }\n Files.copy(Paths.get(src), Paths.get(dst), options);\n }\n\n /**\n * Normalizes the specified path. After the normalization, all file separators are equal to {@code /}.\n *\n * @param path the path to be normalized.\n * @return a normalized version of the specified path.\n */\n public static String normalize(String path) {\n return path.replace('\\\\', '/');\n }\n\n /**\n * Returns the file size of the specified file.\n *\n * @param file the file whose size is to be returned.\n * @param filter the filter to be applied.\n * @return the size of the file or {@code 0} if the specified predicate\n * evaluates to {@code false}.\n */\n public static long fileSize(File file, Predicate<String> filter) {\n return filter.test(file.getName()) ? file.length() : 0;\n }\n\n /**\n * Traverses the specified path and returns the size of all children.\n *\n * @param path the path to be traversed.\n * @param filter the filter to be applied.\n * @return the size of all children.\n */\n public static long fileSizes(Path path, Predicate<String> filter) {\n\n final SizeValueHolder holder = new SizeValueHolder();\n\n try {\n Files.walkFileTree(path, new SimpleFileVisitor<>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {\n String name = file.getFileName().toString();\n if (filter.test(name)) {\n holder._size += attrs.size();\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException ex) {\n Log.e(file + \" skipped. Progress may be inaccurate\", ex);\n return FileVisitResult.CONTINUE; // skip folder that can't be traversed\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException ex) {\n if (ex != null) {\n Log.e(dir + \" could not be traversed. Progress may be inaccurate\", ex);\n }\n return FileVisitResult.CONTINUE;\n }\n });\n } catch (IOException ex) {\n throw new AssertionError(ex);\n }\n\n return holder._size;\n }\n\n /**\n * Generates a unique file name using the specified parameters.\n *\n * @param path the file path including only the directory.\n * @param name the name of the file of which to generate a unique version.\n * @return a unique filename that consists of the path, name, suffix and file name extension (if any).\n */\n public static String generateUniqueFilename(String path, String name) {\n return generateUniqueFilename(path, name, 1);\n }\n\n /**\n * Generates a unique file name using the specified parameters.\n *\n * @param path the file path including only the directory.\n * @param name the name of the file of which to generate a unique version.\n * @param beginSuffix the suffix to begin with (will be incremented).\n * @return a unique filename that consists of the path, name, suffix and file name extension (if any).\n */\n public static String generateUniqueFilename(String path, String name, int beginSuffix) {\n final String extension = getExtension(name, true);\n\n if (!extension.isEmpty()) {\n name = getDisplayName(name);\n }\n\n return generateUniqueFilename(path, name, extension, beginSuffix);\n }\n\n /**\n * Generates a unique file name using the specified parameters.\n *\n * @param path the file path including only the directory.\n * @param name the name of the file of which to generate a unique version.\n * @param ext the name of the file extension.\n * @return a unique filename that consists of the path, name, suffix and file name extension.\n */\n public static String generateUniqueFilename(String path, String name, String ext) {\n return generateUniqueFilename(path, name, ext, 1);\n }\n\n /**\n * Generates a unique file name using the specified parameters.\n *\n * @param path the file path including only the directory.\n * @param name the name of the file of which to generate a unique version.\n * @param ext the name of the file extension.\n * @param beginSuffix the suffix to begin with (will be incremented). This\n * parameter will be ignored if its value is less or equal zero.\n * @return a unique filename that consists of the path, name, suffix and file name extension.\n */\n public static String generateUniqueFilename(String path, String name, String ext, int beginSuffix) {\n path = normalize(path);\n name = normalize(name);\n\n int suffix = beginSuffix > 0 ? beginSuffix : 1; // to be appended\n boolean isFirst = true; // to ignore suffix on first check\n final StringBuilder filename = new StringBuilder();\n\n if (ext.startsWith(\"*\")) { // ignore asterisk if any\n ext = ext.substring(1);\n }\n\n final String trimmedPath = path.trim();\n String uniqueFilename = FileUtils.combine(trimmedPath, name + ext);\n\n if (!FileUtils.isValid(uniqueFilename)) return uniqueFilename; // return as it is if not exists\n\n do { // as long as file exists\n if (isFirst && beginSuffix <= 0) {\n filename.append(name).append(ext);\n } else {\n filename.append(name).append(suffix).append(ext);\n ++suffix;\n }\n isFirst = false;\n uniqueFilename = FileUtils.combine(trimmedPath, filename.toString());\n filename.setLength(0); // clear\n } while (FileUtils.isValidFile(uniqueFilename));\n\n return uniqueFilename;\n }\n}", "public abstract class BaseController implements Initializable {\n\n //<editor-fold desc=\"Static members\">\n\n /**\n * The default archive name of an archive if not explicitly specified.\n */\n protected static final String DEFAULT_ARCHIVE_NAME = \"gzipper_out\";\n\n /**\n * A set with all the stages currently open.\n */\n private static final Set<Stage> _stages = new HashSet<>();\n\n /**\n * Returns all currently open stages.\n *\n * @return all currently open stages.\n */\n public static Set<Stage> getStages() {\n return _stages;\n }\n\n /**\n * The icon image used for each stage.\n */\n protected static Image iconImage;\n\n /**\n * Returns the icon image that is to be used for each stage.\n *\n * @return the icon image that is to be used for each stage.\n */\n public static Image getIconImage() {\n var resource = BaseController.class.getResource(\"/images/icon_32.png\");\n return iconImage = new Image(resource.toExternalForm());\n }\n\n //</editor-fold>\n\n /**\n * The aggregated primary stage.\n */\n protected Stage primaryStage;\n\n /**\n * Sets the primary stage of this controller.\n *\n * @param primaryStage the primary stage to be set.\n */\n public void setPrimaryStage(Stage primaryStage) {\n this.primaryStage = primaryStage;\n }\n\n /**\n * The aggregated host services. May be {@code null} if not set.\n */\n protected HostServices hostServices;\n\n /**\n * The currently active theme.\n */\n protected CSS.Theme theme;\n\n /**\n * Constructs a controller with the specified CSS theme.\n *\n * @param theme the {@link CSS} theme to be applied.\n */\n public BaseController(CSS.Theme theme) {\n this.theme = theme;\n }\n\n /**\n * Constructs a controller with the specified CSS theme and host services.\n *\n * @param theme the {@link CSS} theme to be applied.\n * @param hostServices the host services to be aggregated.\n */\n public BaseController(CSS.Theme theme, HostServices hostServices) {\n this.theme = theme;\n this.hostServices = hostServices;\n }\n\n /**\n * Loads the alternative theme (dark theme).\n *\n * @param enableTheme true to enable, false to disable the alternative theme.\n */\n protected void loadAlternativeTheme(boolean enableTheme) {\n this.theme = enableTheme ? CSS.Theme.DARK_THEME : CSS.Theme.getDefault();\n _stages.forEach((stage) -> CSS.load(this.theme, stage.getScene()));\n }\n\n /**\n * Closes the primary stage of this controller.\n */\n protected void close() {\n primaryStage.close();\n }\n\n /**\n * Exits the application.\n */\n protected void exit() {\n close();\n Platform.exit();\n System.exit(0);\n }\n}", "public final class HashViewController extends BaseController implements Interruptible {\n\n /**\n * Default buffer size when reading large files. Currently 1 mebibyte(s).\n */\n private static final int BUFFER_SIZE = 1024 * 1024;\n\n /**\n * Threshold at which {@link #BUFFER_SIZE} will be used. Currently set to 100 Mebibytes.\n */\n private static final int LARGE_FILE_THRESHOLD = 1024 * 1024 * 100;\n\n /**\n * The currently selected {@link MessageDigestAlgorithm}.\n */\n private final ObjectProperty<MessageDigestAlgorithm> _algorithm;\n\n /**\n * Set to remember results for {@link #_resultTable} to avoid duplicates.\n */\n private final Set<NamedMessageDigestResult> _models = new HashSet<>();\n\n /**\n * Handler used to execute tasks.\n */\n private final TaskHandler _taskHandler;\n\n /**\n * If set to false the currently running task will be interrupted.\n */\n private volatile boolean _isAlive = false;\n\n @FXML\n private TableView<HashViewTableModel> _resultTable;\n @FXML\n private TableColumn<HashViewTableModel, String> _fileNameColumn;\n @FXML\n private TableColumn<HashViewTableModel, String> _filePathColumn;\n @FXML\n private TableColumn<HashViewTableModel, String> _hashValueColumn;\n @FXML\n private ComboBox<MessageDigestAlgorithm> _algorithmComboBox;\n @FXML\n private Button _addFilesButton;\n @FXML\n private Button _closeButton;\n @FXML\n private CheckBox _appendFilesCheckBox;\n @FXML\n private CheckBox _lowerCaseCheckBox;\n @FXML\n private ProgressIndicator _progressIndicator;\n\n /**\n * Constructs a controller for the hash view with the specified CSS theme.\n *\n * @param theme the {@link CSS} theme to apply.\n */\n public HashViewController(CSS.Theme theme) {\n super(theme);\n _algorithm = new SimpleObjectProperty<>();\n _taskHandler = new TaskHandler(TaskHandler.ExecutorType.QUEUED);\n }\n\n @FXML\n void handleAddFilesButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_addFilesButton)) {\n final FileChooser fc = new FileChooser();\n fc.setTitle(I18N.getString(\"browseForFiles.text\"));\n\n final List<File> selectedFiles\n = fc.showOpenMultipleDialog(primaryStage);\n computeAndAppend(selectedFiles); // performs null check\n GUIUtils.autoFitTable(_resultTable);\n }\n }\n\n @FXML\n void handleLowerCaseCheckBoxAction(ActionEvent evt) {\n if (evt.getSource().equals(_lowerCaseCheckBox)) {\n _resultTable.getItems().forEach(item -> item.setHashValue(setCase(item.getHashValue())));\n _resultTable.refresh();\n }\n }\n\n @FXML\n void handleAlgorithmComboBoxAction(ActionEvent evt) {\n if (evt.getSource().equals(_algorithmComboBox)) {\n final int size = _resultTable.getItems().size();\n final List<File> files = new ArrayList<>(size);\n _resultTable.getItems().stream()\n .map((model) -> new File(model.getFilePath()))\n .forEachOrdered(files::add);\n clearRows();\n computeAndAppend(files);\n GUIUtils.autoFitTable(_resultTable);\n }\n }\n\n @FXML\n void handleCloseButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_closeButton)) {\n close();\n }\n }\n\n @FXML\n void handleResultTableOnDragOver(DragEvent evt) {\n if (evt.getGestureSource() != _resultTable\n && evt.getDragboard().hasFiles()) {\n evt.acceptTransferModes(TransferMode.COPY_OR_MOVE);\n }\n evt.consume();\n }\n\n @FXML\n void handleResultTableOnDragDropped(DragEvent evt) {\n final Dragboard dragboard = evt.getDragboard();\n boolean success = false;\n if (dragboard.hasFiles()) {\n computeAndAppend(dragboard.getFiles());\n GUIUtils.autoFitTable(_resultTable);\n success = true;\n }\n evt.setDropCompleted(success);\n evt.consume();\n }\n\n private void initTableCells() {\n _fileNameColumn.setCellValueFactory(data\n -> new ReadOnlyStringWrapper(data.getValue().getFileName()));\n _filePathColumn.setCellValueFactory(data\n -> new ReadOnlyStringWrapper(data.getValue().getFilePath()));\n _hashValueColumn.setCellValueFactory(data\n -> new ReadOnlyStringWrapper(data.getValue().getHashValue()));\n setCellFactory(_fileNameColumn);\n setCellFactory(_filePathColumn);\n setCellFactory(_hashValueColumn);\n }\n\n private void setCellFactory(TableColumn<HashViewTableModel, String> column) {\n column.setCellFactory((TableColumn<HashViewTableModel, String> col) -> {\n final TableCell<HashViewTableModel, String> cell = new TableCell<>() {\n @Override\n protected void updateItem(String value, boolean empty) {\n super.updateItem(value, empty);\n setText(empty ? null : value);\n }\n };\n\n // programmatically set up context menu\n final ContextMenu ctxMenu = new ContextMenu();\n final MenuItem copyMenuItem = new MenuItem(I18N.getString(\"copy.text\"));\n final MenuItem copyRowMenuItem = new MenuItem(I18N.getString(\"copyRow.text\"));\n final MenuItem copyAllMenuItem = new MenuItem(I18N.getString(\"copyAll.text\"));\n final MenuItem compareToMenuItem = new MenuItem(I18N.getString(\"compareTo.text\"));\n\n copyMenuItem.setOnAction(evt -> { // copy\n if (evt.getSource().equals(copyMenuItem)) {\n final Clipboard clipboard = Clipboard.getSystemClipboard();\n final ClipboardContent content = new ClipboardContent();\n content.putString(cell.getItem());\n clipboard.setContent(content);\n }\n });\n\n copyRowMenuItem.setOnAction(evt -> { // copy row\n if (evt.getSource().equals(copyRowMenuItem)) {\n final Clipboard clipboard = Clipboard.getSystemClipboard();\n final ClipboardContent content = new ClipboardContent();\n final StringBuilder sb = new StringBuilder();\n final HashViewTableModel model = cell.getTableRow().getItem();\n sb.append(model.getFileName()).append(\"\\t\")\n .append(model.getFilePath()).append(\"\\t\")\n .append(model.getHashValue());\n content.putString(sb.toString());\n clipboard.setContent(content);\n }\n });\n\n copyAllMenuItem.setOnAction(evt -> { // copy all\n if (evt.getSource().equals(copyAllMenuItem)) {\n final Clipboard clipboard = Clipboard.getSystemClipboard();\n final ClipboardContent content = new ClipboardContent();\n final StringBuilder sb = new StringBuilder();\n _resultTable.getItems().forEach((model) ->\n sb.append(model.getFileName()).append(\"\\t\")\n .append(model.getFilePath()).append(\"\\t\")\n .append(model.getHashValue()).append(\"\\n\"));\n content.putString(sb.toString());\n clipboard.setContent(content);\n }\n });\n\n compareToMenuItem.setOnAction(evt -> { // compare to\n if (evt.getSource().equals(compareToMenuItem)) {\n final Optional<String> result = Dialogs.showTextInputDialog(\n I18N.getString(\"compareTo.text\"),\n I18N.getString(\"compareToDialogHeader.text\"),\n I18N.getString(\"hashValue.text\"),\n theme, iconImage);\n if (result.isPresent() && !result.get().isEmpty()) {\n final String message;\n final int delay = 3600;\n if (result.get().equalsIgnoreCase(cell.getItem())) {\n message = I18N.getString(\"equal.text\").toUpperCase();\n Toast.show(primaryStage, message, Color.GREEN, delay);\n } else {\n message = I18N.getString(\"notEqual.text\").toUpperCase();\n Toast.show(primaryStage, message, Color.RED, delay);\n }\n }\n }\n });\n\n ctxMenu.getItems().addAll(copyMenuItem, copyRowMenuItem, copyAllMenuItem,\n new SeparatorMenuItem(), compareToMenuItem);\n\n cell.contextMenuProperty().bind(Bindings\n .when(cell.emptyProperty())\n .then((ContextMenu) null)\n .otherwise(ctxMenu));\n\n return cell;\n });\n }\n\n private String setCase(String value) {\n return _lowerCaseCheckBox.isSelected()\n ? value.toLowerCase()\n : value.toUpperCase();\n }\n\n /**\n * Computes the hash value of the specified file and appends the result as a\n * row to {@link #_resultTable}.\n *\n * @param file the file of which to compute and append the hashing result.\n */\n private void computeAndAppend(File file) {\n try {\n MessageDigestResult result;\n if (file.isFile()) { // folders are not supported\n final MessageDigestAlgorithm algorithm = _algorithm.get();\n if (file.length() > LARGE_FILE_THRESHOLD) {\n final MessageDigestProvider provider\n = MessageDigestProvider.createProvider(algorithm);\n try (FileInputStream fis = new FileInputStream(file);\n BufferedInputStream bis = new BufferedInputStream(fis, BUFFER_SIZE)) {\n final byte[] buffer = new byte[BUFFER_SIZE];\n int readBytes;\n while ((readBytes = bis.read(buffer, 0, buffer.length)) > 0) {\n provider.updateHash(buffer, 0, readBytes);\n }\n }\n result = provider.computeHash();\n } else {\n byte[] bytes = Files.readAllBytes(file.toPath());\n result = MessageDigestProvider.computeHash(bytes, algorithm);\n }\n\n final String path = FileUtils.getPath(file);\n NamedMessageDigestResult namedResult = new NamedMessageDigestResult(result, path);\n appendColumn(namedResult, file);\n }\n } catch (IOException | NoSuchAlgorithmException ex) {\n Log.e(\"Error reading file\", ex);\n final MessageDigestResult result = new MessageDigestResult();\n appendColumn(new NamedMessageDigestResult(result, StringUtils.EMPTY), file);\n }\n }\n\n /**\n * Starts new task if none is already active to compute the hash values for\n * the specified list of files and to eventually append the results to\n * {@link #_resultTable}. A task is being used to avoid a non-responsive UI.\n *\n * @param files list of files to be processed.\n */\n @SuppressWarnings({\"SleepWhileInLoop\", \"BusyWait\"})\n private void computeAndAppend(final List<File> files) {\n if (_isAlive || ListUtils.isNullOrEmpty(files)) {\n return;\n }\n // clear table if append is deactivated\n if (!_appendFilesCheckBox.isSelected()) {\n clearRows();\n }\n\n final Task<Boolean> task = new Task<>() {\n @Override\n protected Boolean call() {\n for (File file : files) {\n if (!_isAlive) {\n return false;\n }\n computeAndAppend(file);\n }\n return true;\n }\n };\n\n // set up event handlers\n task.setOnSucceeded(this::onTaskCompleted);\n task.setOnFailed(this::onTaskCompleted);\n\n bindUIControls(task);\n _isAlive = true;\n _taskHandler.submit(task);\n\n // wait for task to complete\n while (task.isRunning()) {\n try {\n Thread.sleep(10);\n } catch (InterruptedException ex) {\n Log.e(\"Task interrupted\", ex);\n Thread.currentThread().interrupt();\n }\n }\n }\n\n private void onTaskCompleted(Event evt) {\n Platform.runLater(this::unbindUIControls);\n _isAlive = false;\n evt.consume();\n }\n\n private void bindUIControls(Task<?> task) {\n\n final ReadOnlyBooleanProperty running = task.runningProperty();\n\n _addFilesButton.disableProperty().bind(running);\n _algorithmComboBox.disableProperty().bind(running);\n _appendFilesCheckBox.disableProperty().bind(running);\n _lowerCaseCheckBox.disableProperty().bind(running);\n _progressIndicator.disableProperty().bind(Bindings.not(running));\n _progressIndicator.visibleProperty().bind(running);\n }\n\n private void unbindUIControls() {\n _addFilesButton.disableProperty().unbind();\n _algorithmComboBox.disableProperty().unbind();\n _appendFilesCheckBox.disableProperty().unbind();\n _lowerCaseCheckBox.disableProperty().unbind();\n _progressIndicator.disableProperty().unbind();\n _progressIndicator.visibleProperty().unbind();\n }\n\n /**\n * Should always be called in favor of {@code table.getItems().clear()}\n * since this method will also clear the set of added models, which exists\n * to avoid duplicates in table view.\n */\n private void clearRows() {\n _resultTable.getItems().clear();\n _models.clear();\n }\n\n private void appendColumn(NamedMessageDigestResult namedResult, File file) {\n if (!_models.contains(namedResult)) {\n final HashViewTableModel model;\n if (!namedResult.getMessageDigestResult().isEmpty()) {\n model = new HashViewTableModel(\n file.getName(),\n FileUtils.getPath(file),\n setCase(namedResult.getMessageDigestResult().toString()));\n } else {\n model = new HashViewTableModel(\n file.getName(),\n FileUtils.getPath(file),\n I18N.getString(\"errorReadingFile.text\"));\n }\n Platform.runLater(() -> {\n _resultTable.getItems().add(model);\n _models.add(namedResult);\n });\n }\n }\n\n @Override\n public void initialize(URL location, ResourceBundle resources) {\n // set up combo box\n final MessageDigestAlgorithm selectedAlgorithm\n = MessageDigestAlgorithm.SHA_256;\n _algorithmComboBox.getItems().addAll(MessageDigestAlgorithm.values());\n _algorithmComboBox.valueProperty().bindBidirectional(_algorithm);\n _algorithm.setValue(selectedAlgorithm);\n\n // set up table\n initTableCells();\n final String placeholderText = I18N.getString(\"addFilesDragDrop.text\");\n _resultTable.setPlaceholder(new Label(placeholderText));\n }\n\n @Override\n public void interrupt() {\n _isAlive = false;\n }\n}", "public final class MainViewController extends BaseController {\n\n //<editor-fold desc=\"Attributes\">\n\n /**\n * Key constant used to access the properties map for menu items.\n */\n private static final String COMPRESSION_LEVEL_KEY = \"compressionLevel\";\n\n /**\n * Logger for UI named {@code MainViewController.class.getName()}.\n */\n public static final Logger LOGGER = Logger.getLogger(MainViewController.class.getName());\n\n /**\n * Handler used to execute tasks.\n */\n private final TaskHandler _taskHandler;\n\n /**\n * Map consisting of {@link Future} objects representing the currently\n * active tasks.\n */\n private final ConcurrentMap<Integer, Future<?>> _activeTasks;\n\n /**\n * The currently active state.\n */\n private ArchivingState _state;\n\n /**\n * The output file or directory that has been selected by the user.\n */\n private File _outputFile;\n\n /**\n * A list consisting of the files that have been selected by the user. These\n * can either be files to be packed or archives to be extracted.\n */\n private List<File> _selectedFiles;\n\n /**\n * The archive name specified by user.\n */\n private String _archiveName;\n\n /**\n * The file extension of the archive type.\n */\n private String _archiveFileExtension;\n\n /**\n * The compression level. Initialized with default compression level.\n */\n private int _compressionLevel;\n\n /**\n * True if user wishes to put each file into a separate archive.\n */\n private boolean _putIntoSeparateArchives;\n\n //</editor-fold>\n\n //<editor-fold desc=\"FXML attributes\">\n\n @FXML\n private MenuItem _applyFilterMenuItem;\n @FXML\n private MenuItem _resetFilterMenuItem;\n @FXML\n private MenuItem _noCompressionMenuItem;\n @FXML\n private MenuItem _bestSpeedCompressionMenuItem;\n @FXML\n private MenuItem _defaultCompressionMenuItem;\n @FXML\n private MenuItem _bestCompressionMenuItem;\n @FXML\n private MenuItem _closeMenuItem;\n @FXML\n private MenuItem _deleteMenuItem;\n @FXML\n private MenuItem _addManyFilesMenuItem;\n @FXML\n private MenuItem _hashingMenuItem;\n @FXML\n private MenuItem _resetAppMenuItem;\n @FXML\n private MenuItem _aboutMenuItem;\n @FXML\n private RadioButton _compressRadioButton;\n @FXML\n private RadioButton _decompressRadioButton;\n @FXML\n private TextArea _textArea;\n @FXML\n private CheckMenuItem _enableLoggingCheckMenuItem;\n @FXML\n private CheckMenuItem _enableDarkThemeCheckMenuItem;\n @FXML\n private TextField _outputPathTextField;\n @FXML\n private ComboBox<ArchiveType> _archiveTypeComboBox;\n @FXML\n private Button _startButton;\n @FXML\n private Button _abortButton;\n @FXML\n private Button _selectFilesButton;\n @FXML\n private Button _saveAsButton;\n @FXML\n private ProgressBar _progressBar;\n @FXML\n private Text _progressText;\n\n //</editor-fold>\n\n /**\n * Constructs a controller for Main View with the specified CSS theme and\n * host services.\n *\n * @param theme the {@link CSS} theme to be applied.\n * @param hostServices the host services to aggregate.\n */\n public MainViewController(CSS.Theme theme, HostServices hostServices) {\n super(theme, hostServices);\n _archiveName = DEFAULT_ARCHIVE_NAME;\n _compressionLevel = Deflater.DEFAULT_COMPRESSION;\n _activeTasks = new ConcurrentHashMap<>();\n _taskHandler = new TaskHandler(TaskHandler.ExecutorType.CACHED);\n Log.i(\"Default archive name set to: {0}\", _archiveName, false);\n }\n\n //<editor-fold desc=\"FXML methods\">\n\n @FXML\n void handleApplyFilterMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_applyFilterMenuItem)) {\n final Optional<String> result = Dialogs.showPatternInputDialog(theme, getIconImage());\n if (result.isPresent()) {\n if (!result.get().isEmpty()) {\n final Pattern pattern = Pattern.compile(result.get());\n _state.setFilterPredicate(new PatternPredicate(pattern));\n Log.i(I18N.getString(\"filterApplied.text\", result.get()), true);\n } else {\n resetFilter();\n }\n }\n }\n }\n\n @FXML\n void handleResetFilterMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_resetFilterMenuItem)) {\n resetFilter();\n }\n }\n\n @FXML\n void handleCompressionLevelMenuItemAction(ActionEvent evt) {\n final MenuItem selectedItem = (MenuItem) evt.getSource();\n final Object compressionStrength = selectedItem.getProperties().get(COMPRESSION_LEVEL_KEY);\n if (compressionStrength != null) {\n _compressionLevel = (int) compressionStrength;\n final String msg = I18N.getString(\"compressionLevelChange.text\") + \" \";\n Log.i(\"{0}{1}\", true, msg, selectedItem.getText());\n }\n }\n\n @FXML\n void handleCloseMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_closeMenuItem)) {\n cancelActiveTasks();\n exit();\n }\n }\n\n @FXML\n void handleDeleteMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_deleteMenuItem)) {\n final Optional<ButtonType> result = Dialogs\n .showConfirmationDialog(I18N.getString(\"clearText.text\"),\n I18N.getString(\"clearTextConfirmation.text\"),\n I18N.getString(\"confirmation.text\"), theme, getIconImage());\n\n if (result.isPresent() && result.get() == ButtonType.YES) {\n _textArea.clear();\n _textArea.setText(\"run:\\n\");\n }\n }\n }\n\n @FXML\n void handleAddManyFilesMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_addManyFilesMenuItem)) {\n final DropViewController dropViewController = ViewControllers.showDropView(theme);\n final List<String> filePaths = dropViewController.getAddresses();\n if (!ListUtils.isNullOrEmpty(filePaths)) {\n _putIntoSeparateArchives = dropViewController.isPutInSeparateArchives();\n final int size = filePaths.size();\n _selectedFiles = new ArrayList<>(size);\n _startButton.setDisable(false);\n if (size > 10) { // threshold, to avoid flooding text area\n filePaths.forEach((filePath) -> _selectedFiles.add(new File(filePath)));\n Log.i(I18N.getString(\"manyFilesSelected.text\"), true, size);\n } else { // log files in detail\n filePaths.stream()\n .peek((filePath) -> _selectedFiles.add(new File(filePath)))\n .forEachOrdered((filePath) -> Log.i(\"{0}: {1}\",\n true, I18N.getString(\"fileSelected.text\"), filePath));\n }\n } else {\n Log.i(I18N.getString(\"noFilesSelected.text\"), true);\n _startButton.setDisable(ListUtils.isNullOrEmpty(_selectedFiles));\n }\n }\n }\n\n @FXML\n void handleHashingMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_hashingMenuItem)) {\n ViewControllers.showHashView(theme);\n }\n }\n\n @FXML\n void handleResetAppMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_resetAppMenuItem)) {\n final Optional<ButtonType> result = Dialogs\n .showConfirmationDialog(I18N.getString(\"resetApp.text\"),\n I18N.getString(\"resetAppConfirmation.text\"),\n I18N.getString(\"confirmation.text\"), theme, getIconImage());\n if (result.isPresent() && result.get() == ButtonType.YES) {\n Settings.getInstance().restoreDefaults();\n }\n }\n }\n\n @FXML\n void handleAboutMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_aboutMenuItem)) {\n ViewControllers.showAboutView(theme, hostServices);\n }\n }\n\n @FXML\n void handleStartButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_startButton)) {\n try {\n if (_state.checkUpdateOutputPath()) {\n final String outputPathText = _outputPathTextField.getText();\n final File outputFile = new File(outputPathText);\n final String outputPath = FileUtils.getPath(outputFile);\n\n checkUpdateOutputFileAndArchiveName(outputPath);\n\n final String recentPath = FileUtils.getParent(outputPath);\n Settings.getInstance().setProperty(\"recentPath\", recentPath);\n final ArchiveType archiveType = _archiveTypeComboBox.getValue();\n for (ArchiveOperation operation : _state.initOperation(archiveType)) {\n Log.i(\"Operation started using the following archive info: {0}\",\n operation.getArchiveInfo().toString(), false);\n _state.performOperation(operation);\n }\n } else {\n Log.w(I18N.getString(\"invalidOutputPath.text\"), true);\n }\n } catch (GZipperException ex) {\n Log.e(ex.getLocalizedMessage(), ex);\n }\n }\n }\n\n @FXML\n void handleAbortButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_abortButton)) {\n cancelActiveTasks();\n }\n }\n\n @FXML\n void handleSelectFilesButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_selectFilesButton)) {\n final FileChooser fc = new FileChooser();\n if (_compressRadioButton.isSelected()) {\n fc.setTitle(I18N.getString(\"browseForFiles.text\"));\n } else {\n fc.setTitle(I18N.getString(\"browseForArchive.text\"));\n _state.applyExtensionFilters(fc);\n }\n\n final List<File> selectedFiles = fc.showOpenMultipleDialog(primaryStage);\n\n String message;\n if (selectedFiles != null) {\n _putIntoSeparateArchives = false;\n _startButton.setDisable(false);\n int size = selectedFiles.size();\n message = I18N.getString(\"filesSelected.text\", size);\n if (size <= 10) {\n selectedFiles.forEach((file) -> { // log the path of each selected file\n Log.i(\"{0}: \\\"{1}\\\"\", true,\n I18N.getString(\"fileSelected.text\"),\n FileUtils.getPath(file));\n });\n }\n _selectedFiles = selectedFiles;\n } else {\n message = I18N.getString(\"noFilesSelected.text\");\n _startButton.setDisable(ListUtils.isNullOrEmpty(_selectedFiles));\n }\n Log.i(message, true);\n }\n }\n\n @FXML\n void handleSaveAsButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_saveAsButton)) {\n final File file = pickFileToBeSaved();\n if (file != null) {\n updateSelectedFile(file);\n String path = FileUtils.getPath(file);\n if (!file.isDirectory() && FileUtils.getExtension(path).isEmpty()) {\n path += _archiveFileExtension;\n }\n setOutputPath(path);\n Log.i(\"Output file set to: {0}\", FileUtils.getPath(file), false);\n }\n }\n }\n\n @FXML\n void handleModeRadioButtonAction(ActionEvent evt) {\n if (evt.getSource().equals(_compressRadioButton)) {\n performModeRadioButtonAction(true, \"browseForFiles.text\", \"saveAsArchive.text\");\n } else if (evt.getSource().equals(_decompressRadioButton)) {\n performModeRadioButtonAction(false, \"browseForArchive.text\", \"saveAsFiles.text\");\n }\n resetSelectedFiles();\n }\n\n @FXML\n void handleArchiveTypeComboBoxAction(ActionEvent evt) {\n if (evt.getSource().equals(_archiveTypeComboBox)) {\n var archiveType = _archiveTypeComboBox.getValue();\n Log.i(\"Archive type selection change to: {0}\", archiveType, false);\n if (archiveType == ArchiveType.GZIP) {\n performGzipSelectionAction();\n }\n if (_decompressRadioButton.isSelected()) {\n resetSelectedFiles();\n } else { // update file extension\n final String outputPathText = _outputPathTextField.getText();\n final String fileExtension = archiveType.getDefaultExtensionName();\n String outputPath;\n if (outputPathText.endsWith(_archiveFileExtension)) {\n int lastIndexOfExtension = outputPathText.lastIndexOf(_archiveFileExtension);\n outputPath = outputPathText.substring(0, lastIndexOfExtension) + fileExtension;\n } else if (!FileUtils.isValidDirectory(outputPathText)) {\n outputPath = outputPathText + fileExtension;\n } else {\n outputPath = outputPathText;\n }\n setOutputPath(outputPath);\n _archiveFileExtension = fileExtension;\n }\n }\n }\n\n @FXML\n void onOutputPathTextFieldKeyTyped(KeyEvent evt) {\n if (evt.getSource().equals(_outputPathTextField)) {\n String filename = _outputPathTextField.getText();\n if (!FileUtils.containsIllegalChars(filename)) {\n updateSelectedFile(new File(filename));\n }\n }\n }\n\n @FXML\n void handleEnableLoggingCheckMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_enableLoggingCheckMenuItem)) {\n boolean enableLogging = _enableLoggingCheckMenuItem.isSelected();\n Settings.getInstance().setProperty(\"loggingEnabled\", enableLogging);\n Log.setVerboseUiLogging(enableLogging);\n }\n }\n\n @FXML\n void handleEnableDarkThemeCheckMenuItemAction(ActionEvent evt) {\n if (evt.getSource().equals(_enableDarkThemeCheckMenuItem)) {\n boolean enableTheme = _enableDarkThemeCheckMenuItem.isSelected();\n loadAlternativeTheme(enableTheme);\n Settings.getInstance().setProperty(\"darkThemeEnabled\", enableTheme);\n }\n }\n\n //</editor-fold>\n\n //<editor-fold desc=\"Methods related to UI\">\n\n private void checkUpdateOutputFileAndArchiveName(String outputPath) {\n if (!FileUtils.getPath(_outputFile).equals(outputPath)) {\n _outputFile = new File(outputPath);\n if (!_outputFile.isDirectory()) {\n _archiveName = _outputFile.getName();\n }\n }\n }\n\n private File pickFileToBeSaved() {\n final File file;\n\n if (_compressRadioButton.isSelected() && _putIntoSeparateArchives) {\n var directoryChooser = new DirectoryChooser();\n directoryChooser.setTitle(I18N.getString(\"saveAsArchiveTitle.text\"));\n file = directoryChooser.showDialog(primaryStage);\n } else if (_compressRadioButton.isSelected()) {\n var fileChooser = new FileChooser();\n fileChooser.setTitle(I18N.getString(\"saveAsArchiveTitle.text\"));\n _state.applyExtensionFilters(fileChooser);\n file = fileChooser.showSaveDialog(primaryStage);\n } else {\n var directoryChooser = new DirectoryChooser();\n directoryChooser.setTitle(I18N.getString(\"saveAsPathTitle.text\"));\n file = directoryChooser.showDialog(primaryStage);\n }\n\n return file;\n }\n\n private void performModeRadioButtonAction(boolean compress, String selectFilesButtonText, String saveAsButtonText) {\n _state = compress ? new CompressState() : new DecompressState();\n _selectFilesButton.setText(I18N.getString(selectFilesButtonText));\n _saveAsButton.setText(I18N.getString(saveAsButtonText));\n }\n\n private void performGzipSelectionAction() {\n final Settings settings = Settings.getInstance();\n final String propertyKey = \"showGzipInfoDialog\";\n final boolean showDialog = settings.evaluateProperty(propertyKey);\n if (showDialog) {\n final String infoTitle = I18N.getString(\"info.text\");\n final String infoText = I18N.getString(\"gzipCompressionInfo.text\", ArchiveType.TAR_GZ.getDisplayName());\n Dialogs.showDialog(Alert.AlertType.INFORMATION, infoTitle, infoTitle, infoText, theme, getIconImage());\n settings.setProperty(propertyKey, false);\n }\n }\n\n private void bindUIControls(Task<?> task) {\n\n final ReadOnlyBooleanProperty running = task.runningProperty();\n\n // controls\n _startButton.disableProperty().bind(running);\n _abortButton.disableProperty().bind(Bindings.not(running));\n _compressRadioButton.disableProperty().bind(running);\n _decompressRadioButton.disableProperty().bind(running);\n _archiveTypeComboBox.disableProperty().bind(running);\n _saveAsButton.disableProperty().bind(running);\n _selectFilesButton.disableProperty().bind(running);\n _addManyFilesMenuItem.disableProperty().bind(running);\n // progress bar\n _progressBar.visibleProperty().bind(running);\n _progressText.visibleProperty().bind(running);\n }\n\n private void unbindUIControls() {\n // controls\n _startButton.disableProperty().unbind();\n _abortButton.disableProperty().unbind();\n _compressRadioButton.disableProperty().unbind();\n _decompressRadioButton.disableProperty().unbind();\n _archiveTypeComboBox.disableProperty().unbind();\n _selectFilesButton.disableProperty().unbind();\n _saveAsButton.disableProperty().unbind();\n _addManyFilesMenuItem.disableProperty().unbind();\n // progress bar\n _progressBar.visibleProperty().unbind();\n _progressText.visibleProperty().unbind();\n }\n\n private void resetFilter() {\n final boolean wasApplied = _state.getFilterPredicate() != null;\n _state.setFilterPredicate(null);\n if (wasApplied) {\n Log.i(I18N.getString(\"filterReset.text\"), true);\n }\n }\n\n private void resetSelectedFiles() {\n if (!ListUtils.isNullOrEmpty(_selectedFiles)) {\n Log.i(I18N.getString(\"selectionReset.text\"), true);\n }\n _putIntoSeparateArchives = false;\n _selectedFiles = Collections.emptyList();\n _startButton.setDisable(true);\n }\n\n private void setOutputPath(String outputPath) {\n String osStyleFilePath = outputPath.replace('/', File.separatorChar);\n _outputPathTextField.setText(osStyleFilePath);\n }\n\n private void updateSelectedFile(File file) {\n if (file != null) {\n if (!file.isDirectory()) {\n final String archiveName = _archiveName = file.getName();\n String fileExtension = FileUtils.getExtension(archiveName, true);\n if (fileExtension.isEmpty()) {\n fileExtension = _archiveTypeComboBox.getValue().getDefaultExtensionName();\n }\n _archiveFileExtension = fileExtension;\n }\n _outputFile = file;\n }\n }\n\n //</editor-fold>\n\n //<editor-fold desc=\"Methods related to archiving job\">\n\n /**\n * Cancels all currently active tasks.\n */\n public void cancelActiveTasks() {\n if (!MapUtils.isNullOrEmpty(_activeTasks)) {\n _activeTasks.keySet().stream().map(_activeTasks::get)\n .filter((task) -> (!task.cancel(true))).forEachOrdered((task) -> {\n // log error message only when cancellation failed\n Log.e(\"Task cancellation failed for {0}\", task.hashCode());\n });\n }\n }\n\n /**\n * Initializes the archiving job by creating the required {@link Task}. This\n * task will not perform the algorithmic operations for archiving but instead\n * constantly checks for interruption to properly detect the abortion of an\n * operation. For the algorithmic operations a new task will be created and\n * submitted to the task handler. If an operation has been aborted, e.g.\n * through user interaction, the operation will be interrupted.\n *\n * @param operation the {@link ArchiveOperation} that will eventually be\n * performed by the task when executed.\n * @return a {@link Task} that can be executed to perform the specified archiving operation.\n */\n @SuppressWarnings(\"SleepWhileInLoop\")\n private Task<Boolean> initArchivingJob(final ArchiveOperation operation) {\n Task<Boolean> task = new Task<>() {\n @SuppressWarnings(\"BusyWait\")\n @Override\n protected Boolean call() throws Exception {\n final Future<Boolean> futureTask = _taskHandler.submit(operation);\n while (!futureTask.isDone()) {\n try {\n Thread.sleep(10); // continuous check for interruption\n } catch (InterruptedException ex) {\n // if exception is caught, task has been interrupted\n Log.i(I18N.getString(\"interrupt.text\"), true);\n Log.w(ex.getLocalizedMessage(), false);\n operation.interrupt();\n if (futureTask.cancel(true)) {\n Log.i(I18N.getString(\"operationCancel.text\"), true, operation);\n }\n }\n }\n\n try { // check for cancellation\n return futureTask.get();\n } catch (CancellationException ex) {\n return false; // ignore exception\n }\n }\n };\n\n showSuccessMessageAndFinalizeArchivingJob(operation, task);\n showErrorMessageAndFinalizeArchivingJob(operation, task);\n\n return task;\n }\n\n private void showErrorMessageAndFinalizeArchivingJob(ArchiveOperation operation, Task<Boolean> task) {\n task.setOnFailed(e -> {\n Log.i(I18N.getString(\"operationFail.text\"), true, operation);\n final Throwable thrown = e.getSource().getException();\n if (thrown != null) Log.e(thrown.getLocalizedMessage(), thrown);\n finishArchivingJob(operation, task);\n });\n }\n\n private void showSuccessMessageAndFinalizeArchivingJob(ArchiveOperation operation, Task<Boolean> task) {\n task.setOnSucceeded(e -> {\n final boolean success = (boolean) e.getSource().getValue();\n if (success) {\n Log.i(I18N.getString(\"operationSuccess.text\"), true, operation);\n } else {\n Log.w(I18N.getString(\"operationNoSuccess.text\"), true, operation);\n }\n finishArchivingJob(operation, task);\n });\n }\n\n /**\n * Calculates the total duration in seconds of the specified\n * {@link ArchiveOperation} and logs it to {@link #_textArea}. Also toggles\n * {@link #_startButton} and {@link #_abortButton}.\n *\n * @param operation {@link ArchiveOperation} that holds elapsed time.\n * @param task the task that will be removed from {@link #_activeTasks}.\n */\n private void finishArchivingJob(ArchiveOperation operation, Task<?> task) {\n Log.i(I18N.getString(\"elapsedTime.text\"), true, operation.calculateElapsedTime());\n _activeTasks.remove(task.hashCode());\n if (_activeTasks.isEmpty()) {\n unbindUIControls();\n _state.refresh();\n _progressBar.setProgress(0d); // reset\n _progressText.setText(StringUtils.EMPTY);\n }\n }\n\n //</editor-fold>\n\n //<editor-fold desc=\"Initialization\">\n\n private void initLogger() {\n TextAreaHandler handler = new TextAreaHandler(_textArea);\n handler.setFormatter(new SimpleFormatter());\n Log.setLoggerForUI(LOGGER.getName());\n LOGGER.setUseParentHandlers(false);\n LOGGER.addHandler(handler);\n }\n\n @Override\n public void initialize(URL location, ResourceBundle resources) {\n\n initLogger();\n\n final Settings settings = Settings.getInstance();\n setRecentlyUsedPathInOutputPathTextField(settings);\n\n if (theme == CSS.Theme.DARK_THEME) {\n _enableDarkThemeCheckMenuItem.setSelected(true);\n }\n\n setUpPropertiesForCompressionLevelMenuItem();\n setUpArchiveTypesComboBox();\n\n final boolean enableLogging = settings.evaluateProperty(\"loggingEnabled\");\n _enableLoggingCheckMenuItem.setSelected(enableLogging);\n\n _state = new CompressState(); // the default one\n final String formattedText = String.format(\"run:\\n%s\\n\", I18N.getString(\"changeOutputPath.text\"));\n _textArea.setText(formattedText);\n }\n\n private void setRecentlyUsedPathInOutputPathTextField(Settings settings) {\n final OperatingSystem os = settings.getOs();\n final String recentPath = settings.getProperty(\"recentPath\");\n\n if (FileUtils.isValidDirectory(recentPath)) {\n setOutputPath(recentPath);\n } else {\n setOutputPath(os.getDefaultUserDirectory());\n }\n\n _outputFile = new File(_outputPathTextField.getText());\n }\n\n private void setUpArchiveTypesComboBox() {\n final ArchiveType selectedType = ArchiveType.TAR_GZ;\n _archiveTypeComboBox.getItems().addAll(ArchiveType.values());\n _archiveTypeComboBox.setValue(selectedType);\n _archiveFileExtension = selectedType.getDefaultExtensionName();\n }\n\n private void setUpPropertiesForCompressionLevelMenuItem() {\n _noCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.NO_COMPRESSION);\n _bestSpeedCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.BEST_SPEED);\n _defaultCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.DEFAULT_COMPRESSION);\n _bestCompressionMenuItem.getProperties().put(COMPRESSION_LEVEL_KEY, Deflater.BEST_COMPRESSION);\n }\n\n //</editor-fold>\n\n //<editor-fold desc=\"Controller states\">\n\n /**\n * Inner class that represents the currently active state. This can either\n * be the {@link CompressState} or {@link DecompressState}.\n */\n private abstract class ArchivingState implements Listener<Integer> {\n\n /**\n * Holds the current progress or {@code -1d}. The current progress is\n * retrieved by the JavaFX thread to update the progress in the UI. A\n * new task is only submitted to the JavaFX thread if the value is\n * {@code -1d}. This avoids an unresponsive UI since the JavaFX thread\n * will not be flooded with new tasks.\n */\n private final ProgressManager _progressManager = new ProgressManager();\n\n /**\n * Converts percentage values to string objects. See method\n * {@link #update(org.gzipper.java.application.observer.Notifier, java.lang.Integer)}.\n */\n private final PercentageStringConverter _converter = new PercentageStringConverter();\n\n /**\n * Used to filter files or archive entries when processing archives.\n */\n protected Predicate<String> _filterPredicate = null;\n\n /**\n * Set the filter to be used when processing archives.\n *\n * @param filterPredicate the filter or {@code null} to reset it.\n */\n final void setFilterPredicate(Predicate<String> filterPredicate) {\n _filterPredicate = filterPredicate;\n }\n\n /**\n * Returns the filter to be used when processing archives.\n *\n * @return the filter to be used when processing archives. If no filter\n * is set, this method will return {@code null}.\n */\n final Predicate<String> getFilterPredicate() {\n return _filterPredicate;\n }\n\n /**\n * Validates the output path specified in user control.\n *\n * @return true if output path is valid, false otherwise.\n */\n abstract boolean checkUpdateOutputPath();\n\n /**\n * Initializes the archiving operation.\n *\n * @param archiveType the type of the archive, see {@link ArchiveType}.\n * @return list consisting of {@link ArchiveOperation}.\n * @throws GZipperException if the archive type could not have been\n * determined.\n */\n abstract List<ArchiveOperation> initOperation(ArchiveType archiveType) throws GZipperException;\n\n /**\n * Applies the required extension filters to the specified file chooser.\n *\n * @param chooser the {@link FileChooser} to which the extension filters\n * will be applied to.\n */\n void applyExtensionFilters(FileChooser chooser) {\n if (chooser != null) {\n final ArchiveType selectedType = _archiveTypeComboBox.getSelectionModel().getSelectedItem();\n for (ArchiveType type : ArchiveType.values()) {\n if (type.equals(selectedType)) {\n ExtensionFilter extFilter = new ExtensionFilter(\n type.getDisplayName(), type.getExtensionNames(true));\n chooser.getExtensionFilters().add(extFilter);\n }\n }\n }\n }\n\n /**\n * Refreshes this state, e.g. clears the state of the progress manager.\n */\n void refresh() {\n _progressManager.reset();\n }\n\n /**\n * Performs the specified {@link ArchiveOperation}.\n *\n * @param operation the {@link ArchiveOperation} to be performed.\n */\n void performOperation(ArchiveOperation operation) {\n if (operation != null) {\n Task<Boolean> task = initArchivingJob(operation);\n final ArchiveInfo info = operation.getArchiveInfo();\n Log.i(I18N.getString(\"operationStarted.text\"), true, operation,\n info.getArchiveType().getDisplayName());\n Log.i(I18N.getString(\"outputPath.text\", info.getOutputPath()), true);\n bindUIControls(task); // do this before submitting task\n _activeTasks.put(task.hashCode(), _taskHandler.submit(task));\n }\n }\n\n @Override\n public final void update(Notifier<Integer> notifier, Integer value) {\n if (value >= 100) {\n notifier.detach(this);\n } else {\n double progress = _progressManager.updateProgress(notifier.getId(), value);\n // update progress and execute on JavaFX thread if not busy\n if (_progressManager.getAndSetProgress(progress) == ProgressManager.SENTINEL) {\n Platform.runLater(() -> {\n double totalProgress = _progressManager\n .getAndSetProgress(ProgressManager.SENTINEL);\n if (totalProgress > _progressBar.getProgress()) {\n _progressBar.setProgress(totalProgress);\n _progressText.setText(_converter.toString(totalProgress));\n }\n });\n }\n }\n }\n }\n\n private final class CompressState extends ArchivingState {\n\n private String determineOutputPath(File outputFile) {\n if (!outputFile.exists() || outputFile.isFile()) {\n return outputFile.getParent();\n }\n\n return FileUtils.getPath(outputFile);\n }\n\n @Override\n public boolean checkUpdateOutputPath() {\n String outputPath = _outputPathTextField.getText();\n String extName = _archiveTypeComboBox.getValue().getDefaultExtensionName();\n\n if (FileUtils.isValidDirectory(outputPath) && !_putIntoSeparateArchives) {\n\n String archiveName = DEFAULT_ARCHIVE_NAME;\n\n if (_selectedFiles.size() == 1) {\n File firstFile = _selectedFiles.get(0);\n archiveName = firstFile.getName();\n }\n // user has not specified output filename\n outputPath = FileUtils.generateUniqueFilename(outputPath, archiveName, extName);\n }\n\n _archiveFileExtension = extName;\n\n if (FileUtils.isValidOutputFile(outputPath)) {\n setOutputPath(outputPath);\n return true;\n }\n\n return false;\n }\n\n @Override\n public void performOperation(ArchiveOperation operation) {\n if (!ListUtils.isNullOrEmpty(_selectedFiles)) {\n super.performOperation(operation);\n } else {\n Log.e(\"Operation cannot be started as no files have been specified\");\n Log.i(I18N.getString(\"noFilesSelectedWarning.text\"), true);\n }\n }\n\n @Override\n public List<ArchiveOperation> initOperation(ArchiveType archiveType) throws GZipperException {\n\n List<ArchiveOperation> operations;\n\n if (_archiveTypeComboBox.getValue() == ArchiveType.GZIP || _putIntoSeparateArchives) {\n\n final List<ArchiveInfo> infos;\n final String outputPath = determineOutputPath(_outputFile);\n operations = new ArrayList<>(_selectedFiles.size());\n\n if (_putIntoSeparateArchives) {\n infos = ArchiveInfoFactory.createArchiveInfos(\n archiveType, _compressionLevel, _selectedFiles, outputPath);\n } else if (_selectedFiles.size() == 1) {\n var info = ArchiveInfoFactory.createArchiveInfo(archiveType,\n _archiveName, _compressionLevel, _selectedFiles, _outputFile.getParent());\n infos = new ArrayList<>(1);\n infos.add(info);\n } else {\n infos = ArchiveInfoFactory.createArchiveInfos(archiveType,\n _archiveName, _compressionLevel, _selectedFiles, outputPath);\n }\n\n for (ArchiveInfo info : infos) {\n var builder = new ArchiveOperation.Builder(info, CompressionMode.COMPRESS);\n builder.addListener(this).filterPredicate(_filterPredicate);\n operations.add(builder.build());\n }\n } else {\n operations = new ArrayList<>(1);\n var info = ArchiveInfoFactory.createArchiveInfo(archiveType, _archiveName,\n _compressionLevel, _selectedFiles, _outputFile.getParent());\n _archiveName = info.getArchiveName();\n setOutputPath(FileUtils.combine(info.getOutputPath(), _archiveName));\n var builder = new ArchiveOperation.Builder(info, CompressionMode.COMPRESS);\n builder.addListener(this).filterPredicate(_filterPredicate);\n operations.add(builder.build());\n }\n\n return operations;\n }\n }\n\n private final class DecompressState extends ArchivingState {\n\n @Override\n public boolean checkUpdateOutputPath() {\n return FileUtils.isValidDirectory(_outputPathTextField.getText());\n }\n\n @Override\n public void performOperation(ArchiveOperation operation) {\n if (_outputFile != null && !ListUtils.isNullOrEmpty(_selectedFiles)) {\n super.performOperation(operation);\n } else {\n Log.e(\"Operation cannot be started because an invalid path has been specified\");\n Log.w(I18N.getString(\"outputPathWarning.text\"), true);\n _outputPathTextField.requestFocus();\n }\n }\n\n @Override\n public List<ArchiveOperation> initOperation(ArchiveType archiveType) throws GZipperException {\n\n List<ArchiveOperation> operations = new ArrayList<>(_selectedFiles.size());\n\n for (File file : _selectedFiles) {\n var info = ArchiveInfoFactory.createArchiveInfo(archiveType, FileUtils.getPath(file),\n FileUtils.getPath(_outputFile) + File.separator);\n var builder = new ArchiveOperation.Builder(info, CompressionMode.DECOMPRESS);\n builder.addListener(this).filterPredicate(_filterPredicate);\n operations.add(builder.build());\n }\n\n return operations;\n }\n }\n\n //</editor-fold>\n}", "public final class Log {\n\n /**\n * Default logger named {@code GZipper.class.getName()}.\n */\n public static final Logger DEFAULT_LOGGER;\n\n static {\n DEFAULT_LOGGER = Logger.getLogger(Log.class.getName());\n }\n\n /**\n * Name of the UI logger. The logger will be retrieved via\n * {@code java.util.logging.Logger.getLogger()}.\n */\n private static String LoggerNameUI;\n\n /**\n * If set to true, verbose logging is enabled. Verbose logging means that\n * the output in the UI is more detailed. This means that if logged, even\n * full exception messages will be displayed.\n */\n private static boolean _verboseUiLogging;\n\n /**\n * Enables verbose logging for the UI output.\n *\n * @param verboseUiLogging true to enable, false to disable.\n */\n public static void setVerboseUiLogging(boolean verboseUiLogging) {\n _verboseUiLogging = verboseUiLogging;\n }\n\n /**\n * Sets the name of the logger to be used for UI logging.\n *\n * @param loggerName the name of the logger.\n */\n public static void setLoggerForUI(String loggerName) {\n LoggerNameUI = loggerName;\n }\n\n /**\n * Logs a new error message including an exception.\n *\n * @param msg the message to log.\n * @param thrown the exception to include.\n */\n public static void e(String msg, Throwable thrown) {\n msg += \"\\n\" + stackTraceAsString(thrown);\n LogRecord record = new LogRecord(Level.SEVERE, msg);\n record.setThrown(thrown);\n log(record, _verboseUiLogging);\n }\n\n /**\n * Logs a new error message with an optional parameter.\n *\n * @param msg the message to log.\n * @param param the optional parameter.\n */\n public static void e(String msg, Object param) {\n LogRecord record = new LogRecord(Level.SEVERE, msg);\n record.setParameters(new Object[]{param});\n log(record, _verboseUiLogging);\n }\n\n /**\n * Logs a new error message with optional parameters.\n *\n * @param msg the message to log.\n * @param params the optional parameters.\n */\n public static void e(String msg, Object... params) {\n LogRecord record = new LogRecord(Level.SEVERE, msg);\n record.setParameters(params);\n log(record, _verboseUiLogging);\n }\n\n /**\n * Logs a new info message including an exception.\n *\n * @param msg the message to log.\n * @param thrown the exception to include.\n * @param uiLogging true to log to the UI as well.\n */\n public static void i(String msg, Throwable thrown, boolean uiLogging) {\n msg += \"\\n\" + stackTraceAsString(thrown);\n LogRecord record = new LogRecord(Level.INFO, msg);\n record.setThrown(thrown);\n log(record, uiLogging);\n }\n\n /**\n * Logs a new info message with an optional parameter.\n *\n * @param msg the message to log.\n * @param param the optional parameter.\n * @param uiLogging true to log to the UI as well.\n */\n public static void i(String msg, Object param, boolean uiLogging) {\n LogRecord record = new LogRecord(Level.INFO, msg);\n record.setParameters(new Object[]{param});\n log(record, uiLogging);\n }\n\n /**\n * Logs a new info message with optional parameters.\n *\n * @param msg the message to log.\n * @param uiLogging true to log to the UI as well.\n * @param params the optional parameters.\n */\n public static void i(String msg, boolean uiLogging, Object... params) {\n LogRecord record = new LogRecord(Level.INFO, msg);\n record.setParameters(params);\n log(record, uiLogging);\n }\n\n /**\n * Logs a new warning message including an exception.\n *\n * @param msg the message to log.\n * @param thrown the exception to include.\n * @param uiLogging true to log to the UI as well.\n */\n public static void w(String msg, Throwable thrown, boolean uiLogging) {\n msg += \"\\n\" + stackTraceAsString(thrown);\n LogRecord record = new LogRecord(Level.WARNING, msg);\n record.setThrown(thrown);\n log(record, uiLogging);\n }\n\n /**\n * Logs a new warning message with an optional parameter.\n *\n * @param msg the message to log.\n * @param param the optional parameter.\n * @param uiLogging true to log to the UI as well.\n */\n public static void w(String msg, Object param, boolean uiLogging) {\n LogRecord record = new LogRecord(Level.WARNING, msg);\n record.setParameters(new Object[]{param});\n log(record, uiLogging);\n }\n\n /**\n * Logs a new warning message with optional parameters.\n *\n * @param msg the message to log.\n * @param uiLogging true to log to the UI as well.\n * @param params the optional parameters.\n */\n public static void w(String msg, boolean uiLogging, Object... params) {\n LogRecord record = new LogRecord(Level.WARNING, msg);\n record.setParameters(params);\n log(record, uiLogging);\n }\n\n /**\n * Converts the stack trace of the specified {@link Throwable} to a string.\n *\n * @param thrown holds the stack trace.\n * @return string representation of the stack trace.\n */\n private static String stackTraceAsString(Throwable thrown) {\n StringWriter errors = new StringWriter();\n thrown.printStackTrace(new PrintWriter(errors));\n return errors.toString();\n }\n\n /**\n * Logs the specified {@link LogRecord} using both, the default logger and\n * the logger for UI output if {@code uiLogging} equals true.\n *\n * @param record the {@link LogRecord} to be logged.\n * @param uiLogging true to also log using the logger for UI.\n */\n private static void log(LogRecord record, boolean uiLogging) {\n DEFAULT_LOGGER.log(record);\n if (uiLogging) {\n Logger.getLogger(LoggerNameUI).log(record);\n }\n }\n}", "public final class Settings {\r\n\r\n public static final String FALSE_STRING = \"false\";\r\n public static final String TRUE_STRING = \"true\";\r\n\r\n /**\r\n * The actual properties file. Required to store away changed properties.\r\n */\r\n private File _propsFile;\r\n\r\n /**\r\n * The properties read from the {@link #_propsFile};\r\n */\r\n private Properties _props;\r\n\r\n /**\r\n * The default properties values for restoration.\r\n */\r\n private final Properties _defaults;\r\n\r\n /**\r\n * The operating system the JVM runs on.\r\n */\r\n private OperatingSystem _os;\r\n\r\n private Settings() {\r\n _defaults = initDefaults();\r\n }\r\n\r\n /**\r\n * Initializes this singleton class. This may only be called once.\r\n *\r\n * @param props the properties file to initialize this class with.\r\n * @param os the current operating system.\r\n */\r\n public void init(File props, OperatingSystem os) {\r\n if (_props == null) {\r\n _os = os; // to receive environment variables\r\n if (props != null) {\r\n _propsFile = props;\r\n _props = new Properties(_defaults);\r\n\r\n try (final FileInputStream fis = new FileInputStream(props);\r\n final BufferedInputStream bis = new BufferedInputStream(fis)) {\r\n _props.load(bis);\r\n } catch (IOException ex) {\r\n Log.e(ex.getLocalizedMessage(), ex);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Initializes the default properties values.\r\n *\r\n * @return the default properties.\r\n */\r\n private Properties initDefaults() {\r\n\r\n final Properties defaults = new Properties();\r\n\r\n defaults.setProperty(\"loggingEnabled\", FALSE_STRING);\r\n defaults.setProperty(\"recentPath\", StringUtils.EMPTY);\r\n defaults.setProperty(\"darkThemeEnabled\", FALSE_STRING);\r\n defaults.setProperty(\"showGzipInfoDialog\", TRUE_STRING);\r\n\r\n return defaults;\r\n }\r\n\r\n /**\r\n * Sets a new property to {@link #_props}.\r\n *\r\n * @param key the key of the property.\r\n * @param value the value of the property as string.\r\n * @return the previous value of the specified key.\r\n */\r\n public synchronized Object setProperty(String key, String value) {\r\n return _props.setProperty(key, value);\r\n }\r\n\r\n /**\r\n * Sets a new property to {@link #_props}.\r\n *\r\n * @param key the key of the property.\r\n * @param value the value of the property as boolean.\r\n * @return the previous value of the specified key.\r\n */\r\n public synchronized Object setProperty(String key, boolean value) {\r\n final String propertyValue = value ? TRUE_STRING : FALSE_STRING;\r\n return _props.setProperty(key, propertyValue);\r\n }\r\n\r\n /**\r\n * Returns the property with the specified key if it exists.\r\n *\r\n * @param key the key of the property.\r\n * @return the value of the property as string.\r\n */\r\n public String getProperty(String key) {\r\n return _props.getProperty(key);\r\n }\r\n\r\n /**\r\n * Evaluates and returns the property with the specified key if it exists.\r\n *\r\n * @param key the key of the property.\r\n * @return true if property equals \"true\", false otherwise.\r\n */\r\n public boolean evaluateProperty(String key) {\r\n final String property = _props.getProperty(key);\r\n return property != null && property.equals(TRUE_STRING);\r\n }\r\n\r\n /**\r\n * Returns the operating system on which the JVM is running on.\r\n *\r\n * @return the operating system on which the JVM is running on.\r\n */\r\n public OperatingSystem getOs() {\r\n return _os;\r\n }\r\n\r\n /**\r\n * Saves all the properties to {@link #_propsFile};\r\n *\r\n * @throws IOException if an I/O error occurs.\r\n */\r\n public void storeAway() throws IOException {\r\n _props.store(new BufferedOutputStream(new FileOutputStream(_propsFile)), \"\");\r\n }\r\n\r\n /**\r\n * Restores the default properties.\r\n */\r\n public void restoreDefaults() {\r\n _props.clear();\r\n _props.putAll(_defaults);\r\n }\r\n\r\n /**\r\n * Returns the singleton instance of this class.\r\n *\r\n * @return the singleton instance of this class.\r\n */\r\n public static Settings getInstance() {\r\n return SettingsHolder.INSTANCE;\r\n }\r\n\r\n /**\r\n * Holder class for singleton instance.\r\n */\r\n private static class SettingsHolder {\r\n\r\n private static final Settings INSTANCE = new Settings();\r\n }\r\n}\r" ]
import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.gzipper.java.application.model.OS; import org.gzipper.java.application.model.OperatingSystem; import org.gzipper.java.application.util.AppUtils; import org.gzipper.java.application.util.FileUtils; import org.gzipper.java.presentation.controller.BaseController; import org.gzipper.java.presentation.controller.HashViewController; import org.gzipper.java.presentation.controller.MainViewController; import org.gzipper.java.util.Log; import org.gzipper.java.util.Settings; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ResourceBundle; import java.util.logging.*;
/* * Copyright (C) 2020 Matthias Fussenegger * * 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.gzipper.java.presentation; /** * @author Matthias Fussenegger */ public final class GZipper extends Application { //<editor-fold desc="Constants"> private static final String LAUNCH_MODE_PARAM_NAME = "launch_mode"; private static final String LAUNCH_MODE_APPLICATION = "application"; private static final String LAUNCH_MODE_HASH_VIEW = "hashview"; //</editor-fold> //<editor-fold desc="Initialization"> private void initApplication() {
final String decPath = AppUtils.getDecodedRootPath(getClass());
2
sivaprasadreddy/jblogger
src/main/java/com/sivalabs/jblogger/web/controllers/BaseController.java
[ "@Entity\n@Table(name = \"TAGS\")\n@Data\npublic class Tag implements Serializable, Comparable<Tag>\n{\n\tprivate static final long serialVersionUID = 1L;\n\n\t@Id\n\t@SequenceGenerator(name=\"tag_id_generator\", sequenceName=\"tag_id_seq\", initialValue = 100, allocationSize=1)\n\t@GeneratedValue(generator = \"tag_id_generator\")\n\tprivate Long id;\n\n\t@Column(name = \"label\", unique=true, nullable = false, length = 150)\n\tprivate String label;\n\t\n\t@JsonIgnore\n\t@ManyToMany(mappedBy=\"tags\")\n\tprivate List<Post> posts;\n\n\t@Override\n\tpublic int compareTo(Tag other)\n\t{\n\t\treturn this.label.compareToIgnoreCase(other.label);\n\t}\n\n}", "public class AuthenticatedUser extends org.springframework.security.core.userdetails.User\n{\n\n\tprivate static final long serialVersionUID = 1L;\n\tprivate User user;\n\t\n\tpublic AuthenticatedUser(User user)\n\t{\n\t\tsuper(user.getEmail(), user.getPassword(), getAuthorities(user));\n\t\tthis.user = user;\n\t}\n\t\n\tpublic User getUser()\n\t{\n\t\treturn user;\n\t}\n\t\n\tprivate static Collection<? extends GrantedAuthority> getAuthorities(User user)\n\t{\n\t\tList<Role> roles = user.getRoles();\n\t\tfinal String[] roleNames = roles.stream().map(Role::getName).toArray(String[]::new);\n\t\treturn AuthorityUtils.createAuthorityList(roleNames);\n\t}\n}", "public class SecurityUtils\n{\n\tprivate SecurityUtils() {\n\t}\n\n\tpublic static AuthenticatedUser getCurrentUser() {\n\n\t Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n\t if (principal instanceof AuthenticatedUser) {\n\t \treturn (AuthenticatedUser) principal;\n\t }\n\t return null;\n\t}\n\n\tpublic static boolean isLoggedIn() {\n\t return getCurrentUser() != null;\n\t}\n}", "@Service\n@Transactional\npublic class BlogService \n{\n\tprivate final PostRepository postRepository;\n\tprivate final CommentRepository commentRepository;\n\tprivate final PageViewRepository pageViewRepository;\n\n\t@Autowired\n\tpublic BlogService(PostRepository postRepository, CommentRepository commentRepository, PageViewRepository pageViewRepository) {\n\t\tthis.postRepository = postRepository;\n\t\tthis.commentRepository = commentRepository;\n\t\tthis.pageViewRepository = pageViewRepository;\n\t}\n\n\tpublic BlogOverview getBlogOverView(TimePeriod timePeriod)\n\t{\n\t\tBlogOverview overview = new BlogOverview();\n\t\tlong postsCount = postRepository.count();\n\t\toverview.setPostsCount(postsCount);\n\n\t\tlong commentsCount = commentRepository.count();\n\t\toverview.setCommentsCount(commentsCount);\n\n\t\tLocalDateTime today = LocalDateTime.now();\n\t\tLocalDateTime startDate = CommonUtils.getStartOfDay(today);\n\t\tLocalDateTime endDate = CommonUtils.getEndOfDay(today);\n\t\t\n\t\tlong todayViewCount = pageViewRepository.countByVisitTimeBetween(startDate, endDate);\n\t\toverview.setTodayViewCount(todayViewCount);\n\n\t\tLocalDateTime yesterday = CommonUtils.getYesterday(today);\n\t\tstartDate = CommonUtils.getStartOfDay(yesterday);\n\t\tendDate = CommonUtils.getEndOfDay(yesterday);\n\t\tlong yesterdayViewCount = pageViewRepository.countByVisitTimeBetween(startDate, endDate);\n\t\toverview.setYesterdayViewCount(yesterdayViewCount);\n\t\t\n\t\tstartDate = CommonUtils.getWeekStartDay(today);\n\t\tendDate = CommonUtils.getWeekEndDay(today);\n\t\t\n\t\tlong thisWeekViewCount = pageViewRepository.countByVisitTimeBetween(startDate, endDate);\n\t\toverview.setThisWeekViewCount(thisWeekViewCount);\n\t\t\n\t\tstartDate = CommonUtils.getMonthStartDay(today);\n\t\tendDate = CommonUtils.getMonthEndDay(today);\n\t\t\n\t\tlong thisMonthViewCount = pageViewRepository.countByVisitTimeBetween(startDate, endDate);\n\t\toverview.setThisMonthViewCount(thisMonthViewCount);\n\t\t\n\t\tlong alltimeViewCount = postRepository.getTotalPostViewCount();\n\t\toverview.setAlltimeViewCount(alltimeViewCount);\n\t\t\n\t\tif(timePeriod == TimePeriod.ALL_TIME){\n\t\t\tstartDate = CommonUtils.getDummyVeryOldDate();\n\t\t\tendDate = CommonUtils.getDummyVeryNewDate();\n\t\t} else if(timePeriod == TimePeriod.MONTH){\n\t\t\tstartDate = CommonUtils.getMonthStartDay(today);\n\t\t\tendDate = CommonUtils.getMonthEndDay(today);\n\t\t} else if(timePeriod == TimePeriod.WEEK){\n\t\t\tstartDate = CommonUtils.getWeekStartDay(today);\n\t\t\tendDate = CommonUtils.getWeekEndDay(today);\n\t\t} else if(timePeriod == TimePeriod.YESTERDAY){\n\t\t\tstartDate = CommonUtils.getStartOfDay(yesterday);\n\t\t\tendDate = CommonUtils.getEndOfDay(yesterday);\n\t\t} else {\n\t\t\tstartDate = CommonUtils.getStartOfDay(today);\n\t\t\tendDate = CommonUtils.getEndOfDay(today);\n\t\t}\n\t\t\n\t\tList<PageView> pageViews = pageViewRepository.findByVisitTimeBetween(startDate, endDate);\n\t\toverview.setPageViews(pageViews );\n\t\treturn overview;\n\t}\n\n}", "@Component\n@Slf4j\npublic class EmailService\n{\n\tprivate final ApplicationProperties applicationProperties;\n\tprivate final JavaMailSender javaMailSender;\n\n\t@Autowired\n\tpublic EmailService(ApplicationProperties applicationProperties, JavaMailSender javaMailSender) {\n\t\tthis.applicationProperties = applicationProperties;\n\t\tthis.javaMailSender = javaMailSender;\n\t}\n\n\t@Async\n\tpublic CompletableFuture<Void> send(String subject, String content)\n\t{\n\t\tString supportEmail = applicationProperties.getSupportEmail();\n\t\t\n\t\tSimpleMailMessage mailMessage = new SimpleMailMessage();\n mailMessage.setTo(supportEmail);\n mailMessage.setReplyTo(supportEmail);\n mailMessage.setFrom(supportEmail);\n mailMessage.setSubject(subject);\n mailMessage.setText(content); \n\t\t\n try\n\t\t{\n\t\t\tjavaMailSender.send(mailMessage);\n\t\t} catch (MailException e)\n\t\t{\n\t\t\tlog.error(\"\", e);\n\t\t}\n\t\treturn CompletableFuture.completedFuture(null);\n\t}\n\t\n}", "@Service\n@Transactional\npublic class TagService\n{\n\tprivate TagRepository tagRepository;\n\n\t@Autowired\n\tpublic TagService(TagRepository tagRepository) {\n\t\tthis.tagRepository = tagRepository;\n\t}\n\n\tpublic List<Tag> search(String query){\n\t\treturn tagRepository.findByLabelLike(query+\"%\");\n\t}\n\t\n\tpublic Optional<Tag> findById(Long id){\n\t\treturn tagRepository.findById(id);\n\t}\n\n\t@Cacheable(value = \"tags.item\")\n\tpublic Optional<Tag> findByLabel(String label){\n\t\treturn tagRepository.findByLabel(label.trim());\n\t}\n\t\n\t@CacheEvict(value = {\"tags.counts\", \"tags.all\"}, allEntries=true)\n\tpublic Tag createTag(Tag tag){\n\t\tif(findByLabel(tag.getLabel()).isPresent()){\n\t\t\tthrow new JBloggerException(\"Tag [\"+tag.getLabel()+\"] already exists\");\n\t\t}\n\t\treturn tagRepository.save(tag);\n\t}\n\t\n\t@Cacheable(value = \"tags.all\")\n\tpublic List<Tag> findAllTags()\n\t{\n\t\treturn tagRepository.findAll();\n\t}\n\t\n\t@Cacheable(value = \"tags.counts\")\n\tpublic Map<Tag, Integer> getTagsWithCount()\n\t{\n\t\tMap<Tag, Integer> map = new TreeMap<>();\n\n\t\tList<Object[]> tagsWithCount = tagRepository.getTagsWithCount();\n\t\tfor (Object[] objects : tagsWithCount) {\n\t\t\tTag tag = new Tag();\n\t\t\ttag.setId(Long.parseLong(String.valueOf(objects[0])));\n\t\t\ttag.setLabel(String.valueOf(objects[1]));\n\t\t\tInteger count = Integer.parseInt(String.valueOf(objects[2]));\n\t\t\tmap.put(tag, count);\n\t\t}\n\t\t\n\t\treturn map;\n\t}\n\n}" ]
import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.ModelAttribute; import com.sivalabs.jblogger.entities.Tag; import com.sivalabs.jblogger.security.AuthenticatedUser; import com.sivalabs.jblogger.security.SecurityUtils; import com.sivalabs.jblogger.services.BlogService; import com.sivalabs.jblogger.services.EmailService; import com.sivalabs.jblogger.services.TagService;
package com.sivalabs.jblogger.web.controllers; public abstract class BaseController { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired protected ApplicationEventPublisher publisher; @Autowired protected MessageSource messageSource; @Autowired protected BlogService blogService; @Autowired protected TagService tagService; @Autowired protected EmailService emailService; public String getMessage(String code) { return messageSource.getMessage(code, null, null); } public String getMessage(String code, String defaultMsg) { return messageSource.getMessage(code, null, defaultMsg, null); } public void publish(Object event){ publisher.publishEvent(event); } @ModelAttribute("authenticatedUser") public AuthenticatedUser authenticatedUser(@AuthenticationPrincipal AuthenticatedUser authenticatedUser) { return authenticatedUser; } public static AuthenticatedUser getCurrentUser() {
return SecurityUtils.getCurrentUser();
2
lkorth/photo-paper
PhotoPaper/src/main/java/com/lukekorth/photo_paper/services/WallpaperService.java
[ "public class WallpaperApplication extends Application {\n\n private static final String VERSION = \"version\";\n\n private static FiveHundredPxClient sApiClient;\n private static FiveHundredPxClient sNonLoggedInApiClient;\n private static ThreadBus sBus;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n migrate();\n MailableLog.init(this, BuildConfig.DEBUG);\n DebugUtils.setup(this);\n\n Realm.init(this);\n RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();\n Realm.setDefaultConfiguration(realmConfiguration);\n\n getBus().register(this);\n\n if (Settings.isEnabled(this) && !AlarmHelper.isAlarmSet(this)) {\n AlarmHelper.scheduleWallpaperAlarm(this);\n }\n }\n\n private void migrate() {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n SharedPreferences.Editor editor = prefs.edit();\n int version = prefs.getInt(VERSION, 0);\n if (BuildConfig.VERSION_CODE > version) {\n String now = new Date().toString();\n if (version == 0) {\n editor.putString(\"install_date\", now);\n }\n\n editor.putString(\"upgrade_date\", now);\n editor.putInt(VERSION, BuildConfig.VERSION_CODE);\n editor.apply();\n\n MailableLog.clearLog(this);\n }\n }\n\n @Subscribe\n public void onUserUpdated(UserUpdatedEvent event) {\n sApiClient = null;\n }\n\n public static FiveHundredPxClient getApiClient() {\n if (sApiClient == null) {\n Realm realm = Realm.getDefaultInstance();\n OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();\n if (User.isUserLoggedIn(realm)) {\n AccessToken accessToken = User.getLoggedInUserAccessToken(realm);\n OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(BuildConfig.CONSUMER_KEY,\n BuildConfig.CONSUMER_SECRET);\n consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());\n okHttpBuilder.addInterceptor(new SigningInterceptor(consumer));\n } else {\n okHttpBuilder.addInterceptor(new ConsumerApiKeyInterceptor());\n }\n\n okHttpBuilder.addInterceptor(new UserAgentInterceptor());\n\n if (BuildConfig.DEBUG) {\n okHttpBuilder.addNetworkInterceptor(DebugUtils.getDebugNetworkInterceptor());\n }\n\n sApiClient = new Retrofit.Builder()\n .baseUrl(\"https://api.500px.com/v1/\")\n .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation()\n .create()))\n .client(okHttpBuilder.build())\n .addConverterFactory(GsonConverterFactory.create())\n .build()\n .create(FiveHundredPxClient.class);\n\n realm.close();\n }\n\n return sApiClient;\n }\n\n public static FiveHundredPxClient getNonLoggedInApiClient() {\n if (sNonLoggedInApiClient == null) {\n OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder()\n .addInterceptor(new ConsumerApiKeyInterceptor())\n .addInterceptor(new UserAgentInterceptor());\n\n if (BuildConfig.DEBUG) {\n okHttpBuilder.addNetworkInterceptor(DebugUtils.getDebugNetworkInterceptor());\n }\n\n sNonLoggedInApiClient = new Retrofit.Builder()\n .baseUrl(\"https://api.500px.com/v1/\")\n .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation()\n .create()))\n .client(okHttpBuilder.build())\n .addConverterFactory(GsonConverterFactory.create())\n .build()\n .create(FiveHundredPxClient.class);\n }\n\n return sNonLoggedInApiClient;\n }\n\n public static Bus getBus() {\n if (sBus == null) {\n sBus = new ThreadBus();\n }\n return sBus;\n }\n}", "public class PicassoHelper {\n\n public static Picasso getPicasso(Context context) {\n return new Picasso.Builder(context.getApplicationContext())\n .downloader(new OkHttp3Downloader(context.getApplicationContext(), 512000000)) // 512mb\n .indicatorsEnabled(BuildConfig.DEBUG)\n .build();\n }\n\n public static void clearCache(Context context) {\n PicassoTools.clearCache(PicassoHelper.getPicasso(context));\n }\n}", "public class Settings {\n\n private static SharedPreferences getPrefs(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n public static String getFavoriteGallery(Context context) {\n return getPrefs(context).getString(\"favorite_gallery\", null);\n }\n\n public static String getFavoriteGalleryId(Context context) {\n return getPrefs(context).getString(\"favorite_gallery_id\", null);\n }\n\n public static void setFavoriteGallery(Context context, String gallery) {\n getPrefs(context).edit().putString(\"favorite_gallery\", gallery).apply();\n }\n\n public static void setFavoriteGalleryId(Context context, String id) {\n getPrefs(context).edit().putString(\"favorite_gallery_id\", id).apply();\n }\n\n public static String getFeature(Context context) {\n return getPrefs(context).getString(\"feature\", \"popular\");\n }\n\n public static void setFeature(Context context, String feature) {\n getPrefs(context).edit().putString(\"feature\", feature).apply();\n }\n\n public static String getSearchQuery(Context context) {\n return getPrefs(context).getString(\"search_query\", \"\");\n }\n\n public static void setSearchQuery(Context context, String query) {\n getPrefs(context).edit().putString(\"search_query\", query).apply();\n }\n\n public static int[] getCategories(Context context) {\n Set<String> defaultCategory = new HashSet<String>();\n defaultCategory.add(\"8\");\n Set<String> prefCategories = getPrefs(context).getStringSet(\"categories\", defaultCategory);\n\n int[] categories = new int[prefCategories.size()];\n int i = 0;\n for (String category : prefCategories) {\n categories[i] = Integer.parseInt(category);\n i++;\n }\n\n return categories;\n }\n\n public static void setCategories(Context context, Set<String> categories) {\n getPrefs(context).edit().putStringSet(\"categories\", categories).apply();\n }\n\n public static boolean isEnabled(Context context) {\n return getPrefs(context).getBoolean(\"enable\", false);\n }\n\n public static int getUpdateInterval(Context context) {\n return Integer.parseInt(getPrefs(context).getString(\"update_interval\", \"3600\"));\n }\n\n public static void setUpdateInterval(Context context, String interval) {\n getPrefs(context).edit().putString(\"update_interval\", interval).apply();\n }\n\n public static boolean useParallax(Context context) {\n return getPrefs(context).getBoolean(\"use_parallax\", false);\n }\n\n public static boolean useOnlyWifi(Context context) {\n return getPrefs(context).getBoolean(\"use_only_wifi\", true);\n }\n\n public static long getLastUpdated(Context context) {\n return getPrefs(context).getLong(\"last_updated\", 0);\n }\n\n public static void setUpdated(Context context) {\n getPrefs(context).edit().putLong(\"last_updated\", System.currentTimeMillis()).apply();\n }\n\n public static void clearUpdated(Context context) {\n getPrefs(context).edit().putLong(\"last_updated\", 0).apply();\n }\n}", "public class Utils {\n\n public static boolean shouldGetPhotos(Context context, Realm realm) {\n return Settings.isEnabled(context) && Utils.needMorePhotos(context, realm) &&\n isCurrentNetworkOk(context);\n }\n\n public static boolean shouldUpdateWallpaper(Context context) {\n return Settings.isEnabled(context) && (((Settings.getLastUpdated(context) +\n (Settings.getUpdateInterval(context) * 1000)) < System.currentTimeMillis()));\n }\n\n public static boolean isCurrentNetworkOk(Context context) {\n return !Settings.useOnlyWifi(context) ||\n (Settings.useOnlyWifi(context) && Utils.isConnectedToWifi(context));\n }\n\n public static boolean needMorePhotos(Context context, Realm realm) {\n return Photos.unseenPhotoCount(context, realm) <= 10;\n }\n\n public static boolean isConnectedToWifi(Context context) {\n ConnectivityManager connectivityManager =\n (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();\n return (activeNetwork != null && activeNetwork.isConnectedOrConnecting() &&\n activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);\n }\n\n public static int dpToPx(Context context, double dp) {\n return (int) Math.round(dp * (context.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));\n }\n\n public static int getWallpaperHeight(Context context) {\n return WallpaperManager.getInstance(context).getDesiredMinimumHeight();\n }\n\n public static int getWallpaperWidth(Context context) {\n return WallpaperManager.getInstance(context).getDesiredMinimumWidth();\n }\n\n public static int getScreenHeight(Context context) {\n return getScreenResolution(context).y;\n }\n\n public static int getScreenWidth(Context context) {\n return getScreenResolution(context).x;\n }\n\n private static Point getScreenResolution(Context context) {\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Point point = new Point();\n windowManager.getDefaultDisplay().getSize(point);\n return point;\n }\n\n public static boolean supportsParallax(Context context) {\n return ((double) getWallpaperWidth(context) / getScreenWidth(context)) >= 2;\n }\n\n public static String getListSummary(Context context, int indexArrayId, int valueArrayId,\n String index, String defaultValue) {\n String[] indexArray = context.getResources().getStringArray(indexArrayId);\n String[] valueArray = context.getResources().getStringArray(valueArrayId);\n int i;\n for (i = 0; i < indexArray.length; i++) {\n if (indexArray[i].equals(index)) {\n return valueArray[i];\n }\n }\n return defaultValue;\n }\n}", "public class Photos extends RealmObject {\n\n public static final String BASE_URL_500PX = \"http://500px.com\";\n\n private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\");\n\n @Expose\n @SerializedName(\"id\")\n @Required\n private String id;\n\n @Expose\n private String name;\n\n @Expose\n private String description;\n\n @Expose\n private String userName;\n\n @Expose\n private long createdAt;\n\n @Expose\n private String feature;\n\n @Expose\n private String search;\n\n @Expose\n private int category;\n\n @Expose\n @SerializedName(\"highest_rating\")\n private double highestRating;\n\n @Expose\n @SerializedName(\"times_viewed\")\n private int views;\n\n @Expose\n @SerializedName(\"image_url\")\n public String imageUrl;\n\n @Expose\n @SerializedName(\"url\")\n private String urlPath;\n\n @Expose\n private int palette;\n\n @Expose\n private boolean seen;\n\n @Expose\n private long seenAt;\n\n @Expose\n private int failedCount;\n\n @Expose\n private long addedAt;\n\n public String getPhotoId() {\n return id;\n }\n\n public void setPhotoId(String photoId) {\n this.id = photoId;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public long getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(long createdAt) {\n this.createdAt = createdAt;\n }\n\n public String getFeature() {\n return feature;\n }\n\n public void setFeature(String feature) {\n this.feature = feature;\n }\n\n public String getSearch() {\n return search;\n }\n\n public void setSearch(String search) {\n this.search = search;\n }\n\n public int getCategory() {\n return category;\n }\n\n public void setCategory(int category) {\n this.category = category;\n }\n\n public double getHighestRating() {\n return highestRating;\n }\n\n public void setHighestRating(double highestRating) {\n this.highestRating = highestRating;\n }\n\n public int getViews() {\n return views;\n }\n\n public void setViews(int views) {\n this.views = views;\n }\n\n public String getImageUrl() {\n return imageUrl;\n }\n\n public void setImageUrl(String imageUrl) {\n this.imageUrl = imageUrl;\n }\n\n public String getUrlPath() {\n return urlPath;\n }\n\n public void setUrlPath(String urlPath) {\n this.urlPath = urlPath;\n }\n\n public int getPalette() {\n return palette;\n }\n\n public void setPalette(int palette) {\n this.palette = palette;\n }\n\n public boolean isSeen() {\n return seen;\n }\n\n public void setSeen(boolean seen) {\n this.seen = seen;\n }\n\n public long getSeenAt() {\n return seenAt;\n }\n\n public void setSeenAt(long seenAt) {\n this.seenAt = seenAt;\n }\n\n public int getFailedCount() {\n return failedCount;\n }\n\n public void setFailedCount(int failedCount) {\n this.failedCount = failedCount;\n }\n\n public long getAddedAt() {\n return addedAt;\n }\n\n public void setAddedAt(long addedAt) {\n this.addedAt = addedAt;\n }\n\n public static Photos create(Realm realm, Photo photo, String feature, String search) {\n Logger logger = LoggerFactory.getLogger(\"Photos\");\n\n if (photo.nsfw) {\n logger.debug(\"Photo was nsfw\");\n return null;\n }\n\n if (realm.where(Photos.class).equalTo(\"id\", photo.id).count() > 0) {\n logger.debug(\"Photo already exists\");\n return null;\n }\n\n try {\n realm.beginTransaction();\n\n Photos photoModel = realm.createObject(Photos.class);\n photoModel.setPhotoId(photo.id);\n photoModel.setName(photo.name);\n photoModel.setDescription(photo.description);\n photoModel.setUserName(photo.user.getFullName());\n photoModel.setCreatedAt(DATE_FORMAT.parse(photo.createdAt.substring(0, photo.createdAt.length() - 6)).getTime());\n photoModel.setFeature(feature);\n photoModel.setSearch(search);\n photoModel.setCategory(photo.category);\n photoModel.setHighestRating(photo.highestRating);\n photoModel.setViews(photo.views);\n photoModel.setImageUrl(photo.imageUrl);\n photoModel.setUrlPath(photo.url);\n photoModel.setSeen(false);\n photoModel.setSeenAt(0);\n photoModel.setAddedAt(photoModel.addedAt = System.currentTimeMillis());\n\n realm.commitTransaction();\n\n return photoModel;\n } catch (ParseException e) {\n logger.error(e.getMessage());\n }\n\n return null;\n }\n\n public static Photos getPhoto(Realm realm, int id) {\n return realm.where(Photos.class)\n .equalTo(\"id\", id)\n .findFirst();\n }\n\n public static Photos getNextPhoto(Context context, Realm realm) {\n RealmResults<Photos> photos = getQuery(context, realm);\n if (photos.isEmpty()) {\n return null;\n } else {\n return photos.first();\n }\n }\n\n public static Photos getCurrentPhoto(Realm realm) {\n RealmResults<Photos> photos = getRecentlySeenPhotos(realm);\n if (photos.isEmpty()) {\n return null;\n } else {\n return photos.first();\n }\n }\n\n public static RealmResults<Photos> getRecentlySeenPhotos(Realm realm) {\n return realm.where(Photos.class)\n .equalTo(\"seen\", true)\n .greaterThan(\"seenAt\", System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))\n .findAllSorted(\"seenAt\", Sort.DESCENDING);\n }\n\n public static List<Photos> getUnseenPhotos(Context context, Realm realm) {\n return getQuery(context, realm);\n }\n\n public static int unseenPhotoCount(Context context, Realm realm) {\n return getQuery(context, realm).size();\n }\n\n private static RealmResults<Photos> getQuery(Context context, Realm realm) {\n String feature = Settings.getFeature(context);\n RealmQuery<Photos> query = realm.where(Photos.class);\n if (feature.equals(\"search\")) {\n query.equalTo(\"search\", Settings.getSearchQuery(context));\n } else {\n query.equalTo(\"feature\", feature);\n }\n\n query.beginGroup();\n int[] categories = Settings.getCategories(context);\n for (int i = 0; i < categories.length - 1; i++) {\n query.equalTo(\"category\", categories[i])\n .or();\n }\n query.equalTo(\"category\", categories[categories.length - 1])\n .endGroup();\n\n return query.equalTo(\"seen\", false)\n .findAllSorted(new String[] { \"failedCount\", \"highestRating\", \"views\", \"createdAt\" },\n new Sort[] { Sort.ASCENDING, Sort.DESCENDING, Sort.DESCENDING, Sort.ASCENDING });\n }\n}", "public class WallpaperChangedEvent {\n}" ]
import android.app.IntentService; import android.app.WallpaperManager; import android.content.Intent; import android.graphics.Bitmap; import android.os.Build; import android.os.PowerManager; import android.support.v7.graphics.Palette; import com.google.firebase.analytics.FirebaseAnalytics; import com.lukekorth.photo_paper.R; import com.lukekorth.photo_paper.WallpaperApplication; import com.lukekorth.photo_paper.helpers.PicassoHelper; import com.lukekorth.photo_paper.helpers.Settings; import com.lukekorth.photo_paper.helpers.Utils; import com.lukekorth.photo_paper.models.Photos; import com.lukekorth.photo_paper.models.WallpaperChangedEvent; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.RequestCreator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; import io.realm.Realm;
package com.lukekorth.photo_paper.services; public class WallpaperService extends IntentService { public WallpaperService() { super("WallpaperService"); } @Override protected void onHandleIntent(Intent intent) { Logger logger = LoggerFactory.getLogger("WallpaperService"); if (!Settings.isEnabled(this)) { logger.debug("App is not enabled"); return; } PowerManager.WakeLock wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "500pxApiService"); wakeLock.acquire(TimeUnit.MINUTES.toMillis(1)); WallpaperManager wallpaperManager = WallpaperManager.getInstance(this); int width = wallpaperManager.getDesiredMinimumWidth(); int height = wallpaperManager.getDesiredMinimumHeight(); if (Utils.supportsParallax(this) && !Settings.useParallax(this)) { width = width / 2; } Realm realm = Realm.getDefaultInstance(); Photos photo = Photos.getNextPhoto(this, realm); if (photo != null) { try { logger.debug("Setting wallpaper to " + width + "px wide by " + height + "px tall");
RequestCreator request = PicassoHelper.getPicasso(this)
1
tvbarthel/SimpleWeatherForecast
SimpleWeatherForecast/src/main/java/fr/tvbarthel/apps/simpleweatherforcast/ui/WeatherRemoteViewsFactory.java
[ "public class MainActivity extends ActionBarActivity implements SharedPreferences.OnSharedPreferenceChangeListener {\n\n public static final String EXTRA_PAGE_POSITION = \"fr.tvbarthel.apps.simpleweatherforcast.MainActivity.Extra.PagePosition\";\n\n private ViewGroup mRootView;\n private ForecastPagerAdapter mSectionsPagerAdapter;\n private ViewPager mViewPager;\n private Toast mTextToast;\n private String mTemperatureUnit;\n private SpannableString mActionBarSpannableTitle;\n private AlphaForegroundColorSpan mAlphaForegroundColorSpan;\n private TypefaceSpan mTypefaceSpanLight;\n private int[] mBackgroundColors;\n private Menu mMenu;\n private SimpleDateFormat mActionBarTitleDateFormat;\n private ProgressBar mProgressBar;\n private String mLoadedWeather;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);\n setSupportActionBar(toolbar);\n\n // Get the colors used for the background\n mBackgroundColors = getResources().getIntArray(R.array.background_colors);\n //Get the temperature unit symbol\n mTemperatureUnit = SharedPreferenceUtils.getTemperatureUnitSymbol(this);\n\n mAlphaForegroundColorSpan = new AlphaForegroundColorSpan(Color.WHITE);\n mTypefaceSpanLight = new TypefaceSpan(\"sans-serif-light\");\n mActionBarTitleDateFormat = new SimpleDateFormat(\"EEEE dd MMMM\", Locale.getDefault());\n\n mProgressBar = (ProgressBar) findViewById(R.id.activity_main_progress_bar);\n mRootView = (ViewGroup) findViewById(R.id.activity_main_root);\n\n initActionBar();\n initViewPager();\n initRootPadding();\n }\n\n private void initRootPadding() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n final Resources resources = getResources();\n final boolean isPortrait = resources.getBoolean(R.bool.is_portrait);\n final ActionBar actionBar = getSupportActionBar();\n\n final ViewTreeObserver vto = mRootView.getViewTreeObserver();\n if (vto.isAlive()) {\n vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {\n @Override\n public boolean onPreDraw() {\n mRootView.getViewTreeObserver().removeOnPreDrawListener(this);\n\n int paddingBottom = mRootView.getPaddingBottom();\n int paddingTop = mRootView.getPaddingTop();\n int paddingRight = mRootView.getPaddingRight();\n int paddingLeft = mRootView.getPaddingLeft();\n\n // Add the status bar height to the top padding.\n int resourceId = resources.getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n paddingTop += resources.getDimensionPixelSize(resourceId);\n }\n\n if (isPortrait) {\n // Add the navigation bar height to the bottom padding.\n resourceId = resources.getIdentifier(\"navigation_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n paddingBottom += resources.getDimensionPixelSize(resourceId);\n }\n } else {\n // Add the navigation bar width to the right padding.\n resourceId = resources.getIdentifier(\"navigation_bar_width\", \"dimen\", \"android\");\n if (resourceId > 0) {\n paddingRight += resources.getDimensionPixelSize(resourceId);\n }\n }\n\n mRootView.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);\n return true;\n }\n });\n }\n }\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n final String lastKnownWeather = SharedPreferenceUtils.getLastKnownWeather(getApplicationContext());\n final Intent intent = getIntent();\n SharedPreferenceUtils.registerOnSharedPreferenceChangeListener(this, this);\n\n if (lastKnownWeather == null) {\n // There is no forecast, it should be the first launch\n mProgressBar.setVisibility(View.VISIBLE);\n } else if (mLoadedWeather != lastKnownWeather) {\n // Load the last known weather\n loadDailyForecast(lastKnownWeather);\n } else if (intent != null && intent.hasExtra(EXTRA_PAGE_POSITION)) {\n final int position = intent.getIntExtra(EXTRA_PAGE_POSITION, 0);\n mViewPager.setCurrentItem(position, true);\n intent.removeExtra(EXTRA_PAGE_POSITION);\n }\n\n //Check if the last known weather is out dated.\n if (SharedPreferenceUtils.isWeatherOutdated(this, false) || lastKnownWeather == null) {\n DailyForecastUpdateService.startForUpdate(this);\n }\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n SharedPreferenceUtils.unregisterOnSharedPreferenceChangeListener(this, this);\n hideToast();\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n setIntent(intent);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n mMenu = menu;\n // If the user is supporting us, add a thanks action.\n SupportUtils.checkSupport(getApplicationContext(), new SupportUtils.OnCheckSupportListener() {\n @Override\n public void onCheckSupport(boolean supporting) {\n if (supporting) {\n getMenuInflater().inflate(R.menu.thanks, mMenu);\n }\n }\n });\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n int id = item.getItemId();\n boolean isActionConsumed;\n switch (id) {\n case R.id.menu_item_about:\n isActionConsumed = handleActionAbout();\n break;\n\n case R.id.menu_item_manual_refresh:\n isActionConsumed = handleActionManualRefresh();\n break;\n\n case R.id.menu_item_license:\n isActionConsumed = handleActionLicense();\n break;\n\n case R.id.menu_item_more_apps:\n isActionConsumed = handleActionMoreApps();\n break;\n\n case R.id.menu_item_unit_picker:\n isActionConsumed = handleActionUnitPicker();\n break;\n\n case R.id.menu_item_support:\n isActionConsumed = handleActionSupport();\n break;\n\n case R.id.menu_item_contact_us:\n isActionConsumed = handleActionContactUs();\n break;\n\n case R.id.menu_item_thanks:\n isActionConsumed = handleThanksButton();\n break;\n\n default:\n isActionConsumed = super.onOptionsItemSelected(item);\n }\n return isActionConsumed;\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {\n if (key.equals(SharedPreferenceUtils.KEY_TEMPERATURE_UNIT_SYMBOL)) {\n mTemperatureUnit = SharedPreferenceUtils.getTemperatureUnitSymbol(this);\n mSectionsPagerAdapter.notifyDataSetChanged();\n invalidatePageTransformer();\n\n // Broadcast change to the widgets\n Intent intent = new Intent(this, WeatherWidgetReceiver.class);\n intent.setAction(WeatherWidgetReceiver.APPWIDGET_DATA_CHANGED);\n sendBroadcast(intent);\n } else if (SharedPreferenceUtils.KEY_LAST_UPDATE.equals(key)) {\n final String lastKnownWeather = SharedPreferenceUtils.getLastKnownWeather(getApplicationContext());\n loadDailyForecast(lastKnownWeather);\n }\n }\n\n private boolean handleThanksButton() {\n makeTextToast(R.string.support_has_supported_us);\n return true;\n }\n\n private boolean handleActionContactUs() {\n final String uriString = getString(R.string.contact_us_uri,\n Uri.encode(getString(R.string.contact_us_email)),\n Uri.encode(getString(R.string.contact_us_default_subject)));\n final Uri mailToUri = Uri.parse(uriString);\n Intent sendToIntent = new Intent(Intent.ACTION_SENDTO);\n sendToIntent.setData(mailToUri);\n startActivity(sendToIntent);\n return true;\n }\n\n private boolean handleActionSupport() {\n final int colorSize = mBackgroundColors.length;\n final int currentPosition = mViewPager.getCurrentItem();\n final int currentColor = mBackgroundColors[currentPosition % colorSize];\n final Intent intent = new Intent(this, SupportActivity.class);\n intent.putExtra(SupportActivity.EXTRA_BG_COLOR, currentColor);\n startActivity(intent);\n return true;\n }\n\n private boolean handleActionUnitPicker() {\n final String[] temperatureUnitNames = getResources().getStringArray(R.array.temperature_unit_names);\n final String[] temperatureUnitSymbols = getResources().getStringArray(R.array.temperature_unit_symbols);\n (TemperatureUnitPickerDialogFragment.newInstance(temperatureUnitNames, temperatureUnitSymbols))\n .show(getSupportFragmentManager(), \"dialog_unit_picker\");\n return true;\n }\n\n private boolean handleActionAbout() {\n (new AboutDialogFragment()).show(getSupportFragmentManager(), \"dialog_about\");\n return true;\n }\n\n private boolean handleActionMoreApps() {\n (new MoreAppsDialogFragment()).show(getSupportFragmentManager(), \"dialog_more_apps\");\n return true;\n }\n\n private boolean handleActionLicense() {\n (new LicenseDialogFragment()).show(getSupportFragmentManager(), \"dialog_license\");\n return true;\n }\n\n private boolean handleActionManualRefresh() {\n if (SharedPreferenceUtils.isWeatherOutdated(this, true)) {\n DailyForecastUpdateService.startForUpdate(this);\n mSectionsPagerAdapter.clear();\n mLoadedWeather = null;\n mProgressBar.setVisibility(View.VISIBLE);\n } else {\n makeTextToast(R.string.toast_already_up_to_date);\n }\n return true;\n }\n\n\n private void initActionBar() {\n // Hide the app icon in the actionBar\n getSupportActionBar().setDisplayShowHomeEnabled(false);\n }\n\n private void initViewPager() {\n mSectionsPagerAdapter = new ForecastPagerAdapter(getSupportFragmentManager());\n mViewPager = (ViewPager) findViewById(R.id.activity_main_view_pager);\n mViewPager.setAdapter(mSectionsPagerAdapter);\n mViewPager.setPageTransformer(true, new ForecastPageTransformer());\n mViewPager.setOffscreenPageLimit(2);\n mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int currentPosition, float positionOffset, int i2) {\n setGradientBackgroundColor(currentPosition, positionOffset);\n updateActionBarTitle(currentPosition, positionOffset);\n }\n\n @Override\n public void onPageSelected(int i) {\n }\n\n @Override\n public void onPageScrollStateChanged(int i) {\n }\n });\n }\n\n private void makeTextToast(int stringResourceId) {\n hideToast();\n mTextToast = Toast.makeText(this, stringResourceId, Toast.LENGTH_LONG);\n mTextToast.show();\n }\n\n private void hideToast() {\n if (mTextToast != null) {\n mTextToast.cancel();\n mTextToast = null;\n }\n }\n\n private void loadDailyForecast(final String jsonDailyForecast) {\n mProgressBar.setVisibility(View.VISIBLE);\n if (jsonDailyForecast != null) {\n new DailyForecastJsonParser() {\n @Override\n protected void onPostExecute(ArrayList<DailyForecastModel> dailyForecastModels) {\n super.onPostExecute(dailyForecastModels);\n mLoadedWeather = jsonDailyForecast;\n mProgressBar.setVisibility(View.INVISIBLE);\n mSectionsPagerAdapter.updateModels(dailyForecastModels);\n\n final Intent intent = getIntent();\n if (intent != null && intent.hasExtra(EXTRA_PAGE_POSITION)) {\n final int position = intent.getIntExtra(EXTRA_PAGE_POSITION, 0);\n mViewPager.setCurrentItem(position);\n intent.removeExtra(EXTRA_PAGE_POSITION);\n } else {\n invalidatePageTransformer();\n }\n }\n }.execute(jsonDailyForecast);\n }\n }\n\n /**\n * Trick to notify the pageTransformer of a data set change.\n */\n private void invalidatePageTransformer() {\n if (mViewPager.getAdapter().getCount() > 0) {\n new Handler().post(new Runnable() {\n @Override\n public void run() {\n if (mViewPager.beginFakeDrag()) {\n mViewPager.fakeDragBy(0f);\n mViewPager.endFakeDrag();\n }\n }\n });\n }\n }\n\n @SuppressLint(\"NewApi\")\n private void setGradientBackgroundColor(int currentPosition, float positionOffset) {\n final GradientDrawable g = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,\n new int[]{getColor(currentPosition, positionOffset), getColor(currentPosition, (float) Math.pow(positionOffset, 0.40))});\n if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {\n mRootView.setBackgroundDrawable(g);\n } else {\n mRootView.setBackground(g);\n }\n }\n\n private void setActionBarAlpha(float alpha) {\n mAlphaForegroundColorSpan.setAlpha(alpha);\n mActionBarSpannableTitle.setSpan(mAlphaForegroundColorSpan, 0, mActionBarSpannableTitle.length(),\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n getSupportActionBar().setTitle(mActionBarSpannableTitle);\n }\n\n private void updateActionBarTitle(int currentPosition, float positionOffset) {\n float alpha = 1 - positionOffset * 2;\n if (positionOffset >= 0.5) {\n currentPosition++;\n alpha = (positionOffset - 0.5f) * 2;\n }\n setActionBarTitle(currentPosition);\n setActionBarAlpha(alpha);\n }\n\n private void setActionBarTitle(int position) {\n String newTitle = getActionBarTitle(position);\n if (mActionBarSpannableTitle == null || !mActionBarSpannableTitle.toString().equals(newTitle)) {\n mActionBarSpannableTitle = new SpannableString(newTitle);\n mActionBarSpannableTitle.setSpan(mTypefaceSpanLight, 0, mActionBarSpannableTitle.length(),\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n }\n }\n\n private String getActionBarTitle(int currentPosition) {\n final DailyForecastModel currentModel = mSectionsPagerAdapter.getModel(currentPosition);\n return mActionBarTitleDateFormat.format(currentModel.getDateTime() * 1000);\n }\n\n\n private int getColor(int currentPosition, float positionOffset) {\n //retrieve current color and next color relative to the current position.\n final int colorSize = mBackgroundColors.length;\n final int currentColor = mBackgroundColors[(currentPosition) % colorSize];\n final int nextColor = mBackgroundColors[(currentPosition + 1) % colorSize];\n\n //Compute the deltas relative to the current position offset.\n final int deltaR = (int) ((Color.red(nextColor) - Color.red(currentColor)) * positionOffset);\n final int deltaG = (int) ((Color.green(nextColor) - Color.green(currentColor)) * positionOffset);\n final int deltaB = (int) ((Color.blue(nextColor) - Color.blue(currentColor)) * positionOffset);\n\n return Color.argb(255, Color.red(currentColor) + deltaR, Color.green(currentColor) + deltaG, Color.blue(currentColor) + deltaB);\n }\n\n\n /**\n * A {@link FragmentStatePagerAdapter} used for {@link DailyForecastModel}\n */\n public class ForecastPagerAdapter extends FragmentStatePagerAdapter {\n\n private final ArrayList<DailyForecastModel> mDailyForecastModels;\n\n public ForecastPagerAdapter(FragmentManager fm) {\n super(fm);\n mDailyForecastModels = new ArrayList<DailyForecastModel>();\n }\n\n public void updateModels(ArrayList<DailyForecastModel> newModels) {\n mDailyForecastModels.clear();\n mDailyForecastModels.addAll(newModels);\n notifyDataSetChanged();\n }\n\n public void clear() {\n mDailyForecastModels.clear();\n notifyDataSetChanged();\n }\n\n public DailyForecastModel getModel(int position) {\n if (position >= mDailyForecastModels.size()) {\n return new DailyForecastModel();\n }\n return mDailyForecastModels.get(position);\n }\n\n @Override\n public Fragment getItem(int position) {\n return ForecastFragment.newInstance(mDailyForecastModels.get(position), mTemperatureUnit);\n }\n\n @Override\n public int getItemPosition(Object object) {\n return POSITION_NONE;\n }\n\n @Override\n public int getCount() {\n return mDailyForecastModels.size();\n }\n }\n\n /**\n * A {@link PageTransformer} used to scale the fragments.\n */\n public class ForecastPageTransformer implements PageTransformer {\n\n public void transformPage(View view, float position) {\n final int pageWidth = view.getWidth();\n\n if (position < -2.0) { // [-Infinity,-2.0)\n // This page is way off-screen to the left.\n ViewHelper.setAlpha(view, 0);\n\n } else if (position <= 2.0) { // [-2.0,2.0]\n final float normalizedPosition = Math.abs(position / 2);\n final float scaleFactor = 1f - normalizedPosition;\n final float horizontalMargin = pageWidth * normalizedPosition;\n\n //Translate back the page.\n if (position < 0) {\n //left\n ViewHelper.setTranslationX(view, horizontalMargin);\n } else {\n //right\n ViewHelper.setTranslationX(view, -horizontalMargin);\n }\n\n // Scale the page down relative to its size.\n ViewHelper.setScaleX(view, (float) Math.pow(scaleFactor, 0.80));\n ViewHelper.setScaleY(view, (float) Math.pow(scaleFactor, 0.80));\n\n // Fade the page relative to its size.\n ViewHelper.setAlpha(view, 1f * scaleFactor - (scaleFactor * 0.25f));\n\n } else { // (2.0,+Infinity]\n // This page is way off-screen to the right.\n ViewHelper.setAlpha(view, 0);\n }\n }\n }\n\n}", "public class DailyForecastJsonParser extends AsyncTask<String, Void, ArrayList<DailyForecastModel>> {\n\n private static final String TAG_WEATHER_LIST = \"list\";\n private static final String TAG_HUMIDITY = \"humidity\";\n private static final String TAG_WEATHER = \"weather\";\n private static final String TAG_WEATHER_DESCRIPTION = \"description\";\n private static final String TAG_TEMPERATURE = \"temp\";\n private static final String TAG_TEMPERATURE_DAY = \"day\";\n private static final String TAG_TEMPERATURE_MIN = \"min\";\n private static final String TAG_TEMPERATURE_MAX = \"max\";\n private static final String TAG_DATE_TIME = \"dt\";\n\n @Override\n protected ArrayList<DailyForecastModel> doInBackground(String... params) {\n return parse(params[0]);\n }\n\n public static ArrayList<DailyForecastModel> parse(final String json) {\n final ArrayList<DailyForecastModel> result = new ArrayList<DailyForecastModel>();\n if (json != null) {\n try {\n JSONObject root = new JSONObject(json);\n JSONArray weatherList = root.getJSONArray(TAG_WEATHER_LIST);\n for (int i = 0; i < weatherList.length(); i++) {\n result.add(parseDailyForecast(weatherList.getJSONObject(i)));\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n return result;\n }\n\n private static DailyForecastModel parseDailyForecast(JSONObject jsonDailyForecast) {\n final DailyForecastModel model = new DailyForecastModel();\n model.setDateTime(parseDateTime(jsonDailyForecast));\n model.setHumidity(parseHumidity(jsonDailyForecast));\n model.setDescription(parseWeatherDescription(jsonDailyForecast));\n parseTemperature(model, jsonDailyForecast);\n return model;\n }\n\n private static void parseTemperature(DailyForecastModel model, JSONObject dailyForecast) {\n try {\n JSONObject jsonTemperature = dailyForecast.getJSONObject(TAG_TEMPERATURE);\n model.setTemperature(parseDayTemperature(jsonTemperature));\n model.setMinTemperature(parseMinTemperature(jsonTemperature));\n model.setMaxTemperature(parseMaxTemperature(jsonTemperature));\n } catch (JSONException exception) {\n exception.printStackTrace();\n model.setTemperature(0d);\n model.setMinTemperature(0d);\n model.setMaxTemperature(0d);\n }\n }\n\n private static Double parseDayTemperature(JSONObject temperature) {\n return parseDouble(temperature, TAG_TEMPERATURE_DAY, 0d);\n }\n\n private static Double parseMinTemperature(JSONObject temperature) {\n return parseDouble(temperature, TAG_TEMPERATURE_MIN, 0d);\n }\n\n private static Double parseMaxTemperature(JSONObject temperature) {\n return parseDouble(temperature, TAG_TEMPERATURE_MAX, 0d);\n }\n\n\n private static Double parseDouble(JSONObject object, String tag, Double defaultValue) {\n try {\n return object.getDouble(tag);\n } catch (JSONException exception) {\n exception.printStackTrace();\n return defaultValue;\n }\n }\n\n private static String parseWeatherDescription(JSONObject dailyForecast) {\n String weatherDescription = \"\";\n try {\n weatherDescription = dailyForecast.getJSONArray(TAG_WEATHER).getJSONObject(0).getString(TAG_WEATHER_DESCRIPTION);\n } catch (JSONException exception) {\n exception.printStackTrace();\n }\n return weatherDescription;\n }\n\n private static int parseHumidity(JSONObject dailyForecast) {\n int humidity = 0;\n try {\n humidity = dailyForecast.getInt(TAG_HUMIDITY);\n } catch (JSONException exception) {\n exception.printStackTrace();\n }\n return humidity;\n }\n\n private static long parseDateTime(JSONObject dailyForecast) {\n long dateTime = 0;\n try {\n dateTime = dailyForecast.getLong(TAG_DATE_TIME);\n } catch (JSONException exception) {\n exception.printStackTrace();\n }\n return dateTime;\n }\n\n}", "public class DailyForecastModel implements Parcelable {\n\n private long mDateTime;\n private String mDescription;\n private Double mTemperature;\n private Double mMinTemperature;\n private Double mMaxTemperature;\n private int mHumidity;\n\n public DailyForecastModel() {\n }\n\n public DailyForecastModel(Parcel in) {\n readFromParcel(in);\n }\n\n public String getDescription() {\n return mDescription;\n }\n\n public void setDescription(String description) {\n mDescription = description;\n }\n\n public int getHumidity() {\n return mHumidity;\n }\n\n public void setHumidity(int humidity) {\n mHumidity = humidity;\n }\n\n public long getDateTime() {\n return mDateTime;\n }\n\n public void setDateTime(long dateTime) {\n mDateTime = dateTime;\n }\n\n public Double getTemperature() {\n return mTemperature;\n }\n\n public void setTemperature(Double temperature) {\n mTemperature = temperature;\n }\n\n public Double getMinTemperature() {\n return mMinTemperature;\n }\n\n public void setMinTemperature(Double minTemperature) {\n mMinTemperature = minTemperature;\n }\n\n public Double getMaxTemperature() {\n return mMaxTemperature;\n }\n\n public void setMaxTemperature(Double maxTemperature) {\n mMaxTemperature = maxTemperature;\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.writeLong(mDateTime);\n dest.writeString(mDescription);\n dest.writeInt(mHumidity);\n dest.writeDouble(mTemperature);\n dest.writeDouble(mMinTemperature);\n dest.writeDouble(mMaxTemperature);\n }\n\n private void readFromParcel(Parcel in) {\n mDateTime = in.readLong();\n mDescription = in.readString();\n mHumidity = in.readInt();\n mTemperature = in.readDouble();\n mMinTemperature = in.readDouble();\n mMaxTemperature = in.readDouble();\n }\n\n public static final Parcelable.Creator<DailyForecastModel> CREATOR = new Parcelable.Creator<DailyForecastModel>() {\n @Override\n public DailyForecastModel createFromParcel(Parcel source) {\n return new DailyForecastModel(source);\n }\n\n @Override\n public DailyForecastModel[] newArray(int size) {\n return new DailyForecastModel[size];\n }\n };\n\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 final class TemperatureUtils {\n\n\n /**\n * Convert a temperature in Celsius to the requested unit.\n *\n * @param context a {@link android.content.Context}\n * @param temperatureInCelsius the given temperature in Celsius\n * @param temperatureUnit the requested unit\n * @return the temperature converted\n */\n public static long convertTemperature(Context context, double temperatureInCelsius, String temperatureUnit) {\n double temperatureConverted = temperatureInCelsius;\n if (temperatureUnit.equals(context.getString(R.string.temperature_unit_fahrenheit_symbol))) {\n temperatureConverted = temperatureInCelsius * 1.8f + 32f;\n } else if (temperatureUnit.equals(context.getString(R.string.temperature_unit_kelvin_symbol))) {\n temperatureConverted = temperatureInCelsius + 273.15f;\n }\n return Math.round(temperatureConverted);\n }\n\n // Non-instantiable class.\n private TemperatureUtils() {\n }\n}" ]
import android.annotation.TargetApi; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import fr.tvbarthel.apps.simpleweatherforcast.MainActivity; import fr.tvbarthel.apps.simpleweatherforcast.R; import fr.tvbarthel.apps.simpleweatherforcast.openweathermap.DailyForecastJsonParser; import fr.tvbarthel.apps.simpleweatherforcast.openweathermap.DailyForecastModel; import fr.tvbarthel.apps.simpleweatherforcast.utils.SharedPreferenceUtils; import fr.tvbarthel.apps.simpleweatherforcast.utils.TemperatureUtils;
package fr.tvbarthel.apps.simpleweatherforcast.ui; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class WeatherRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { private Context mContext; private int mAppWidgetId; private List<DailyForecastModel> mDailyForecasts; private int[] mColors; private SimpleDateFormat mSimpleDateFormat; private String mTemperatureUnit; public WeatherRemoteViewsFactory(Context context, Intent intent) { mContext = context; mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); mSimpleDateFormat = new SimpleDateFormat("EEEE dd MMMM", Locale.getDefault()); } @Override public void onCreate() { mColors = new int[]{R.color.holo_blue, R.color.holo_purple, R.color.holo_yellow, R.color.holo_red, R.color.holo_green}; } @Override public void onDataSetChanged() { final String lastKnownWeather = SharedPreferenceUtils.getLastKnownWeather(mContext);
mDailyForecasts = DailyForecastJsonParser.parse(lastKnownWeather);
1
material-motion/material-motion-android
library/src/main/java/com/google/android/material/motion/interactions/Rotatable.java
[ "public class ConstraintApplicator<T> {\n\n private final Operation<T, T>[] constraints;\n\n public ConstraintApplicator(Operation<T, T>[] constraints) {\n this.constraints = constraints;\n }\n\n public MotionObservable<T> apply(MotionObservable<T> stream) {\n for (Operation<T, T> constraint : constraints) {\n stream = stream.compose(constraint);\n }\n return stream;\n }\n}", "public class MotionObservable<T> extends IndefiniteObservable<MotionObserver<T>> {\n\n public MotionObservable(Connector<MotionObserver<T>> connector) {\n super(connector);\n }\n\n /**\n * Subscribes to the IndefiniteObservable and ignores all incoming values.\n *\n * @see #subscribe(Observer)\n */\n public Subscription subscribe() {\n return super.subscribe(new SimpleMotionObserver<T>() {\n @Override\n public void next(T value) {\n }\n });\n }\n\n /**\n * A light-weight operator builder. Applies the given operation to the incoming stream.\n * <p>\n * This is the preferred method for building new operators. This builder can be used to create\n * any operator that only needs to modify or block values. All state events are forwarded\n * along.\n *\n * @param operation An operation to apply to each incoming value. The operation must handle\n * values of type {@link T} or more general types. For example, an operation that handles {@link\n * View}s can be applied to a stream of {@link TextView}s.\n * @param <U> The returned stream contains values of this type. The operation must output values\n * of this type.\n */\n public <U> MotionObservable<U> compose(final Operation<T, U> operation) {\n final MotionObservable<T> upstream = MotionObservable.this;\n\n return new MotionObservable<>(new Connector<MotionObserver<U>>() {\n\n @NonNull\n @Override\n public Disconnector connect(final MotionObserver<U> observer) {\n operation.preConnect(observer);\n final Subscription subscription = upstream.subscribe(new MotionObserver<T>() {\n\n @Override\n public void next(T value) {\n operation.next(observer, value);\n }\n\n @Override\n public void build(MotionBuilder<T> builder, T[] values) {\n if (operation instanceof SameTypedMapOperation) {\n //noinspection unchecked\n ((SameTypedMapOperation<T>) operation).build(\n (MotionObserver<T>) observer, builder, values);\n }\n }\n });\n operation.postConnect(observer);\n\n return new Disconnector() {\n\n @Override\n public void disconnect() {\n operation.preDisconnect(observer);\n subscription.unsubscribe();\n operation.postDisconnect(observer);\n }\n };\n }\n });\n }\n\n public <U> MotionObservable<U> compose(final RawOperation<T, U> operation) {\n return operation.compose(this);\n }\n}", "public final class MotionRuntime {\n\n private final List<Subscription> subscriptions = new ArrayList<>();\n private final WeakHashMap<View, ReactiveView> cachedReactiveViews = new WeakHashMap<>();\n private final WeakHashMap<Object, List<Interaction<?, ?>>> cachedInteractions =\n new WeakHashMap<>();\n\n /**\n * Subscribes to the stream, writes its output to the given property, and observes its state.\n */\n public <O, T> void write(\n MotionObservable<T> stream, final O target, final Property<O, T> property) {\n write(stream, ReactiveProperty.of(target, property));\n }\n\n /**\n * Subscribes to the stream, writes its output to the given property, and observes its state.\n */\n public <T> void write(MotionObservable<T> stream, final ReactiveProperty<T> property) {\n subscriptions.add(stream.subscribe(new MotionObserver<T>() {\n\n @Override\n public void next(T value) {\n property.write(value);\n }\n\n @Override\n public void build(MotionBuilder<T> builder, T[] values) {\n builder.start(property, values);\n }\n }));\n }\n\n @SafeVarargs\n public final <O, T> void addInteraction(\n Interaction<O, T> interaction, O target, Operation<T, T>... constraints) {\n addInteraction(interaction, target, new ConstraintApplicator<>(constraints));\n }\n\n public final <O, T> void addInteraction(\n Interaction<O, T> interaction, O target, ConstraintApplicator<T> constraints) {\n List<Interaction<?, ?>> interactions = cachedInteractions.get(target);\n if (interactions == null) {\n interactions = new ArrayList<>();\n cachedInteractions.put(target, interactions);\n }\n interactions.add(interaction);\n\n interaction.apply(this, target, constraints);\n }\n\n /**\n * Returns a reactive version of the given object and caches the returned result for future access.\n */\n public ReactiveView get(View view) {\n ReactiveView reactiveView = cachedReactiveViews.get(view);\n if (reactiveView == null) {\n reactiveView = new ReactiveView(view);\n cachedReactiveViews.put(view, reactiveView);\n }\n\n return reactiveView;\n }\n\n public <I extends Interaction<O, ?>, O> List<I> interactions(Class<I> klass, O target) {\n List<Interaction<?, ?>> interactions = cachedInteractions.get(target);\n List<I> filteredInteractions = new ArrayList<>();\n\n for (Interaction<?, ?> i : interactions) {\n if(klass.isInstance(i))\n //noinspection unchecked\n filteredInteractions.add((I)i);\n }\n return filteredInteractions;\n }\n\n /**\n * Initiates interaction {@code a} when interaction {@code b} changes to the given state.\n */\n public void start(Interaction<?, ?> a, Interaction<?, ?> b, @MotionState int state) {\n MotionObservable<Boolean> stream =\n b.state.getStream()\n .compose(dedupe())\n .compose(rewrite(state, true));\n write(stream, a.enabled);\n }\n}", "public abstract class GestureInteraction<GR extends GestureRecognizer, T>\n extends Interaction<View, T> {\n\n public final GR gestureRecognizer;\n public final MotionObservable<GR> gestureStream;\n\n protected GestureInteraction(GR gestureRecognizer) {\n this.gestureRecognizer = gestureRecognizer;\n this.gestureStream = GestureSource.from(this);\n }\n\n @Override\n public final void apply(MotionRuntime runtime, View target, ConstraintApplicator<T> constraints) {\n OnTouchListeners.add(target, gestureRecognizer);\n\n onApply(runtime, gestureStream, target, constraints);\n }\n\n /**\n * Applies the values of the gesture recognizer stream to the target view.\n */\n protected abstract void onApply(\n MotionRuntime runtime,\n MotionObservable<GR> stream,\n View target,\n ConstraintApplicator<T> constraints);\n\n}", "public static <T extends RotateGestureRecognizer> Operation<T, Float> rotated(final View view) {\n return new Operation<T, Float>() {\n\n private float initialRotation;\n\n @Override\n public void next(MotionObserver<Float> observer, T gestureRecognizer) {\n switch (gestureRecognizer.getState()) {\n case BEGAN:\n initialRotation = view.getRotation();\n break;\n case CHANGED:\n float rotation = gestureRecognizer.getRotation();\n\n observer.next((float) (initialRotation + rotation * (180 / Math.PI)));\n break;\n }\n }\n };\n}" ]
import android.view.View; import com.google.android.material.motion.ConstraintApplicator; import com.google.android.material.motion.MotionObservable; import com.google.android.material.motion.MotionRuntime; import com.google.android.material.motion.gestures.RotateGestureRecognizer; import com.google.android.material.motion.gestures.GestureInteraction; import static com.google.android.material.motion.operators.Rotated.rotated;
/* * Copyright 2017-present The Material Motion Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.material.motion.interactions; /** * A rotatable interaction. */ public class Rotatable extends GestureInteraction<RotateGestureRecognizer, Float> { public Rotatable() { this(new RotateGestureRecognizer()); } public Rotatable(RotateGestureRecognizer gestureRecognizer) { super(gestureRecognizer); } @Override protected void onApply( MotionRuntime runtime, MotionObservable<RotateGestureRecognizer> stream, final View target,
ConstraintApplicator<Float> constraints) {
0
B2MSolutions/reyna
reyna-test/src/com/b2msolutions/reyna/DispatcherTest.java
[ "public enum Result {\n OK, PERMANENT_ERROR, TEMPORARY_ERROR, BLACKOUT, NOTCONNECTED\n}", "public class Time {\n\n private final int minuteOfDay;\n\n public Time(int hour, int minute) {\n if(hour >= 24 || minute >= 60 || hour < 0 || minute < 0) {\n throw new InvalidParameterException(\"Invalid time\");\n }\n\n this.minuteOfDay = (hour * 60) + minute;\n }\n\n public Time(int minuteOfDay) {\n if(minuteOfDay < 0 || minuteOfDay >= 1440) {\n throw new InvalidParameterException(\"Invalid minute of day\");\n }\n\n this.minuteOfDay = minuteOfDay;\n }\n\n public Time() {\n Calendar cal = Calendar.getInstance();\n this.minuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);\n }\n\n public int getMinuteOfDay() {\n return minuteOfDay;\n }\n\n public boolean isBeforeOrEqualTo(Time other) {\n return this.minuteOfDay <= other.minuteOfDay;\n }\n\n public boolean isAfterOrEqualTo(Time other) {\n return this.minuteOfDay >= other.minuteOfDay;\n }\n}", "public class TimeRange {\n\n private final Time from;\n\n private final Time to;\n\n public TimeRange(Time from, Time to) {\n this.from = from;\n this.to = to;\n }\n\n public Time getTo() {\n return to;\n }\n\n public Time getFrom() {\n return from;\n }\n\n public boolean contains(Time time) {\n if(from.getMinuteOfDay() == to.getMinuteOfDay()) return false;\n\n if(this.to.isAfterOrEqualTo(this.from)) {\n return time.isAfterOrEqualTo(this.from) && time.isBeforeOrEqualTo(this.to);\n } else {\n return time.isAfterOrEqualTo(this.from) || time.isBeforeOrEqualTo(this.to);\n }\n }\n}", "public class HttpPost extends org.apache.http.client.methods.HttpPost {\n public void setEntity(String content) throws UnsupportedEncodingException {\n super.setEntity(new StringEntity(content));\n }\n}", "@Implements(AndroidHttpClient.class)\npublic class ShadowAndroidHttpClient {\n @RealObject\n private AndroidHttpClient client;\n\n private HttpClient httpClient = new DefaultHttpClient();\n\n @Implementation\n public static AndroidHttpClient newInstance(String userAgent) {\n return newInstanceOf(AndroidHttpClient.class);\n }\n\n @Implementation\n public static AndroidHttpClient newInstance(String userAgent, Context context) {\n return newInstanceOf(AndroidHttpClient.class);\n }\n\n @Implementation\n public static AbstractHttpEntity getCompressedEntity(byte[] data, android.content.ContentResolver resolver) throws java.io.IOException\n {\n AbstractHttpEntity entity;\n if (data.length < getMinGzipSize(resolver)) {\n entity = new ByteArrayEntity(data);\n } else {\n ByteArrayOutputStream arr = new ByteArrayOutputStream();\n OutputStream zipper = new GZIPOutputStream(arr);\n zipper.write(data);\n zipper.close();\n entity = new ByteArrayEntity(arr.toByteArray());\n entity.setContentEncoding(\"gzip\");\n }\n return entity;\n }\n\n @Implementation\n public HttpParams getParams() {\n return httpClient.getParams();\n }\n\n @Implementation\n public ClientConnectionManager getConnectionManager() {\n return httpClient.getConnectionManager();\n }\n\n @Implementation\n public HttpResponse execute(HttpUriRequest httpUriRequest) throws IOException, ClientProtocolException {\n return httpClient.execute(httpUriRequest);\n }\n\n @Implementation\n public HttpResponse execute(HttpUriRequest httpUriRequest, HttpContext httpContext) throws IOException, ClientProtocolException {\n return httpClient.execute(httpUriRequest, httpContext);\n }\n\n @Implementation\n public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest) throws IOException, ClientProtocolException {\n return httpClient.execute(httpHost, httpRequest);\n }\n\n @Implementation\n public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException, ClientProtocolException {\n return httpClient.execute(httpHost, httpRequest, httpContext);\n }\n\n @Implementation\n public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {\n return httpClient.execute(httpUriRequest, responseHandler);\n }\n\n @Implementation\n public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws IOException, ClientProtocolException {\n return httpClient.execute(httpUriRequest, responseHandler, httpContext);\n }\n\n @Implementation\n public <T> T execute(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {\n return httpClient.execute(httpHost, httpRequest, responseHandler);\n }\n\n @Implementation\n public <T> T execute(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws IOException, ClientProtocolException {\n return httpClient.execute(httpHost, httpRequest, responseHandler, httpContext);\n }\n\n @Implementation\n public static long getMinGzipSize(ContentResolver resolver) {\n return 10;\n }\n}", "public class Clock {\n public long getCurrentTimeMillis() {\n return System.currentTimeMillis();\n }\n}", "public class Message implements Serializable {\n private static final long serialVersionUID = 6230786319646630263L;\n\n private Long id;\n\n private String url;\n\n private String body;\n\n private Header[] headers;\n\n public Message(URI uri, String body, Header[] headers) {\n this(null, uri, body, headers);\n }\n\n public Message(Long id, URI uri, String body, Header[] headers) {\n\n this.id = id;\n\n this.url = uri.toString();\n this.body = body;\n this.headers = headers;\n if(this.headers == null) {\n this.headers = new Header[0];\n }\n }\n\n public Long getId() {\n return this.id;\n }\n\n public String getUrl() {\n return this.url;\n }\n\n public URI getURI() {\n try {\n return new URI(this.url);\n } catch (URISyntaxException e) {\n return null;\n }\n }\n\n public void addHeader(Header header) {\n ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(this.headers));\n headerList.add(header);\n this.headers = new Header[headerList.size()];\n headerList.toArray(this.headers);\n }\n\n public String getBody() {\n return this.body;\n }\n\n public Header[] getHeaders() {\n return this.headers;\n }\n}", "public class Preferences {\n\n private final Context context;\n private final String FROM = \"CELLULAR_DATA_BLACKOUT_FROM\";\n private final String TO = \"CELLULAR_DATA_BLACKOUT_TO\";\n private final String STORAGE_SIZE = \"STORAGE_SIZE\";\n private final String WLAN_RANGE = \"WLAN_RANGE\";\n private final String WWAN_RANGE = \"WWAN_RANGE\";\n private final String WWAN_ROAMING_BLACKOUT = \"WWAN_ROAMING_BLACKOUT\";\n private final String ON_CHARGE_BLACKOUT = \"ON_CHARGE_BLACKOUT\";\n private final String OFF_CHARGE_BLACKOUT = \"OFF_CHARGE_BLACKOUT\";\n private final String BATCH_UPLOAD = \"BATCH_UPLOAD\";\n private final String BATCH_UPLOAD_URI = \"BATCH_UPLOAD_URI\";\n private final String BATCH_UPLOAD_INTERVAL = \"BATCH_UPLOAD_INTERVAL\";\n private final String WWAN_BLACKOUT_START = \"WWAN_BLACKOUT_START\";\n private final String WWAN_BLACKOUT_END = \"WWAN_BLACKOUT_END\";\n\n public Preferences(Context context) {\n this.context = context;\n }\n\n public void saveCellularDataBlackout(TimeRange timeRange) {\n if (timeRange == null) {\n return;\n }\n\n int from = timeRange.getFrom().getMinuteOfDay();\n int to = timeRange.getTo().getMinuteOfDay();\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sp.edit();\n editor.putInt(FROM, from);\n editor.putInt(TO, to);\n editor.apply();\n }\n\n public TimeRange getCellularDataBlackout() {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n int from = sp.getInt(FROM, -1);\n int to = sp.getInt(TO, -1);\n\n if (from == -1 || to == -1) {\n return null;\n }\n\n return new TimeRange(new Time(from), new Time(to));\n }\n\n public void resetCellularDataBlackout() {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sp.edit();\n editor.remove(FROM);\n editor.remove(TO);\n editor.apply();\n }\n\n public long getStorageSize() {\n return this.getLong(STORAGE_SIZE, -1);\n }\n\n public void saveStorageSize(long value) {\n this.putLong(STORAGE_SIZE, value);\n }\n\n public void resetStorageSize() {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor edit = sp.edit();\n edit.remove(STORAGE_SIZE);\n edit.apply();\n }\n\n public void saveWlanBlackout(String value) {\n this.putBlackoutRange(WLAN_RANGE, value);\n }\n\n public String getWlanBlackout() {\n return this.getString(WLAN_RANGE, \"\");\n }\n\n public void saveWwanBlackout(String value) {\n this.putBlackoutRange(WWAN_RANGE, value);\n }\n\n public String getWwanBlackout() {\n return this.getString(WWAN_RANGE, \"\");\n }\n\n public void saveWwanRoamingBlackout(boolean value) {\n this.putBoolean(WWAN_ROAMING_BLACKOUT, value);\n }\n\n public boolean canSendOnRoaming() {\n return !this.getBoolean(WWAN_ROAMING_BLACKOUT, true);\n }\n\n public void saveOnChargeBlackout(boolean value) {\n this.putBoolean(ON_CHARGE_BLACKOUT, value);\n }\n\n public boolean canSendOnCharge() {\n return !this.getBoolean(ON_CHARGE_BLACKOUT, false);\n }\n\n public void saveOffChargeBlackout(boolean value) {\n this.putBoolean(OFF_CHARGE_BLACKOUT, value);\n }\n\n public boolean canSendOffCharge() {\n return !this.getBoolean(OFF_CHARGE_BLACKOUT, false);\n }\n\n public void saveBatchUpload(boolean value) {\n this.putBoolean(BATCH_UPLOAD, value);\n }\n\n public boolean getBatchUpload() {\n return this.getBoolean(BATCH_UPLOAD, false);\n }\n\n public void saveBatchUploadUrl(URI value) {\n this.putString(BATCH_UPLOAD_URI, value.toString());\n }\n\n public URI getBatchUploadUrl() {\n String url = this.getString(BATCH_UPLOAD_URI, \"\");\n if (TextUtils.isEmpty(url)) {\n return null;\n }\n\n return URI.create(url);\n }\n\n public void saveBatchUploadCheckInterval(long value) {\n this.putLong(BATCH_UPLOAD_INTERVAL, value);\n }\n\n public long getBatchUploadCheckInterval() {\n return this.getLong(BATCH_UPLOAD_INTERVAL, AlarmManager.INTERVAL_HALF_DAY / 2);\n }\n\n public void putLong(String key, long value) {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor edit = sp.edit();\n edit.putLong(key, value);\n edit.apply();\n }\n\n public long getLong(String key, long defaultValue) {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n return sp.getLong(key, defaultValue);\n }\n\n protected boolean isBlackoutRangeValid(String value) {\n String[] splitRanges = value.split(\",\");\n for (String range : splitRanges) {\n if (!range.matches(\"[0-9][0-9]:[0-9][0-9]-[0-9][0-9]:[0-9][0-9]\")) {\n return false;\n }\n }\n return true;\n }\n\n private void putBoolean(String key, boolean value) {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor edit = sp.edit();\n edit.putBoolean(key, value);\n edit.apply();\n }\n\n private void putString(String key, String value) {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor edit = sp.edit();\n edit.putString(key, value);\n edit.apply();\n }\n\n private void putBlackoutRange(String key, String blackoutRange) {\n String value = isBlackoutRangeValid(blackoutRange) ? blackoutRange : \"\";\n putString(key, value);\n }\n\n private boolean getBoolean(String key, boolean defaultValue) {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n return sp.getBoolean(key, defaultValue);\n }\n\n private String getString(String key, String defaultValue) {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n return sp.getString(key, defaultValue);\n }\n\n public long getNonRecurringWwanBlackoutStartTime(long defaultValue) {\n String res = this.getString(WWAN_BLACKOUT_START, null);\n if(res == null) return defaultValue;\n\n return Long.parseLong(res);\n }\n\n public long getNonRecurringWwanBlackoutEndTime(long defaultValue) {\n String res = this.getString(WWAN_BLACKOUT_END, null);\n if(res == null) return defaultValue;\n\n return Long.parseLong(res);\n }\n\n public String getNonRecurringWwanBlackoutStartTimeAsString() {\n return this.getString(WWAN_BLACKOUT_START, null);\n }\n\n public String getNonRecurringWwanBlackoutEndTimeAsString() {\n return this.getString(WWAN_BLACKOUT_END, null);\n }\n\n public void saveNonRecurringWwanBlackoutStartTime(long startTimeUtc) {\n this.putString(WWAN_BLACKOUT_START, String.valueOf(startTimeUtc));\n }\n\n public void saveNonRecurringWwanBlackoutEndTime(long endTimeUtc) {\n this.putString(WWAN_BLACKOUT_END, String.valueOf(endTimeUtc));\n }\n\n public void resetNonRecurringWwanBlackout() {\n SharedPreferences sp = this.context.getSharedPreferences(Preferences.class.getName(), Context.MODE_PRIVATE);\n SharedPreferences.Editor edit = sp.edit();\n edit.remove(WWAN_BLACKOUT_START);\n edit.remove(WWAN_BLACKOUT_END);\n edit.apply();\n }\n}" ]
import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.b2msolutions.reyna.Dispatcher.Result; import com.b2msolutions.reyna.blackout.Time; import com.b2msolutions.reyna.blackout.TimeRange; import com.b2msolutions.reyna.http.HttpPost; import com.b2msolutions.reyna.shadows.ShadowAndroidHttpClient; import com.b2msolutions.reyna.system.Clock; import com.b2msolutions.reyna.system.Message; import com.b2msolutions.reyna.system.Preferences; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowConnectivityManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.zip.GZIPOutputStream; import static junit.framework.Assert.assertFalse; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static org.robolectric.Shadows.shadowOf;
package com.b2msolutions.reyna; @Config(shadows = {ShadowAndroidHttpClient.class}) @RunWith(RobolectricTestRunner.class) public class DispatcherTest { private Context context; private Intent batteryStatus; @Mock NetworkInfo networkInfo; @Mock Date now; @Before public void setup() { MockitoAnnotations.initMocks(this); context = RuntimeEnvironment.application.getApplicationContext(); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); ShadowConnectivityManager shadowConnectivityManager = shadowOf(connectivityManager); shadowConnectivityManager.setActiveNetworkInfo(networkInfo); when(networkInfo.getType()).thenReturn(ConnectivityManager.TYPE_WIFI); when(networkInfo.isConnectedOrConnecting()).thenReturn(true); } @Test public void sendMessageHappyPathShouldSetExecuteCorrectHttpPostAndReturnOK() throws URISyntaxException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException { Message message = RepositoryTest.getMessageWithHeaders(); StatusLine statusLine = mock(StatusLine.class); when(statusLine.getStatusCode()).thenReturn(200); HttpResponse httpResponse = mock(HttpResponse.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); HttpPost httpPost = mock(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); when(httpClient.execute(httpPost)).thenReturn(httpResponse); Time time = mock(Time.class); assertEquals(Result.OK, new Dispatcher().sendMessage(message, httpPost, httpClient, this.context)); this.verifyHttpPost(message, httpPost); ArgumentCaptor<StringEntity> stringEntityCaptor = ArgumentCaptor.forClass(StringEntity.class); verify(httpPost).setEntity(stringEntityCaptor.capture()); StringEntity stringEntity = stringEntityCaptor.getValue(); assertEquals(stringEntity.getContentType().getValue(), "text/plain; charset=UTF-8"); assertEquals(EntityUtils.toString(stringEntity), "body"); } @Test public void sendMessageHappyPathWithChineseCharactersShouldSetExecuteCorrectHttpPostAndReturnOK() throws URISyntaxException, IOException, KeyManagementException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException { Message message = RepositoryTest.getMessageWithHeaders("谷歌拼音输入法"); StatusLine statusLine = mock(StatusLine.class); when(statusLine.getStatusCode()).thenReturn(200); HttpResponse httpResponse = mock(HttpResponse.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); HttpPost httpPost = mock(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); when(httpClient.execute(httpPost)).thenReturn(httpResponse);
Clock clock = mock(Clock.class);
5
cloudera/director-spi
src/main/java/com/cloudera/director/spi/v2/model/util/SimpleConfiguration.java
[ "public static <T> T checkNotNull(T instance, String message) {\n if (instance == null) {\n throw new NullPointerException(message);\n }\n return instance;\n}", "public interface ConfigurationProperty extends Property<ConfigurationProperty.Widget> {\n\n /**\n * Represents the widget used to display and edit a configuration property.\n */\n enum Widget {\n\n /**\n * Radio button widget.\n */\n RADIO,\n\n /**\n * Checkbox widget.\n */\n CHECKBOX,\n\n /**\n * Text box widget.\n */\n TEXT,\n\n /**\n * Password widget.\n */\n PASSWORD,\n\n /**\n * Numeric widget.\n */\n NUMBER,\n\n /**\n * Text area widget.\n */\n TEXTAREA,\n\n /**\n * File upload widget.\n */\n FILE,\n\n /**\n * List widget with fixed set of values.\n */\n LIST,\n\n /**\n * List widget that supports typing additional values.\n */\n OPENLIST,\n\n /**\n * Multiple selection widget for a fixed set of values.\n */\n MULTI,\n\n /**\n * Multiple selection widget that supports typing additional values.\n */\n OPENMULTI\n }\n\n /**\n * Represents an attribute of a configuration property that can be localized.\n */\n enum ConfigurationPropertyLocalizableAttribute implements LocalizableAttribute {\n\n /**\n * Missing value error message attribute.\n */\n MISSING_VALUE_ERROR_MESSAGE(\"missingValueErrorMessage\"),\n\n /**\n * Placeholder message attribute.\n */\n PLACEHOLDER(\"placeholder\"),\n\n /**\n * Valid values message attribute.\n */\n VALID_VALUES(\"validValues\");\n\n /**\n * The key component, used in building a localization key.\n */\n private final String keyComponent;\n\n /**\n * Creates a localizable attribute with the specified parameters.\n *\n * @param keyComponent the key component, used in building a localization key\n */\n private ConfigurationPropertyLocalizableAttribute(String keyComponent) {\n this.keyComponent = keyComponent;\n }\n\n /**\n * Returns the key component, used in building a localization key.\n *\n * @return the key component, used in building a localization key\n */\n public String getKeyComponent() {\n return keyComponent;\n }\n }\n\n /**\n * Returns the configuration key.\n *\n * @return the configuration key\n */\n String getConfigKey();\n\n /**\n * Returns whether the configuration property is required.\n *\n * @return whether the configuration property is required\n */\n boolean isRequired();\n\n /**\n * Returns the default value of the configuration property.\n *\n * @return the default value of the configuration property\n */\n String getDefaultValue();\n\n /**\n * Returns the human-readable placeholder message when no value has been set for a\n * configuration property.\n\n *\n * @param localizationContext the localization context\n * @return the human-readable placeholder message when no value has been set for a\n * configuration property\n */\n String getPlaceholder(LocalizationContext localizationContext);\n\n /**\n * Returns the localized human-readable error message for when a required configuration property\n * is missing.\n *\n * @param localizationContext the localization context\n * @return the localized human-readable error message for when a required configuration property\n * is missing\n */\n String getMissingValueErrorMessage(LocalizationContext localizationContext);\n\n /**\n * Returns a list of valid values for the configuration property with localized labels. Normally\n * applies to properties that use LIST, OPENLIST, MULTI, or OPENMULTI widgets, but can apply to\n * other widget types.\n *\n * @param localizationContext the localizationContext\n * @return the valid values for the configuration property\n */\n List<ConfigurationPropertyValue> getValidValues(LocalizationContext localizationContext);\n}", "public interface ConfigurationPropertyToken {\n\n /**\n * Returns the configuration property.\n *\n * @return the configuration property\n */\n ConfigurationProperty unwrap();\n}", "public interface Configured {\n\n /**\n * Returns the unmodifiable map of configuration parameter values.\n *\n * @param localizationContext the localization context\n * @return the unmodifiable map of configuration parameter values\n */\n Map<String, String> getConfiguration(LocalizationContext localizationContext);\n\n /**\n * Returns the value of the specified configuration property, or the default value if the value\n * is not present and the configuration property is optional.\n *\n * @param token the configuration property token\n * @param localizationContext the localization context\n * @return the value of the specified configuration property, or the default value if the value\n * is not present and the configuration property is optional\n * @throws IllegalArgumentException if the specified configuration property is not present and\n * required\n */\n String getConfigurationValue(ConfigurationPropertyToken token,\n LocalizationContext localizationContext);\n\n /**\n * Returns the value of the specified configuration property, or the default value if the value\n * is not present and the configuration property is optional.\n *\n * @param property the configuration property\n * @param localizationContext the localization context\n * @return the value of the specified configuration property, or the default value if the value\n * is not present and the configuration property is optional\n * @throws IllegalArgumentException if the specified configuration property is not present and\n * required\n */\n String getConfigurationValue(ConfigurationProperty property,\n LocalizationContext localizationContext);\n}", "public interface LocalizationContext {\n\n /**\n * Localization context factory.\n */\n interface Factory {\n\n /**\n * Creates a root localization context for the specified locale.\n *\n * @param locale the locale\n * @return a root localization context for the specified locale\n */\n LocalizationContext createRootLocalizationContext(Locale locale);\n }\n\n /**\n * Returns the locale.\n *\n * @return the locale\n */\n Locale getLocale();\n\n /**\n * Returns the key prefix of the context, which can be used for property namespacing.\n *\n * @return the key prefix of the context\n */\n String getKeyPrefix();\n\n /**\n * Returns a localized value for the specified localization key suffix components,\n * or the specified default value if a localized value cannot be determined.\n *\n * @param defaultValue the default value to return if a localized value cannot be determined\n * @param keyComponents the localization key suffix components\n * @return a localized value for the specified localization key suffix components,\n * or the specified default value if a localized value cannot be determined\n */\n String localize(String defaultValue, String... keyComponents);\n}" ]
import static com.cloudera.director.spi.v2.util.Preconditions.checkNotNull; import com.cloudera.director.spi.v2.model.ConfigurationProperty; import com.cloudera.director.spi.v2.model.ConfigurationPropertyToken; import com.cloudera.director.spi.v2.model.Configured; import com.cloudera.director.spi.v2.model.LocalizationContext; import java.util.Collections; import java.util.HashMap; import java.util.Map;
// (c) Copyright 2015 Cloudera, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.director.spi.v2.model.util; /** * Simple map-based configurable object implementation. */ public class SimpleConfiguration implements Configured { /** * The map of configuration values. */ private final Map<String, String> configuration; /** * Creates a simple configuration with no configuration. */ public SimpleConfiguration() { this.configuration = Collections.emptyMap(); } /** * Creates a simple configuration with the specified configuration map. * * @param configuration the map of configuration values */ public SimpleConfiguration(Map<String, String> configuration) { this.configuration = Collections.unmodifiableMap(new HashMap<String, String>( checkNotNull(configuration, "configuration is null"))); } @Override public Map<String, String> getConfiguration(LocalizationContext localizationContext) { return configuration; } @Override
public String getConfigurationValue(ConfigurationPropertyToken token,
2
encircled/Joiner
joiner-core/src/test/java/cz/encircled/joiner/core/BasicJoinTest.java
[ "public class JoinerException extends RuntimeException {\n\n public JoinerException(String message) {\n super(message);\n }\n\n public JoinerException(String message, Exception exception) {\n super(message, exception);\n }\n}", "public interface JoinerQuery<T, R> extends JoinRoot {\n\n EntityPath<T> getFrom();\n\n Expression<R> getReturnProjection();\n\n JoinerQuery<T, R> where(Predicate where);\n\n Predicate getWhere();\n\n JoinerQuery<T, R> distinct(boolean isDistinct);\n\n boolean isDistinct();\n\n JoinerQuery<T, R> groupBy(Path<?> groupBy);\n\n Path<?> getGroupBy();\n\n JoinerQuery<T, R> having(Predicate having);\n\n Predicate getHaving();\n\n /**\n * Add join graphs to the query.\n *\n * @param names names of join graphs\n * @return this\n * @see cz.encircled.joiner.query.join.JoinGraphRegistry\n */\n JoinerQuery<T, R> joinGraphs(String... names);\n\n /**\n * Add join graphs to the query.\n *\n * @param names names of join graphs\n * @return this\n * @see cz.encircled.joiner.query.join.JoinGraphRegistry\n */\n JoinerQueryBase<T, R> joinGraphs(Enum... names);\n\n /**\n * Add join graphs to the query.\n *\n * @param names names of join graphs\n * @return this\n * @see cz.encircled.joiner.query.join.JoinGraphRegistry\n */\n JoinerQueryBase<T, R> joinGraphs(Collection<?> names);\n\n Set<Object> getJoinGraphs();\n\n /**\n * Add <b>left</b> joins for specified paths\n *\n * @param paths join paths\n * @return this\n */\n JoinerQueryBase<T, R> joins(EntityPath<?>... paths);\n\n JoinerQueryBase<T, R> joins(CollectionPathBase<?, ?, ?>... path);\n\n JoinerQueryBase<T, R> joins(JoinDescription... joins);\n\n JoinerQueryBase<T, R> joins(Collection<JoinDescription> joins);\n\n Collection<JoinDescription> getJoins();\n\n JoinerQueryBase<T, R> addHint(String hint, Object value);\n\n LinkedHashMap<String, List<Object>> getHints();\n\n JoinerQueryBase<T, R> addFeatures(QueryFeature... features);\n\n JoinerQueryBase<T, R> addFeatures(Collection<QueryFeature> features);\n\n List<QueryFeature> getFeatures();\n\n /**\n * Set offset for the query results\n *\n * @param offset value\n * @return this\n */\n JoinerQuery<T, R> offset(Long offset);\n\n Long getOffset();\n\n /**\n * Set max results for the query results\n *\n * @param limit value\n * @return this\n */\n JoinerQuery<T, R> limit(Long limit);\n\n Long getLimit();\n\n JoinerQuery<T, R> asc(Expression<?> orderBy);\n\n JoinerQuery<T, R> desc(Expression<?> orderBy);\n\n List<QueryOrder> getOrder();\n\n JoinerQuery<T, R> copy();\n\n boolean isCount();\n\n}", "public class JoinerQueryBase<T, R> implements JoinerQuery<T, R>, JoinRoot {\n\n private final EntityPath<T> from;\n private Expression<R> returnProjection;\n\n private Predicate where;\n\n /**\n * Alias to join\n */\n private Map<String, JoinDescription> joins = new LinkedHashMap<>(8);\n\n private Set<Object> joinGraphs = new LinkedHashSet<>();\n\n private boolean distinct = true;\n\n private Path<?> groupBy;\n\n private Predicate having;\n\n private LinkedHashMap<String, List<Object>> hints = new LinkedHashMap<>(2);\n\n private List<QueryFeature> features = new ArrayList<>(2);\n\n private Long offset;\n\n private Long limit;\n\n private List<QueryOrder> orders = new ArrayList<>(2);\n\n private boolean isCount;\n\n public JoinerQueryBase(EntityPath<T> from) {\n this.from = from;\n }\n\n JoinerQueryBase(EntityPath<T> from, boolean isCount) {\n this.from = from;\n this.isCount = isCount;\n }\n\n public JoinerQueryBase(EntityPath<T> from, Expression<R> returnProjection) {\n this.from = from;\n this.returnProjection = returnProjection;\n }\n\n @Override\n public Predicate getWhere() {\n return where;\n }\n\n @Override\n public JoinerQueryBase<T, R> distinct(boolean isDistinct) {\n distinct = isDistinct;\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> groupBy(Path<?> groupBy) {\n this.groupBy = groupBy;\n return this;\n }\n\n @Override\n public Path<?> getGroupBy() {\n return groupBy;\n }\n\n @Override\n public boolean isDistinct() {\n return distinct;\n }\n\n @Override\n public JoinerQueryBase<T, R> where(Predicate where) {\n this.where = where;\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> having(Predicate having) {\n this.having = having;\n return this;\n }\n\n @Override\n public Predicate getHaving() {\n return having;\n }\n\n @Override\n public EntityPath<T> getFrom() {\n return from;\n }\n\n @Override\n public Set<Object> getJoinGraphs() {\n return joinGraphs;\n }\n\n @Override\n public Map<String, JoinDescription> getAllJoins() {\n return joins;\n }\n\n @Override\n public Collection<JoinDescription> getJoins() {\n return joins.values();\n }\n\n @Override\n public JoinerQueryBase<T, R> joinGraphs(final String... names) {\n Collections.addAll(joinGraphs, names);\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> joinGraphs(final Enum... names) {\n Collections.addAll(joinGraphs, names);\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> joinGraphs(Collection<?> names) {\n Assert.notNull(names);\n\n joinGraphs.addAll(names);\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> joins(EntityPath<?>... paths) {\n for (EntityPath<?> path : paths) {\n Assert.notNull(path);\n\n addJoin(J.left(path));\n }\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> joins(CollectionPathBase<?, ?, ?>... paths) {\n for (CollectionPathBase<?, ?, ?> path : paths) {\n joins(((EntityPath<?>) JoinerUtils.getDefaultPath(path)));\n }\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> joins(JoinDescription... joins) {\n for (JoinDescription join : joins) {\n Assert.notNull(join);\n\n addJoin(join);\n }\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> joins(Collection<JoinDescription> joins) {\n Assert.notNull(joins);\n\n joins.forEach(this::addJoin);\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> addHint(String hint, Object value) {\n Assert.notNull(hint);\n\n hints.computeIfAbsent(hint, h -> new ArrayList<>(2));\n hints.get(hint).add(value);\n\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> addFeatures(QueryFeature... features) {\n Assert.notNull(features);\n\n Collections.addAll(this.features, features);\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> addFeatures(Collection<QueryFeature> features) {\n Assert.notNull(features);\n\n this.features.addAll(features);\n return this;\n }\n\n @Override\n public List<QueryFeature> getFeatures() {\n return features;\n }\n\n @Override\n public LinkedHashMap<String, List<Object>> getHints() {\n return hints;\n }\n\n @Override\n public Expression<R> getReturnProjection() {\n return returnProjection;\n }\n\n @Override\n public JoinerQueryBase<T, R> offset(Long offset) {\n this.offset = offset;\n return this;\n }\n\n @Override\n public Long getOffset() {\n return offset;\n }\n\n @Override\n public JoinerQueryBase<T, R> limit(Long limit) {\n this.limit = limit;\n return this;\n }\n\n @Override\n public Long getLimit() {\n return limit;\n }\n\n @Override\n public JoinerQueryBase<T, R> asc(Expression<?> orderBy) {\n Assert.notNull(orderBy);\n\n orders.add(new QueryOrder<>(true, orderBy));\n return this;\n }\n\n @Override\n public JoinerQueryBase<T, R> desc(Expression<?> orderBy) {\n Assert.notNull(orderBy);\n\n orders.add(new QueryOrder<>(false, orderBy));\n return this;\n }\n\n @Override\n public List<QueryOrder> getOrder() {\n return orders;\n }\n\n @Override\n public JoinerQuery<T, R> copy() {\n JoinerQueryBase<T, R> copy = Q.select(returnProjection)\n .from(from)\n .joinGraphs(new LinkedHashSet<>(joinGraphs))\n .joins(getJoins().stream().map(JoinDescription::copy).collect(Collectors.toList()))\n .addFeatures(new ArrayList<>(getFeatures()))\n .where(where)\n .offset(offset)\n .limit(limit)\n .groupBy(groupBy)\n .having(this.having);\n\n copy.isCount = isCount;\n copy.orders = new ArrayList<>(orders);\n\n // TODO deep-deep copy?\n copy.hints = new LinkedHashMap<>(hints);\n\n return copy;\n }\n\n @Override\n public boolean isCount() {\n return isCount;\n }\n\n public void count() {\n isCount = true;\n }\n\n @Override\n public String toString() {\n return \"JoinerQueryBase{\" +\n \"from=\" + from +\n \", returnProjection=\" + returnProjection +\n \", where=\" + where +\n \", joins=\" + joins +\n \", joinGraphs=\" + joinGraphs +\n \", distinct=\" + distinct +\n \", groupBy=\" + groupBy +\n \", having=\" + having +\n \", hints=\" + hints +\n \", features=\" + features +\n \", offset=\" + offset +\n \", limit=\" + limit +\n \", orders=\" + orders +\n \", isCount=\" + isCount +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof JoinerQueryBase)) return false;\n JoinerQueryBase<?, ?> that = (JoinerQueryBase<?, ?>) o;\n return distinct == that.distinct &&\n isCount == that.isCount &&\n Objects.equals(from, that.from) &&\n Objects.equals(returnProjection, that.returnProjection) &&\n Objects.equals(where, that.where) &&\n Objects.equals(joins, that.joins) &&\n Objects.equals(joinGraphs, that.joinGraphs) &&\n Objects.equals(groupBy, that.groupBy) &&\n Objects.equals(having, that.having) &&\n Objects.equals(hints, that.hints) &&\n Objects.equals(features, that.features) &&\n Objects.equals(offset, that.offset) &&\n Objects.equals(limit, that.limit) &&\n Objects.equals(orders, that.orders);\n }\n\n @Override\n public int hashCode() {\n\n return Objects.hash(from, returnProjection, where, joins, joinGraphs, distinct, groupBy, having, hints, features, offset, limit, orders, isCount);\n }\n}", "public class Q {\n\n /**\n * Build tuple query projections (i.e. select clause)\n *\n * @param returnProjections path to query projection\n * @return joiner query with custom tuple query projection\n */\n public static FromBuilder<Tuple> select(Expression<?>... returnProjections) {\n Assert.notNull(returnProjections);\n return new TupleQueryFromBuilder(returnProjections);\n }\n\n /**\n * Build query projection (i.e. select clause)\n *\n * @param returnProjection path to query projection\n * @param <R> type of source entity\n * @return joiner query with custom query projection\n */\n public static <R> FromBuilder<R> select(Expression<R> returnProjection) {\n return new ExpressionQueryFromBuilder<>(returnProjection);\n }\n\n /**\n * Build \"from\" clause of query\n *\n * @param from alias of source entity\n * @param <T> type of source entity\n * @return joiner query\n */\n public static <T> JoinerQuery<T, T> from(EntityPath<T> from) {\n return new JoinerQueryBase<>(from, from);\n }\n\n /**\n * Build count query\n *\n * @param from alias of source entity\n * @param <T> type of source entity\n * @return count joiner query\n */\n public static <T> JoinerQuery<T, Long> count(EntityPath<T> from) {\n JoinerQueryBase<T, Long> request = new JoinerQueryBase<>(from, true);\n request.distinct(false);\n return request;\n }\n\n}", "public class J {\n\n /**\n * Aliases of nested joins are determined at runtime. To refer a nested join, this method should be used to get a correct alias.\n * For example, there is a query\n * <p>\n * <code>Q.from(QGroup.group).joins(J.left(QPerson.person).nested(J.left(QContact.contact)))</code>\n * </p>\n * To refer a <code>Contact</code> entity in the 'where' clause, one should use <code>J.path(QPerson.person.contacts).number.eq(12345)</code>\n *\n * @param path path on parent entity\n * @param <T> any entity path\n * @return entity path with correct alias\n */\n @SuppressWarnings(\"unchcecked\")\n public static <P extends SimpleExpression<?>, T extends EntityPath<P>> P path(CollectionPathBase<?, ?, P> path) {\n Assert.notNull(path);\n EntityPath<?> current = JoinerUtils.getDefaultPath(path);\n return ReflectionUtils.instantiate(current.getClass(), current + \"_on_\" + path.getMetadata().getParent());\n }\n\n /**\n * Aliases of nested joins are determined at runtime. To refer a nested join, this method should be used to get a correct alias.\n * For example, there is a query\n * <p>\n * <code>Q.from(QGroup.group).joins(J.left(QPerson.person).nested(J.left(QContact.contact)))</code>\n * </p>\n * To refer a <code>Contact</code> entity in the 'where' clause, one should use <code>J.path(QPerson.person, QContact.contact).number.eq(12345)</code>\n *\n * @param parent parent join path\n * @param path target join path\n * @param <T> any entity path\n * @return entity path with correct alias\n */\n @SuppressWarnings(\"unchcecked\")\n public static <T extends EntityPath> T path(EntityPath<?> parent, T path) {\n if (parent != null) {\n return ReflectionUtils.instantiate(path.getClass(), path.toString() + \"_on_\" + parent.toString());\n }\n return path;\n }\n\n /**\n * Aliases of nested joins are determined at runtime. To refer a nested join, this method should be used to get a correct alias.\n * For example, there is a query\n * <p>\n * <code>Q.from(QGroup.group).joins(J.left(QPerson.person).nested(J.left(QContact.contact).nested(QStatus.status)))</code>\n * </p>\n * To refer a <code>Status</code> entity in the 'where' clause, one should use <code>J.path(QPerson.person, QContact.contact. QStatus.status).state.eq(\"active\")</code>\n *\n * @param grandFather parent of parent join path\n * @param father parent join path\n * @param path target join path\n * @param <T> any entity path\n * @return entity path with correct alias\n */\n @SuppressWarnings(\"unchcecked\")\n public static <T extends EntityPath> T path(EntityPath<?> grandFather, EntityPath<?> father, T path) {\n Assert.notNull(father);\n Assert.notNull(grandFather);\n\n EntityPath<?> parentPath = path(grandFather, father);\n\n return path(parentPath, path);\n }\n\n /**\n * Add <b>left</b> join for given <code>path</code>\n *\n * @param path alias of object to be joined\n * @return join description\n */\n public static JoinDescription left(EntityPath<?> path) {\n return getBasicJoin(path).left();\n }\n\n /**\n * Add <b>right</b> join for given <code>path</code>\n *\n * @param path alias of object to be joined\n * @return join description\n */\n public static JoinDescription right(EntityPath<?> path) {\n return getBasicJoin(path).right();\n }\n\n /**\n * Add <b>left</b> join for given <code>path</code>\n *\n * @param path path to an object to be joined\n * @return join description\n */\n public static JoinDescription left(CollectionPathBase<?, ?, ?> path) {\n return getBasicJoin(JoinerUtils.getDefaultPath(path)).left();\n }\n\n /**\n * Add <b>inner</b> join for given <code>path</code>\n *\n * @param path alias of object to be joined\n * @return join description\n */\n public static JoinDescription inner(EntityPath<?> path) {\n return getBasicJoin(path).inner();\n }\n\n /**\n * Add <b>inner</b> join for given <code>path</code>\n *\n * @param path path to an object to be joined\n * @return join description\n */\n public static JoinDescription inner(CollectionPathBase<?, ?, ?> path) {\n return getBasicJoin(JoinerUtils.getDefaultPath(path)).inner();\n }\n\n /**\n * Collect all joins and its children to single collection\n *\n * @param joins root joins\n * @return all joins, including children\n */\n public static List<JoinDescription> unrollChildrenJoins(Collection<JoinDescription> joins) {\n List<JoinDescription> collection = new LinkedList<>();\n\n for (JoinDescription joinDescription : joins) {\n unrollChildrenInternal(joinDescription, collection);\n }\n\n return collection;\n }\n\n private static void unrollChildrenInternal(JoinDescription join, List<JoinDescription> collection) {\n collection.add(join);\n for (JoinDescription child : join.getChildren()) {\n unrollChildrenInternal(child, collection);\n }\n }\n\n private static JoinDescription getBasicJoin(EntityPath<?> path) {\n Assert.notNull(path);\n\n return new JoinDescription(path);\n }\n\n}", "public class JoinDescription implements JoinRoot {\n\n private final EntityPath<?> originalAlias;\n private CollectionPathBase<?, ?, ?> collectionPath;\n private EntityPath<?> singlePath;\n private EntityPath<?> alias;\n private JoinType joinType = JoinType.LEFTJOIN;\n\n private boolean fetch = true;\n\n private Predicate on;\n\n private JoinDescription parent;\n\n private Map<String, JoinDescription> children = new LinkedHashMap<>(4);\n\n public JoinDescription(EntityPath<?> alias) {\n Assert.notNull(alias);\n\n originalAlias = alias;\n alias(alias);\n }\n\n public JoinDescription copy() {\n JoinDescription copy = new JoinDescription(originalAlias);\n copy.alias = alias;\n\n copy.children = new HashMap<>(children.size());\n children.forEach((k, v) -> copy.children.put(k, v.copy()));\n\n copy.fetch = fetch;\n copy.on = on;\n copy.parent = parent;\n copy.collectionPath = collectionPath;\n copy.singlePath = singlePath;\n copy.joinType = joinType;\n return copy;\n }\n\n public boolean isFetch() {\n return fetch;\n }\n\n public JoinDescription fetch(boolean fetch) {\n this.fetch = fetch;\n return this;\n }\n\n public JoinDescription on(Predicate on) {\n this.on = on;\n return this;\n }\n\n public Predicate getOn() {\n return on;\n }\n\n public JoinType getJoinType() {\n return joinType;\n }\n\n private JoinDescription joinType(final JoinType joinType) {\n this.joinType = joinType;\n return this;\n }\n\n public EntityPath<?> getAlias() {\n return alias;\n }\n\n public EntityPath<?> getOriginalAlias() {\n return originalAlias;\n }\n\n /**\n * Set different alias for current join\n */\n private JoinDescription alias(EntityPath<?> alias) {\n this.alias = alias;\n return this;\n }\n\n public CollectionPathBase<?, ?, ?> getCollectionPath() {\n return collectionPath;\n }\n\n public EntityPath<?> getSinglePath() {\n return singlePath;\n }\n\n public JoinDescription singlePath(EntityPath<?> path) {\n Assert.notNull(path);\n\n singlePath = path;\n collectionPath = null;\n return this;\n }\n\n public JoinDescription collectionPath(CollectionPathBase<?, ?, ?> path) {\n Assert.notNull(path);\n\n collectionPath = path;\n singlePath = null;\n return this;\n }\n\n public boolean isCollectionPath() {\n return collectionPath != null;\n }\n\n public JoinDescription inner() {\n return joinType(JoinType.INNERJOIN);\n }\n\n public JoinDescription left() {\n return joinType(JoinType.LEFTJOIN);\n }\n\n public JoinDescription right() {\n return joinType(JoinType.RIGHTJOIN);\n }\n\n /**\n * Add children joins to current join\n *\n * @param joins children joins\n * @return current join\n */\n public JoinDescription nested(JoinDescription... joins) {\n for (JoinDescription join : joins) {\n join.parent = this;\n join.alias(J.path(this.getAlias(), join.getOriginalAlias()));\n addJoin(join);\n\n reAliasChildren(join);\n }\n\n return this;\n }\n\n /**\n * Re-alias due to order of 'nested' method execution (the very last nested is executed first and it's parent is not re-aliased yet)\n */\n private void reAliasChildren(JoinDescription join) {\n for (JoinDescription child : join.children.values()) {\n child.alias(J.path(join.getAlias(), child.getOriginalAlias()));\n reAliasChildren(child);\n }\n }\n\n /**\n * Add children joins to current join from specified paths\n *\n * @param paths children join paths\n * @return current join\n */\n public JoinDescription nested(EntityPath<?>... paths) {\n for (EntityPath<?> path : paths) {\n nested(J.left(path));\n }\n\n return this;\n }\n\n /**\n * Add children joins to current join from specified paths\n *\n * @param paths children join paths\n * @return current join\n */\n public JoinDescription nested(CollectionPathBase<?, ?, ?>... paths) {\n for (CollectionPathBase<?, ?, ?> path : paths) {\n nested(J.left(path));\n }\n\n return this;\n }\n\n public JoinDescription getParent() {\n return parent;\n }\n\n public Collection<JoinDescription> getChildren() {\n return children.values();\n }\n\n @Override\n public Map<String, JoinDescription> getAllJoins() {\n return children;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof JoinDescription)) return false;\n\n JoinDescription that = (JoinDescription) o;\n\n if (!alias.equals(that.alias)) return false;\n return parent != null ? parent.equals(that.parent) : that.parent == null;\n\n }\n\n @Override\n public int hashCode() {\n int result = alias.hashCode();\n result = 31 * result + (parent != null ? parent.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"JoinDescription{\" +\n \"collectionPath=\" + collectionPath +\n \", singlePath=\" + singlePath +\n \", alias=\" + alias +\n '}';\n }\n\n}" ]
import com.querydsl.core.JoinType; import com.querydsl.core.Tuple; import cz.encircled.joiner.exception.JoinerException; import cz.encircled.joiner.model.*; import cz.encircled.joiner.query.JoinerQuery; import cz.encircled.joiner.query.JoinerQueryBase; import cz.encircled.joiner.query.Q; import cz.encircled.joiner.query.join.J; import cz.encircled.joiner.query.join.JoinDescription; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import javax.persistence.Persistence; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*;
package cz.encircled.joiner.core; /** * TODO cleanup * * @author Kisel on 21.01.2016. */ public class BasicJoinTest extends AbstractTest { public static final String USER_NO_ADDRESS = "user3"; @Test public void testNestedJoinAlias() {
JoinerQueryBase<Group, Group> q = Q.from(QGroup.group).joins(J.left(QUser.user1)
3
KONNEKTING/KonnektingSuite
src/main/java/de/konnekting/suite/ParameterListItem.java
[ "public class NumberParameterTextField extends ParameterTextField {\r\n \r\n private final Logger log = LoggerFactory.getLogger(getClass());\r\n\r\n private long min = 0;\r\n private long max = 0;\r\n private final boolean minMaxSet;\r\n private final ParamType paramType;\r\n \r\n private String validationError = \"\";\r\n private String lastText;\r\n \r\n public NumberParameterTextField(DeviceConfigContainer device, Parameter param, ParameterConfiguration conf) {\r\n super(device, param, conf);\r\n paramType = param.getValue().getType();\r\n\r\n // if min is set, max must also be set --> ensure and catch exception?!\r\n byte[] minRaw = param.getValue().getMin();\r\n byte[] maxRaw = param.getValue().getMax();\r\n byte[] value = conf.getValue();\r\n if (value == null) {\r\n value = param.getValue().getDefault();\r\n // enforce default value to be set/saved\r\n device.setParameterValue(param.getId(), value);\r\n log.info(\"Setting param #{} to default value '{}'\", param.getId(), Helper.bytesToHex(value));\r\n }\r\n\r\n minMaxSet = minRaw != null && maxRaw != null;\r\n\r\n // parse/read MIN/MAX values\r\n Bytes2ReadableValue b2r = new Bytes2ReadableValue();\r\n switch (paramType) {\r\n case INT_8:\r\n if (!checkParamSize(value, param, 1)) {\r\n break;\r\n }\r\n\r\n if (minMaxSet) {\r\n min = b2r.convertINT8(minRaw);\r\n max = b2r.convertINT8(maxRaw);\r\n } else {\r\n min = Byte.MIN_VALUE;\r\n max = Byte.MAX_VALUE;\r\n }\r\n break;\r\n case UINT_8:\r\n if (!checkParamSize(value, param, 1)) {\r\n break;\r\n }\r\n\r\n if (minMaxSet) {\r\n min = b2r.convertUINT8(minRaw);\r\n max = b2r.convertUINT8(maxRaw);\r\n } else {\r\n min = 0;\r\n max = 255;\r\n }\r\n break;\r\n case INT_16:\r\n if (!checkParamSize(value, param, 2)) {\r\n break;\r\n }\r\n if (minMaxSet) {\r\n min = b2r.convertINT16(minRaw);\r\n max = b2r.convertINT16(maxRaw);\r\n } else {\r\n min = Short.MIN_VALUE;\r\n max = Short.MAX_VALUE;\r\n }\r\n break;\r\n case UINT_16:\r\n if (!checkParamSize(value, param, 2)) {\r\n break;\r\n }\r\n if (minMaxSet) {\r\n min = b2r.convertUINT16(minRaw);\r\n max = b2r.convertUINT16(maxRaw);\r\n } else {\r\n min = 0;\r\n max = 65535;\r\n }\r\n break;\r\n case INT_32:\r\n if (!checkParamSize(value, param, 4)) {\r\n break;\r\n }\r\n if (minMaxSet) {\r\n min = b2r.convertINT32(minRaw);\r\n max = b2r.convertINT32(maxRaw);\r\n } else {\r\n min = Integer.MIN_VALUE;\r\n max = Integer.MAX_VALUE;\r\n }\r\n break;\r\n case UINT_32:\r\n if (!checkParamSize(value, param, 4)) {\r\n break;\r\n }\r\n if (minMaxSet) {\r\n min = b2r.convertUINT32(minRaw);\r\n max = b2r.convertUINT32(maxRaw);\r\n } else {\r\n min = 0;\r\n max = 4294967296L;\r\n }\r\n break;\r\n\r\n }\r\n\r\n \r\n setValue(value);\r\n }\r\n\r\n @Override\r\n public String getValidationErrorMessage() {\r\n return validationError;\r\n }\r\n\r\n @Override\r\n public boolean isInputValid() {\r\n \r\n boolean valid = false;\r\n\r\n if (Helper.isNumberType(paramType)) {\r\n try {\r\n long v = Long.parseLong(getText());\r\n if (v >= min && v <= max) {\r\n valid = true;\r\n } else {\r\n validationError = \"Not in range [\" + min + \"..\" + max+\"]\";\r\n }\r\n } catch (NumberFormatException ex) {\r\n validationError = \"Not a valid number: \" + getText();\r\n }\r\n } else {\r\n validationError = \"Unsupported type?! \" + paramType.toString();\r\n valid = false;\r\n }\r\n\r\n if (valid) {\r\n String text = getText();\r\n if (text!=null && !text.equals(lastText)) {\r\n byte[] value = (byte[]) getValue();\r\n device.setParameterValue(param.getId(), value);\r\n } \r\n lastText = text;\r\n }\r\n return valid;\r\n }\r\n\r\n @Override\r\n public byte[] getValue() {\r\n String text = getText();\r\n ReadableValue2Bytes r2b = new ReadableValue2Bytes();\r\n byte[] value;\r\n switch (paramType) {\r\n case INT_8:\r\n value = r2b.convertINT8(Byte.parseByte(text));\r\n break;\r\n case UINT_8:\r\n value = r2b.convertUINT8(Short.parseShort(text));\r\n break;\r\n case INT_16:\r\n value = r2b.convertINT16(Short.parseShort(text));\r\n break;\r\n case UINT_16:\r\n value = r2b.convertUINT16(Integer.parseInt(text));\r\n break;\r\n case INT_32:\r\n value = r2b.convertINT32(Integer.parseInt(text));\r\n break;\r\n case UINT_32:\r\n value = r2b.convertUINT32(Long.parseLong(text));\r\n break;\r\n default:\r\n value = null;\r\n\r\n }\r\n return value;\r\n }\r\n\r\n private void setValue(byte[] value) {\r\n if (value == null) {\r\n setText(\"\");\r\n return;\r\n }\r\n\r\n Bytes2ReadableValue b2r = new Bytes2ReadableValue();\r\n String readableValue = \"\";\r\n\r\n switch (paramType) {\r\n case INT_8:\r\n if (!checkParamSize(value, param, 1)) {\r\n break;\r\n }\r\n\r\n readableValue = String.valueOf(b2r.convertINT8(value));\r\n break;\r\n case UINT_8:\r\n if (!checkParamSize(value, param, 1)) {\r\n break;\r\n }\r\n\r\n readableValue = String.valueOf(b2r.convertUINT8(value));\r\n break;\r\n case INT_16:\r\n if (!checkParamSize(value, param, 2)) {\r\n break;\r\n }\r\n readableValue = String.valueOf(b2r.convertINT16(value));\r\n break;\r\n case UINT_16:\r\n if (!checkParamSize(value, param, 2)) {\r\n break;\r\n }\r\n readableValue = String.valueOf(b2r.convertUINT16(value));\r\n break;\r\n case INT_32:\r\n if (!checkParamSize(value, param, 4)) {\r\n break;\r\n }\r\n readableValue = String.valueOf(b2r.convertINT32(value));\r\n break;\r\n case UINT_32:\r\n if (!checkParamSize(value, param, 4)) {\r\n break;\r\n }\r\n readableValue = String.valueOf(b2r.convertUINT32(value));\r\n break;\r\n\r\n }\r\n setText(readableValue);\r\n }\r\n\r\n\r\n\r\n private boolean checkParamSize(byte[] value, Parameter param, int size) throws HeadlessException {\r\n if (value == null) {\r\n return true;\r\n }\r\n if (value.length != size) {\r\n JOptionPane.showMessageDialog(getParent(), \"Die geladene XML Datei dieses Geräts hat einen Fehler im Abschnitt:\\n\\n\"\r\n + \"<Parameter Id=\\\"\" + param.getId() + \"\\\">:\\n\\n\"\r\n + \"Der Werte Default und die optionalen Werte Min und Max müssen\\n\"\r\n + \"exakt \" + size + \" Byte lang sein, sind aber teilw. \" + value.length + \" Bytes lang.!\\n\"\r\n + \"Bitte informiere den Gerätehersteller.\", \"XML Datei ungültig\", JOptionPane.ERROR_MESSAGE);\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n}\r", "public class ParameterCombobox extends JComboBox<ParameterCombobox.ComboboxItem> implements ParameterDependency {\n\n private final Logger log = LoggerFactory.getLogger(getClass());\n\n private final ParameterConfiguration conf;\n private final Parameter param;\n private final DeviceConfigContainer device;\n\n public ParameterCombobox(DeviceConfigContainer device, Parameter param, ParameterConfiguration conf) {\n this.device = device;\n this.param = param;\n this.conf = conf;\n\n Parameter.Value valueObject = param.getValue();\n String options = valueObject.getOptions();\n\n byte[] currentValRaw = conf.getValue();\n\n if (currentValRaw == null) {\n // set to default\n currentValRaw = valueObject.getDefault();\n log.info(\"Setting param #{} to default value '{}'\", param.getId(), Helper.bytesToHex(currentValRaw));\n }\n\n List<ComboboxItem> cbitems = new ArrayList<>();\n\n StringTokenizer st = new StringTokenizer(options, \"=|\");\n int i = -1;\n int selectedIndex = -1;\n while (st.hasMoreTokens()) {\n i++;\n String val = st.nextToken();\n String representation = st.nextToken();\n ComboboxItem cbi = new ComboboxItem(val, representation);\n cbitems.add(cbi);\n if (val.equalsIgnoreCase(Helper.bytesToHex(currentValRaw))) {\n selectedIndex = i;\n }\n }\n\n setModel(new DefaultComboBoxModel<ComboboxItem>(cbitems.toArray(new ComboboxItem[]{})));\n setSelectedIndex(selectedIndex);\n save(); // ensure that default value is stored\n\n addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n save();\n RootEventBus.getDefault().post(new EventParameterChanged());\n }\n });\n }\n\n @Override\n public boolean isParameterVisible() {\n return device.isParameterEnabled(param);\n }\n\n class ComboboxItem {\n\n private final String representation;\n private final String value;\n\n private ComboboxItem(String value, String representation) {\n this.value = value;\n this.representation = representation;\n }\n\n @Override\n public String toString() {\n return representation;\n }\n\n public String getValue() {\n return value;\n }\n\n }\n\n private void save() {\n int selectedIndex = getSelectedIndex();\n ComboboxItem cbi = getItemAt(selectedIndex);\n log.info(\"Changing combo param #\" + param.getId() + \" to '\" + cbi.getValue() + \"'\");\n device.setParameterValue(param.getId(), Helper.hexToBytes(cbi.getValue()));\n }\n\n}", "public interface ParameterDependency {\n \n public boolean isParameterVisible();\n \n}", "public class RawParameterTextField extends ParameterTextField {\r\n\r\n private final Logger log = LoggerFactory.getLogger(getClass());\r\n\r\n private final ParamType paramType;\r\n\r\n private String validationError = \"\";\r\n private String lastText;\r\n private int length;\r\n\r\n public RawParameterTextField(DeviceConfigContainer device, Parameter param, ParameterConfiguration conf) {\r\n super(device, param, conf);\r\n\r\n paramType = param.getValue().getType();\r\n\r\n switch (paramType) {\r\n case RAW_1:\r\n length = 1;\r\n break;\r\n case RAW_2:\r\n length = 2;\r\n break;\r\n case RAW_3:\r\n length = 3;\r\n break;\r\n case RAW_4:\r\n length = 4;\r\n break;\r\n case RAW_5:\r\n length = 5;\r\n break;\r\n case RAW_6:\r\n length = 6;\r\n break;\r\n case RAW_7:\r\n length = 7;\r\n break;\r\n case RAW_8:\r\n length = 8;\r\n break;\r\n case RAW_9:\r\n length = 9;\r\n break;\r\n case RAW_10:\r\n length = 10;\r\n break;\r\n case RAW_11:\r\n default:\r\n length = 11;\r\n break;\r\n }\r\n\r\n // if min is set, max must also be set --> ensure and catch exception?!\r\n byte[] value = conf.getValue();\r\n if (value == null) {\r\n value = param.getValue().getDefault();\r\n // enforce default value to be set/saved\r\n device.setParameterValue(param.getId(), value);\r\n }\r\n\r\n setValue(value);\r\n }\r\n\r\n @Override\r\n public String getValidationErrorMessage() {\r\n return validationError;\r\n }\r\n\r\n @Override\r\n public boolean isInputValid() {\r\n\r\n boolean valid = false;\r\n\r\n if (Helper.isRawType(paramType)) {\r\n try {\r\n \r\n \r\n byte[] hexToBytes = Helper.hexToBytes(getText());\r\n if (hexToBytes.length!=length) {\r\n if (hexToBytes.length<length) {\r\n validationError = \"HEX value is too short. \";\r\n } else if (hexToBytes.length>length) {\r\n validationError = \"HEX value is too long. \";\r\n }\r\n validationError+=\"Required: \"+(length*2)+\" characters/\"+length+\" bytes. Found: \"+(hexToBytes.length*2)+\" characters/\"+hexToBytes.length+\" bytes!\";\r\n valid=false;\r\n } else {\r\n valid=true;\r\n }\r\n } catch (NumberFormatException ex) {\r\n validationError = \"Not a hex value: [\" + getText()+\"]\";\r\n }\r\n } else {\r\n validationError = \"Unsupported type?! \" + paramType.toString();\r\n valid = false;\r\n }\r\n\r\n if (valid) {\r\n String text = getText();\r\n if (text != null && !text.equals(lastText)) {\r\n byte[] value = (byte[]) getValue();\r\n device.setParameterValue(param.getId(), value);\r\n }\r\n lastText = text;\r\n }\r\n return valid;\r\n }\r\n\r\n @Override\r\n public byte[] getValue() {\r\n byte[] value = Helper.hexToBytes(getText());\r\n return value;\r\n }\r\n\r\n private void setValue(byte[] value) {\r\n if (value == null) {\r\n setText(\"\");\r\n return;\r\n }\r\n \r\n String readableValue = Helper.bytesToHex(value);\r\n setText(readableValue);\r\n }\r\n\r\n}\r", "public class StringParameterTextField extends ParameterTextField {\r\n\r\n private final Logger log = LoggerFactory.getLogger(getClass());\r\n\r\n private final ParamType paramType;\r\n\r\n private String validationError = \"\";\r\n private String lastText;\r\n\r\n public StringParameterTextField(DeviceConfigContainer device, Parameter param, ParameterConfiguration conf) {\r\n super(device, param, conf);\r\n\r\n paramType = param.getValue().getType();\r\n\r\n byte[] value = conf.getValue();\r\n if (value == null) {\r\n value = param.getValue().getDefault();\r\n // enforce default value to be set/saved\r\n device.setParameterValue(param.getId(), value);\r\n }\r\n\r\n setValue(value);\r\n }\r\n\r\n @Override\r\n public String getValidationErrorMessage() {\r\n return validationError;\r\n }\r\n\r\n @Override\r\n public boolean isInputValid() {\r\n\r\n boolean valid = false;\r\n\r\n int len = getText().length();\r\n if (len <= 11) {\r\n valid = true;\r\n } else {\r\n validationError = \"String too long. Max 11 chars allowed.\";\r\n }\r\n\r\n if (valid) {\r\n String text = getText();\r\n if (text != null && !text.equals(lastText)) {\r\n byte[] value = (byte[]) getValue();\r\n device.setParameterValue(param.getId(), value);\r\n }\r\n lastText = text;\r\n }\r\n return valid;\r\n }\r\n\r\n @Override\r\n public byte[] getValue() {\r\n String text = getText();\r\n \r\n ReadableValue2Bytes r2b = new ReadableValue2Bytes();\r\n byte[] value = new byte[]{\r\n (int) 0x00, (int) 0x00, (int) 0x00, \r\n (int) 0x00, (int) 0x00, (int) 0x00, \r\n (int) 0x00, (int) 0x00, (int) 0x00, \r\n (int) 0x00, (int) 0x00};\r\n switch (paramType) {\r\n case STRING_11: {\r\n try {\r\n value = r2b.convertString11(text);\r\n } catch (UnsupportedEncodingException ex) {\r\n log.error(\"Error converting String to bytes\", ex);\r\n }\r\n }\r\n break;\r\n default:\r\n log.error(\"Param with id {} is no string11 type\", param.getId());\r\n }\r\n \r\n return value;\r\n }\r\n\r\n private void setValue(byte[] value) {\r\n if (value == null) {\r\n setText(\"\");\r\n return;\r\n }\r\n\r\n Bytes2ReadableValue b2r = new Bytes2ReadableValue();\r\n String readableValue = \"\";\r\n\r\n switch (paramType) {\r\n case STRING_11:\r\n if (!checkParamSize(value, param, 11)) {\r\n break;\r\n }\r\n\r\n try {\r\n readableValue = b2r.convertString11(value);\r\n } catch (UnsupportedEncodingException ex) {\r\n log.error(\"Error converting bytes to String\", ex);\r\n }\r\n break;\r\n }\r\n setText(readableValue);\r\n }\r\n\r\n private boolean checkParamSize(byte[] value, Parameter param, int size) throws HeadlessException {\r\n if (value == null) {\r\n return true;\r\n }\r\n if (value.length != size) {\r\n JOptionPane.showMessageDialog(getParent(), \"Die geladene XML Datei dieses Geräts hat einen Fehler im Abschnitt:\\n\\n\"\r\n + \"<Parameter Id=\\\"\" + param.getId() + \"\\\">:\\n\\n\"\r\n + \"Der Wert Default muss exakt \" + size + \" Byte lang sein, \\n\"\r\n + \"ist aber \" + value.length + \" Bytes lang.!\\n\"\r\n + \"Bitte informiere den Gerätehersteller.\", \"XML Datei ungültig\", JOptionPane.ERROR_MESSAGE);\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n}\r" ]
import javax.swing.JTextField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.konnekting.deviceconfig.DeviceConfigContainer; import de.konnekting.suite.uicomponents.NumberParameterTextField; import de.konnekting.suite.uicomponents.ParameterCombobox; import de.konnekting.suite.uicomponents.ParameterDependency; import de.konnekting.suite.uicomponents.RawParameterTextField; import de.konnekting.suite.uicomponents.StringParameterTextField; import de.konnekting.xml.konnektingdevice.v0.Parameter; import de.konnekting.xml.konnektingdevice.v0.Parameter.Value; import de.konnekting.xml.konnektingdevice.v0.ParameterConfiguration; import de.konnekting.xml.konnektingdevice.v0.ParamType; import java.awt.GridBagConstraints; import javax.swing.JComponent;
/* * Copyright (C) 2016 Alexander Christian <alex(at)root1.de>. All rights reserved. * * This file is part of KONNEKTING Suite. * * KONNEKTING Suite 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. * * KONNEKTING Suite 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 KONNEKTING DeviceConfig. If not, see <http://www.gnu.org/licenses/>. */ package de.konnekting.suite; /** * * @author achristian */ public class ParameterListItem extends javax.swing.JPanel { private final Logger log = LoggerFactory.getLogger(getClass()); private JComponent comp; private int id; /** * Creates new form ParameterListItem */ public ParameterListItem() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; descriptionLabel = new javax.swing.JLabel(); setLayout(new java.awt.GridBagLayout()); descriptionLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); descriptionLabel.setMaximumSize(new java.awt.Dimension(1000, 50)); descriptionLabel.setMinimumSize(new java.awt.Dimension(200, 27)); descriptionLabel.setName(""); // NOI18N descriptionLabel.setPreferredSize(new java.awt.Dimension(230, 50)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(4, 3, 0, 3); add(descriptionLabel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel descriptionLabel; // End of variables declaration//GEN-END:variables void setParam(int id, DeviceConfigContainer device) { this.id = id; Parameter param = device.getParameter(id); String desc = param.getDescription(); Value valueObject = param.getValue(); String options = valueObject.getOptions(); descriptionLabel.setText("<html>" + desc + "</html>"); ParameterConfiguration conf = device.getParameterConfig(id); GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); if (options == null || options.isEmpty()) { JTextField tfield = null; ParamType paramType = param.getValue().getType(); switch (paramType) { case STRING_11: tfield = new StringParameterTextField(device, param, conf); break; case RAW_1: case RAW_2: case RAW_3: case RAW_4: case RAW_5: case RAW_6: case RAW_7: case RAW_8: case RAW_9: case RAW_10: case RAW_11: tfield = new RawParameterTextField(device, param, conf); break; case INT_8: case UINT_8: case INT_16: case UINT_16: case INT_32: case UINT_32: default: tfield = new NumberParameterTextField(device, param, conf); } comp = tfield; } else { ParameterCombobox combobox = new ParameterCombobox(device, param, conf); comp = combobox; } comp.setMaximumSize(new java.awt.Dimension(230, 27)); comp.setMinimumSize(new java.awt.Dimension(230, 27)); comp.setPreferredSize(new java.awt.Dimension(230, 27)); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weighty = 0.1; gridBagConstraints.insets = new java.awt.Insets(2, 0, 1, 3); add(comp, gridBagConstraints); } boolean updateParameterVisibility() {
if (comp instanceof ParameterDependency) {
2
BudgetFreak/BudgetFreak
server/user-management/src/test/java/de/budgetfreak/usermanagement/web/UserControllerTest.java
[ "public abstract class ResourceLinks<E> {\n private Class<E> targetType;\n\n public ResourceLinks(Class<E> targetType) {\n this.targetType = targetType;\n }\n\n public abstract Collection<Link> generateLinks(E entity);\n\n public boolean accepts(Class<?> targetClass) {\n return targetClass == targetType;\n }\n}", "public class JsonHelper {\n\n private static ObjectMapper halMapper;\n\n static {\n halMapper = new ObjectMapper();\n halMapper.registerModule(new Jackson2HalModule());\n }\n\n private JsonHelper() {\n }\n\n /**\n * Parses the given JSON string into a Java object using a standard Jackson mapper.\n *\n * @param json the JSON string to parse.\n * @param toClass class of the target object.\n * @param <T> type of the target object.\n * @return the Java object the JSON string was mapped into.\n * @throws IOException if the JSON string could not be parsed into an object of the given target\n * type.\n */\n public static <T> T fromJson(String json, Class<T> toClass) throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n return mapper.readValue(json, toClass);\n }\n\n /**\n * Maps the given object to JSON using a standard Jackson mapper.\n */\n public static <T> String toJson(T object) throws JsonProcessingException {\n ObjectMapper mapper = new ObjectMapper();\n return mapper.writeValueAsString(object);\n }\n\n /**\n * Maps the given object to JSON, ignoring the \"links\" property that contains the hypermedia\n * links. This method should be used for mapping request payload only, since the hypermedia links\n * are expected in response payloads.\n */\n public static <T> String toJsonWithoutLinks(T object) {\n try {\n ObjectMapper mapper = new ObjectMapper();\n mapper.addMixIn(object.getClass(), IgnoreLinksMixin.class);\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /**\n * Jackson Mixin used to ignore HATEOAS Links.\n */\n @SuppressWarnings(\"squid:S1610\") // Abstract classes without fields should be converted to interfaces\n private abstract class IgnoreLinksMixin {\n @JsonIgnore\n abstract List<Link> getLinks();\n }\n\n /**\n * Parses the given JSON string into a PagedResources object using a Jackson mapper configured for\n * HAL type HATEOAS resources.\n *\n * @param json the JSON string to parse.\n * @param contentType class of the type of the objects contained within the PagedResources\n * wrapper.\n * @param <T> the type of the objects contained within the PagedResources wrapper.\n * @return a PagedResources object if parsing was successful.\n * @throws IOException if the JSON string could not be parsed into an object of the given target\n * type.\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> PagedResources<T> fromPagedResourceJson(String json, Class<T> contentType)\n throws IOException {\n List<T> contentItems = new ArrayList<>();\n PagedResources<Map<String, Object>> pagedResources =\n halMapper.readValue(json, PagedResources.class);\n for (Map<String, Object> contentItem : pagedResources.getContent()) {\n String objectJson = halMapper.writeValueAsString(contentItem);\n T object = halMapper.readValue(objectJson, contentType);\n contentItems.add(object);\n }\n return new PagedResources<>(contentItems, pagedResources.getMetadata());\n }\n}", "public class UserTestUtils {\n\n private UserTestUtils() {\n }\n\n public static List<User> createBobAndJane() {\n return Arrays.asList(\n createBob(),\n createJane()\n );\n }\n\n public static User createJane() {\n return createUser(2L, \"Jane\", \"$\");\n }\n\n public static User createBob() {\n return createUser(1L, \"Bob\", \"€\");\n }\n\n public static User createUser(long id, String name, String currency) {\n return new User().setId(id).setName(name).setCurrency(currency);\n }\n}", "@Entity(name = \"BF_USER\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n\n @Column(name = \"NAME\")\n private String name;\n\n @Column(name = \"CURRENCY\")\n private String currency;\n\n public User() {\n }\n\n public User(String name, String currency) {\n this.name = name;\n this.currency = currency;\n }\n\n public Long getId() {\n return id;\n }\n\n public User setId(Long id) {\n this.id = id;\n return this;\n }\n\n public String getName() {\n return name;\n }\n\n public User setName(String name) {\n this.name = name;\n return this;\n }\n\n public String getCurrency() {\n return currency;\n }\n\n public User setCurrency(String currency) {\n this.currency = currency;\n return this;\n }\n}", "@Service\n@EnableConfigurationProperties(UserManagementProperties.class)\npublic class UserService {\n\n private UserRepository userRepository;\n private UserManagementProperties userManagementProperties;\n\n @Autowired\n public UserService(UserRepository userRepository, UserManagementProperties userManagementProperties) {\n this.userRepository = userRepository;\n this.userManagementProperties = userManagementProperties;\n }\n\n /**\n * List all users in no given order.\n */\n public List<User> list() {\n return userRepository.findAll();\n }\n\n /**\n * Create and saves an user.\n *\n * @return The created entity.\n */\n public User create(String name, String currency) {\n final User user = new User(name, currency);\n return userRepository.save(user);\n }\n\n /**\n * Get one user by id.\n */\n public User get(long id) {\n return userRepository.findOne(Example.of(new User().setId(id))).orElse(null);\n }\n\n /**\n * Reads the testProperty.\n *\n * @return The configured property.\n */\n public String getTestProperty() {\n return userManagementProperties.getTestProperty();\n }\n}" ]
import de.budgetfreak.utils.web.ResourceLinks; import de.budgetfreak.utils.webtests.JsonHelper; import de.budgetfreak.usermanagement.UserTestUtils; import de.budgetfreak.usermanagement.domain.User; import de.budgetfreak.usermanagement.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.hateoas.PagedResources; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
package de.budgetfreak.usermanagement.web; @RunWith(SpringRunner.class) @WebMvcTest(value = UserController.class) @Import(UserResourceAssembler.class) public class UserControllerTest { @MockBean private UserService userServiceMock; @MockBean
private ResourceLinks<User> userResourceLinksMock;
3
dvorka/shifts-solver
test/com/mindforger/shiftsolver/solver/commons/AbstractShiftSolverTest.java
[ "public class RiaState {\n\n\tprivate UserBean currentUser;\n\tprivate UserSettingsBean userSettings;\n\n\tprivate Employee[] employees;\n\tprivate PeriodPreferences[] periodPreferencesArray;\n\tprivate PeriodSolution[] periodSolutions;\n\t\t\n\tprivate Map<String,Employee> employeesByKey;\n\tprivate Map<String,PeriodPreferences> periodPreferencesByKey;\n\tprivate Map<String,PeriodSolution> periodSolutionsByKey;\n\t\n\tpublic RiaState() {\n\t\temployees=new Employee[0];\n\t\tperiodPreferencesArray=new PeriodPreferences[0];\n\t\tperiodSolutions=new PeriodSolution[0];\n\t\temployeesByKey=new HashMap<String,Employee>();\n\t\tperiodPreferencesByKey=new HashMap<String,PeriodPreferences>();\n\t\tperiodSolutionsByKey=new HashMap<String,PeriodSolution>();\n\t}\n\t\n\tpublic void init(RiaBootImageBean bean) {\n\t\tcurrentUser=bean.getUser();\n\t\tuserSettings=bean.getUserSettings();\n\t\t\n\t\tsetEmployees(bean.getEmployees());\n\t\tsetPeriodPreferencesList(bean.getPeriodPreferencesList());\n\t\tsetPeriodSolutions(bean.getPeriodSolutions());\n\t}\n\t\n\tpublic Employee getEmployee(String employeeId) {\n\t\tif(employeeId!=null) {\n\t\t\treturn employeesByKey.get(employeeId);\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic PeriodSolution getPeriodSolution(String solutionId) {\n\t\tif(solutionId!=null) {\n\t\t\treturn periodSolutionsByKey.get(solutionId);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic PeriodPreferences getPeriodPreferences(String periodPreferencesId) {\n\t\tif(periodPreferencesId!=null) {\n\t\t\treturn periodPreferencesByKey.get(periodPreferencesId);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic UserBean getCurrentUser() {\n\t\treturn currentUser;\n\t}\n\n\tpublic void setCurrentUser(UserBean currentUser) {\n\t\tthis.currentUser = currentUser;\n\t}\n\n\tpublic UserSettingsBean getUserSettings() {\n\t\treturn userSettings;\n\t}\n\n\tpublic void setUserSettings(UserSettingsBean userSettings) {\n\t\tthis.userSettings = userSettings;\n\t}\n\n\tpublic Employee[] getEmployees() {\n\t\treturn employees;\n\t}\n\n\tpublic PeriodPreferences[] getPeriodPreferencesArray() {\n\t\treturn periodPreferencesArray;\n\t}\n\t\n\tpublic PeriodSolution[] getPeriodSolutions() {\n\t\treturn periodSolutions;\n\t}\n\n\tpublic void setEmployees(Employee[] employees) {\n\t\tthis.employees= employees;\n\t\temployeesByKey.clear();\n\t\tif(employees!=null) {\n\t\t\tfor(Employee employee: employees) {\n\t\t\t\temployeesByKey.put(employee.getKey(), employee);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void addEmployee(Employee employee) {\n\t\tList<Employee> employeeList;\n\t\tif(employee!=null) {\n\t\t\temployeeList=new ArrayList<Employee>();\n\t\t\tif(employees!=null) {\n\t\t\t\tfor(Employee e:employees) employeeList.add(e);\n\t\t\t}\n\t\t\temployeeList.add(employee);\n\t\t\temployeesByKey.put(employee.getKey(), employee);\n\t\t\temployees=employeeList.toArray(new Employee[employeeList.size()]);\n\t\t}\n\t}\n\t\n\tpublic void setPeriodPreferencesList(PeriodPreferences[] periodPreferencesList) {\n\t\tthis.periodPreferencesArray = periodPreferencesList;\n\t\tperiodPreferencesByKey.clear();\n\t\tif(periodPreferencesList!=null) {\n\t\t\tfor(PeriodPreferences periodPreferences: periodPreferencesList) {\n\t\t\t\tperiodPreferencesByKey.put(periodPreferences.getKey(), periodPreferences);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void addPeriodPreferences(PeriodPreferences preferences) {\n\t\tList<PeriodPreferences> periodPreferencesList;\n\t\tif(preferences!=null) {\n\t\t\tperiodPreferencesList=new ArrayList<PeriodPreferences>();\n\t\t\tif(periodPreferencesArray!=null) {\n\t\t\t\tfor(PeriodPreferences p:periodPreferencesArray) periodPreferencesList.add(p);\n\t\t\t}\n\t\t\tperiodPreferencesList.add(preferences);\n\t\t\tperiodPreferencesByKey.put(preferences.getKey(),preferences);\n\t\t\tperiodPreferencesArray=periodPreferencesList.toArray(new PeriodPreferences[periodPreferencesList.size()]);\n\t\t}\n\t}\n\n\tpublic void setPeriodSolutions(PeriodSolution[] periodSolutions) {\n\t\tthis.periodSolutions = periodSolutions;\n\t\tperiodSolutionsByKey.clear();\n\t\tif(periodSolutions!=null) {\n\t\t\tfor(PeriodSolution periodSolution: periodSolutions) {\n\t\t\t\tperiodSolutionsByKey.put(periodSolution.getKey(), periodSolution);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void addPeriodSolution(PeriodSolution solution) {\n\t\tList<PeriodSolution> periodSolutionsList;\n\t\tif(solution!=null) {\n\t\t\tperiodSolutionsList =new ArrayList<PeriodSolution>();\n\t\t\tif(periodSolutions!=null) {\n\t\t\t\tfor(PeriodSolution p:periodSolutions) periodSolutionsList.add(p);\n\t\t\t}\n\t\t\tperiodSolutionsList.add(solution);\n\t\t\tperiodSolutionsByKey.put(solution.getKey(),solution);\n\t\t\tperiodSolutions=periodSolutionsList.toArray(new PeriodSolution[periodSolutionsList.size()]);\n\t\t}\n\t}\n}", "public class ShiftSolverLogger implements ShiftSolverConstants {\n\n\tprivate static PrintStream out;\n\t\n\tstatic {\n\t\t// nop\n\t\tout=null;\t\t\n\t}\n\t\n\tpublic static void init(PrintStream printStream) {\n\t\tout=printStream;\n\t}\n\t\n\tpublic static void debug(String message) {\n\t\tif(DEBUG) {\n\t\t\tGWT.log(message);\t\t\t\n\t\t}\n\t\tif(out!=null) out.println(message);\n\t}\n\n\tpublic static boolean isJUnitMode() {\n\t\treturn out!=null;\n\t}\n}", "public class DayPreference implements Serializable {\n\tprivate static final long serialVersionUID = 1302160963964962116L;\n\n\tprivate String key;\n\t\n\tprivate int year;\n\tprivate int month;\n\tprivate int day;\n\t\n\t// three state preferences: NO, I CANNOT MAKE IT (bool) / YES PLEASE, I WANT IT (bool) / I DONT CARE (nothing)\n\t\n\tprivate boolean isHoliDay;\n\t\n\tprivate boolean noDay;\n\tprivate boolean noMorning6; // 6 AM or entire day\n\tprivate boolean noMorning7;\n\tprivate boolean noMorning8;\n\tprivate boolean noAfternoon;\n\tprivate boolean noNight;\n\n\tprivate boolean yesDay;\n\tprivate boolean yesMorning6;\n\tprivate boolean yesMorning7;\n\tprivate boolean yesMorning8;\n\tprivate boolean yesAfternoon;\n\tprivate boolean yesNight;\n\t\n\tpublic DayPreference() {\t\t\n\t}\n\n\tpublic String getKey() {\n\t\treturn key;\n\t}\n\n\tpublic void setKey(String key) {\n\t\tthis.key = key;\n\t}\n\n\tpublic int getYear() {\n\t\treturn year;\n\t}\n\n\tpublic void setYear(int year) {\n\t\tthis.year = year;\n\t}\n\n\tpublic int getMonth() {\n\t\treturn month;\n\t}\n\n\tpublic void setMonth(int month) {\n\t\tthis.month = month;\n\t}\n\n\tpublic int getDay() {\n\t\treturn day;\n\t}\n\n\tpublic void setDay(int day) {\n\t\tthis.day = day;\n\t}\n\n\tpublic boolean isNoDay() {\n\t\treturn noDay;\n\t}\n\n\tpublic void setNoDay(boolean noDay) {\n\t\tthis.noDay = noDay;\n\t}\n\n\tpublic boolean isNoMorning6() {\n\t\treturn noMorning6 || noDay;\n\t}\n\n\tpublic void setNoMorning6(boolean noMorning6) {\n\t\tthis.noMorning6 = noMorning6;\n\t}\n\n\tpublic boolean isNoMorning7() {\n\t\treturn noMorning7 || noDay;\n\t}\n\n\tpublic void setNoMorning7(boolean noMorning7) {\n\t\tthis.noMorning7 = noMorning7;\n\t}\n\n\tpublic boolean isNoMorning8() {\n\t\treturn noMorning8 || noDay;\n\t}\n\n\tpublic void setNoMorning8(boolean noMorning8) {\n\t\tthis.noMorning8 = noMorning8;\n\t}\n\n\tpublic boolean isNoAfternoon() {\n\t\treturn noAfternoon || noDay;\n\t}\n\n\tpublic void setNoAfternoon(boolean noAfternoon) {\n\t\tthis.noAfternoon = noAfternoon;\n\t}\n\n\tpublic boolean isYesNight() {\n\t\treturn yesNight;\n\t}\n\n\tpublic void setYesNight(boolean yesNight) {\n\t\tthis.yesNight = yesNight;\n\t}\n\t\n\tpublic boolean isNoNight() {\n\t\treturn noNight || noDay;\n\t}\n\n\tpublic void setNoNight(boolean noNight) {\n\t\tthis.noNight = noNight;\n\t}\n\n\tpublic boolean isYesDay() {\n\t\treturn yesDay;\n\t}\n\n\tpublic void setYesDay(boolean yesDay) {\n\t\tthis.yesDay = yesDay;\n\t}\n\n\tpublic boolean isYesMorning6() {\n\t\treturn yesMorning6;\n\t}\n\n\tpublic void setYesMorning6(boolean yesMorning6) {\n\t\tthis.yesMorning6 = yesMorning6;\n\t}\n\n\tpublic boolean isYesMorning7() {\n\t\treturn yesMorning7;\n\t}\n\n\tpublic void setYesMorning7(boolean yesMorning7) {\n\t\tthis.yesMorning7 = yesMorning7;\n\t}\n\n\tpublic boolean isYesMorning8() {\n\t\treturn yesMorning8;\n\t}\n\n\tpublic void setYesMorning8(boolean yesMorning8) {\n\t\tthis.yesMorning8 = yesMorning8;\n\t}\n\n\tpublic boolean isYesAfternoon() {\n\t\treturn yesAfternoon;\n\t}\n\n\tpublic void setYesAfternoon(boolean yesAfternoon) {\n\t\tthis.yesAfternoon = yesAfternoon;\n\t}\n\n\tpublic boolean isHoliDay() {\n\t\treturn isHoliDay;\n\t}\n\n\tpublic void setHoliDay(boolean isHoliDay) {\n\t\tthis.isHoliDay = isHoliDay;\n\t\tif(isHoliDay) setNoDay(true);\n\t}\t\n}", "public class Employee implements Serializable {\n\tprivate static final long serialVersionUID = 3788399085593900403L;\n\n\tprivate String key;\n\tprivate long modified;\n\tprivate String modifiedPretty;\n\tprivate String firstname;\n\tprivate String familyname;\n\tprivate String email;\n\tprivate int birthdayYear;\n\tprivate int birthdayMonth;\n\tprivate int birthdayDay;\n\tprivate boolean female;\n\tprivate boolean editor;\n\tprivate boolean sportak;\n\tprivate boolean mortak;\n\tprivate boolean fulltime;\n\t\t\n\tpublic Employee() {\t\t\n\t}\n\t\n\tpublic String getKey() {\n\t\treturn key;\n\t}\n\n\tpublic void setKey(String key) {\n\t\tthis.key = key;\n\t}\n\t\n\tpublic long getModified() {\n\t\treturn modified;\n\t}\n\n\tpublic void setModified(long modified) {\n\t\tthis.modified = modified;\n\t}\n\n\tpublic String getModifiedPretty() {\n\t\treturn modifiedPretty;\n\t}\n\n\tpublic void setModifiedPretty(String modifiedPretty) {\n\t\tthis.modifiedPretty = modifiedPretty;\n\t}\n\n\tpublic String getFirstname() {\n\t\treturn firstname;\n\t}\n\n\tpublic void setFirstname(String firstname) {\n\t\tthis.firstname = firstname;\n\t}\n\n\tpublic String getFamilyname() {\n\t\treturn familyname;\n\t}\n\n\tpublic void setFamilyname(String familyname) {\n\t\tthis.familyname = familyname;\n\t}\n\n\tpublic String getFullName() {\n\t\treturn (getFirstname()!=null?getFirstname():\"\")+\" \"+(getFamilyname()!=null?getFamilyname():\"\");\n\t}\n\t\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 boolean isFemale() {\n\t\treturn female;\n\t}\n\t\n\tpublic void setFemale(boolean female) {\n\t\tthis.female = female;\n\t}\n\t\n\tpublic boolean isEditor() {\n\t\treturn editor;\n\t}\n\t\n\tpublic void setEditor(boolean editor) {\n\t\tthis.editor = editor;\n\t}\n\t\n\tpublic boolean isSportak() {\n\t\treturn sportak;\n\t}\n\t\n\tpublic void setSportak(boolean sportak) {\n\t\tthis.sportak = sportak;\n\t}\n\t\n\tpublic boolean isFulltime() {\n\t\treturn fulltime;\n\t}\n\t\n\tpublic void setFulltime(boolean fulltime) {\n\t\tthis.fulltime = fulltime;\n\t}\n\n\tpublic int getBirthdayYear() {\n\t\treturn birthdayYear;\n\t}\n\n\tpublic void setBirthdayYear(int birthdayYear) {\n\t\tthis.birthdayYear = birthdayYear;\n\t}\n\n\tpublic int getBirthdayMonth() {\n\t\treturn birthdayMonth;\n\t}\n\n\tpublic void setBirthdayMonth(int birthdayMonth) {\n\t\tthis.birthdayMonth = birthdayMonth;\n\t}\n\n\tpublic int getBirthdayDay() {\n\t\treturn birthdayDay;\n\t}\n\n\tpublic void setBirthdayDay(int birthdayDay) {\n\t\tthis.birthdayDay = birthdayDay;\n\t}\n\n\tpublic boolean isMortak() {\n\t\treturn mortak;\n\t}\n\n\tpublic void setMortak(boolean mortak) {\n\t\tthis.mortak = mortak;\n\t}\n}", "public class EmployeePreferences implements Serializable {\n\tprivate static final long serialVersionUID = 7779646494294778098L;\n\n\tprivate String key;\n\t\n\tprivate int shiftsLimit;\n\tprivate List<DayPreference> preferences;\n\t\n\tpublic EmployeePreferences() {\n\t\tpreferences=new ArrayList<DayPreference>();\n\t}\n\n\tpublic EmployeePreferences(int shiftsLimit) {\n\t\tthis();\n\t\tthis.shiftsLimit=shiftsLimit;\n\t}\n\t\n\tpublic void addPreference(DayPreference preference) {\n\t\tpreferences.add(preference);\n\t}\n\t\n\tpublic List<DayPreference> getPreferences() {\n\t\treturn preferences;\n\t}\n\n\tpublic void setPreferences(List<DayPreference> preferences) {\n\t\tthis.preferences = preferences;\n\t}\n\n\tpublic int getShiftsLimit() {\n\t\treturn shiftsLimit;\n\t}\n\n\tpublic void setShiftsLimit(int shiftsLimit) {\n\t\tthis.shiftsLimit = shiftsLimit;\n\t}\n\t\n\tpublic String getKey() {\n\t\treturn key;\n\t}\n\n\tpublic void setKey(String key) {\n\t\tthis.key = key;\n\t}\n\n\tpublic DayPreference getPreferencesForDay(int day) {\n\t\tfor(DayPreference dayPreference:preferences) {\n\t\t\tif(day == dayPreference.getDay()) {\n\t\t\t\treturn dayPreference;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}", "public class PeriodPreferences implements Serializable {\n\tprivate static final long serialVersionUID = 8785936718601939671L;\n\n\tprivate String key;\n\tprivate long modified;\n\tprivate String modifiedPretty;\n\tprivate int startWeekDay;\n\tprivate int monthDays;\n\tprivate int monthWorkDays;\n\tprivate int year;\n\tprivate int month;\n\tprivate Map<String,EmployeePreferences> employeeToPreferences;\n\tprivate String lastMonthEditor;\n\t\n\tpublic PeriodPreferences() {\t\t\n\t}\n\t\n\tpublic PeriodPreferences(int year, int month) {\n\t\temployeeToPreferences=new HashMap<String,EmployeePreferences>();\n\t\tthis.year=year;\n\t\tthis.month=month;\n\t}\n\t\n\tpublic String getKey() {\n\t\treturn key;\n\t}\n\t\n\tpublic void setKey(String key) {\n\t\tthis.key = key;\n\t}\n\t\n\tpublic long getModified() {\n\t\treturn modified;\n\t}\n\n\tpublic void setModified(long modified) {\n\t\tthis.modified = modified;\n\t}\n\n\tpublic String getModifiedPretty() {\n\t\treturn modifiedPretty;\n\t}\n\n\tpublic void setModifiedPretty(String modifiedPretty) {\n\t\tthis.modifiedPretty = modifiedPretty;\n\t}\n\n\tpublic int getYear() {\n\t\treturn year;\n\t}\n\n\tpublic void setYear(int year) {\n\t\tthis.year = year;\n\t}\n\n\tpublic int getMonth() {\n\t\treturn month;\n\t}\n\n\tpublic void setMonth(int month) {\n\t\tthis.month = month;\n\t}\n\t\n\tpublic int getStartWeekDay() {\n\t\treturn startWeekDay;\n\t}\n\n\tpublic void setStartWeekDay(int startWeekDay) {\n\t\tthis.startWeekDay = startWeekDay;\n\t}\n\t\n\tpublic int getMonthDays() {\n\t\treturn monthDays;\n\t}\n\n\tpublic void setMonthDays(int monthDays) {\n\t\tthis.monthDays = monthDays;\n\t}\n\n\tpublic void addEmployeePreferences(String employeeKey, EmployeePreferences preferences) {\n\t\temployeeToPreferences.put(employeeKey, preferences);\n\t}\n\t\n\tpublic Map<String, EmployeePreferences> getEmployeeToPreferences() {\n\t\treturn employeeToPreferences;\n\t}\n\n\tpublic void setEmployeeToPreferences(Map<String, EmployeePreferences> employeeToPreferences) {\n\t\tthis.employeeToPreferences = employeeToPreferences;\n\t}\n\n\tpublic int getMonthWorkDays() {\n\t\treturn monthWorkDays;\n\t}\n\n\tpublic void setMonthWorkDays(int monthWorkDays) {\n\t\tthis.monthWorkDays = monthWorkDays;\n\t}\n\n\tpublic String getLastMonthEditor() {\n\t\treturn lastMonthEditor;\n\t}\n\n\tpublic void setLastMonthEditor(String lastMonthEditor) {\n\t\tthis.lastMonthEditor = lastMonthEditor;\n\t}\n}", "public class Team implements Serializable {\n\tprivate static final long serialVersionUID = -1013823027310866432L;\n\n\tprivate Map<String, Employee> employees;\n\tprivate Map<String, Employee> editors;\n\tprivate Map<String, Employee> sportaci;\n\tprivate Map<String, Employee> men;\n\tprivate Map<String, Employee> women;\n\n\tprivate ArrayList<Employee> employeesList;\n\t\n\tpublic Team() {\n\t\temployees=new HashMap<String, Employee>();\n\t\temployeesList=new ArrayList<Employee>();\n\t\teditors=new HashMap<String, Employee>();\n\t\tsportaci=new HashMap<String, Employee>();\t\t\n\t\tmen=new HashMap<String, Employee>();\t\t\n\t\twomen=new HashMap<String, Employee>();\t\t\n\t}\n\t\n\tpublic void addEmployee(Employee employee) {\n\t\temployees.put(employee.getFullName(), employee);\n\t\temployeesList.add(employee);\n\t\tif(employee.isEditor()) {\n\t\t\teditors.put(employee.getKey(),employee);\n\t\t}\n\t\tif(employee.isSportak()) {\n\t\t\tsportaci.put(employee.getKey(),employee);\t\t\t\t\n\t\t}\n\t}\n\n\tpublic void addEmployees(Collection<Employee> employees) {\n\t\tif(employees!=null) {\n\t\t\tfor(Employee e:employees) {\n\t\t\t\taddEmployee(e);\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\t\n\tpublic Map<String, Employee> getEmployees() {\n\t\treturn employees;\n\t}\n\t\n\tpublic List<Employee> getStableEmployeeList() {\n\t\treturn employeesList;\n\t}\n\t\n\tpublic Map<String, Employee> getEditors() {\n\t\treturn editors;\n\t}\n\t\n\tpublic Map<String, Employee> getSportaci() {\n\t\treturn sportaci;\n\t}\n\n\tpublic Map<String, Employee> getMen() {\n\t\treturn men;\n\t}\n\n\tpublic Map<String, Employee> getWomen() {\n\t\treturn women;\n\t}\n}" ]
import java.util.ArrayList; import java.util.List; import com.mindforger.shiftsolver.client.RiaState; import com.mindforger.shiftsolver.shared.ShiftSolverLogger; import com.mindforger.shiftsolver.shared.model.DayPreference; import com.mindforger.shiftsolver.shared.model.Employee; import com.mindforger.shiftsolver.shared.model.EmployeePreferences; import com.mindforger.shiftsolver.shared.model.PeriodPreferences; import com.mindforger.shiftsolver.shared.model.Team;
e.setKey(""+key++); e.setFirstname("Newcomer1"); e.setFamilyname("X"); e.setSportak(true); e.setFulltime(false); team.addEmployee(e); // e=new Employee(); // e.setKey(""+key++); // e.setFirstname("Newcomer2"); // e.setFamilyname("X"); // e.setSportak(true); // e.setFulltime(false); // team.addEmployee(e); /* * fulltime */ e=new Employee(); e.setKey(""+key++); e.setFirstname("Martin"); e.setFamilyname("H"); e.setFulltime(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Milan"); e.setFamilyname("K"); e.setFulltime(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Jan"); e.setFamilyname("P"); e.setFulltime(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Marika"); e.setFamilyname("T"); e.setFulltime(true); e.setFemale(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Michaela"); e.setFamilyname("V"); e.setFulltime(true); e.setFemale(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Kristina"); e.setFamilyname("W"); e.setFulltime(true); e.setFemale(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Vojtech"); e.setFamilyname("K"); e.setFulltime(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Anna"); e.setFamilyname("K"); e.setFulltime(true); e.setFemale(true); team.addEmployee(e); /* * part time */ e=new Employee(); e.setKey(""+key++); e.setFirstname("Matej"); e.setFamilyname("S"); e.setFulltime(false); e.setFemale(false); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Marie"); e.setFamilyname("H"); e.setFulltime(false); e.setFemale(true); team.addEmployee(e); e=new Employee(); e.setKey(""+key++); e.setFirstname("Dominika"); e.setFamilyname("P"); e.setFulltime(false); e.setFemale(true); team.addEmployee(e); // ... state.setEmployees(team.getStableEmployeeList().toArray(new Employee[team.getStableEmployeeList().size()])); int year=2015; int month=11; PeriodPreferences periodPreferences = new PeriodPreferences(year, month); periodPreferences.setKey("2"); periodPreferences.setMonthDays(30); periodPreferences.setMonthWorkDays(21); periodPreferences.setStartWeekDay(1); periodPreferences.setLastMonthEditor(mirko.getKey());
EmployeePreferences employeePreferences;
4
caseydavenport/biermacht
src/com/biermacht/brews/frontend/fragments/ViewStylesFragment.java
[ "public class DisplayStyleActivity extends AppCompatActivity {\n\n private BeerStyle style;\n private int currentItem; // For storing current page\n DisplayStyleCollectionPagerAdapter cpAdapter;\n ViewPager mViewPager;\n ViewPager.OnPageChangeListener pageListener;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_display_recipe);\n\n // Set icon as back button\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\n // Get recipe from intent\n style = getIntent().getParcelableExtra(Constants.KEY_STYLE);\n\n // Set on page change listener\n pageListener = new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int position, float offset, int offsetPixels) {\n }\n\n @Override\n public void onPageSelected(int position) {\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n }\n };\n\n // Set to the current item.\n currentItem = 0;\n\n // Update user interface\n updateUI();\n }\n\n /**\n * TODO: This creates an entire new pager adapter adapter in order to update the UI. It would be\n * nice if we could just update things in place, without having to create / destroy so many\n * objects.\n */\n public void updatePagerAdater() {\n cpAdapter = new DisplayStyleCollectionPagerAdapter(getSupportFragmentManager(), style, getApplicationContext());\n\n // Set Adapter and onPageChangeListener.\n mViewPager = (ViewPager) findViewById(R.id.pager);\n mViewPager.setAdapter(cpAdapter);\n mViewPager.addOnPageChangeListener(pageListener);\n\n // Set the current item\n mViewPager.setCurrentItem(currentItem);\n }\n\n /**\n * Updates the UI after (potentially) changes have been made to the Recipe being viewed.\n */\n private void updateUI() {\n // Update the PagerAdapter.\n updatePagerAdater();\n\n // Set title based on recipe name\n setTitle(style.getName());\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n return true;\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 }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n // Save the current page we're looking at\n this.currentItem = mViewPager.getCurrentItem();\n }\n}", "public class BeerStyleArrayAdapter extends ArrayAdapter<BeerStyle> {\n\n private Context context;\n private List<BeerStyle> list;\n private Recipe r;\n private ViewStorage vs;\n\n // Variables for temporary storage. These are declared at the class-level so that\n // they do not need to be allocated / cleaned up whenever getView is called, but rather\n // when the adapter is first created.\n private View row;\n private LayoutInflater inflater;\n private String detailText;\n private BeerStyle style;\n private String color;\n\n public BeerStyleArrayAdapter(Context c, List<BeerStyle> list) {\n super(c, android.R.layout.simple_list_item_1, list);\n this.context = c;\n this.list = list;\n this.r = r;\n this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n // View to return\n row = convertView;\n\n if (row == null) {\n // Get inflater\n row = inflater.inflate(R.layout.row_layout_beer_style, parent, false);\n\n // Store component views\n vs = new ViewStorage();\n vs.titleView = (TextView) row.findViewById(R.id.title);\n vs.amountView = (TextView) row.findViewById(R.id.amount);\n vs.imageView = (ImageView) row.findViewById(R.id.row_icon);\n vs.unitView = (TextView) row.findViewById(R.id.unit_text);\n vs.detailView = (TextView) row.findViewById(R.id.style_details_text);\n row.setTag(vs);\n }\n\n // Get component views from row\n vs = (ViewStorage) row.getTag();\n\n style = list.get(position);\n\n // Set style name.\n vs.titleView.setText(style.getName());\n vs.detailView.setText(style.getCategory());\n vs.amountView.setText(style.getCatNum() + style.getStyleLetter());\n vs.unitView.setText(style.getStyleGuide());\n\n // Set color\n color = ColorHandler.getSrmColor(style.getAverageColor());\n vs.imageView.setColorFilter(Color.parseColor(color));\n\n return row;\n }\n\n private class ViewStorage {\n public TextView titleView;\n public TextView amountView;\n public ImageView imageView;\n public TextView unitView;\n public TextView detailView;\n }\n}", "public class BeerStyle implements Parcelable {\n\n // Categories based on beerXMl standard\n private String name;\n private String category;\n private Integer version;\n private String categoryNumber;\n private String styleLetter;\n private String styleGuide;\n private String type;\n private String notes;\n private String profile;\n private String ingredients;\n private String examples;\n\n // Reccomended values\n private double MinOg;\n private double MaxOg;\n private double MinFg;\n private double MaxFg;\n private double MinIbu;\n private double MaxIbu;\n private double minColor;\n private double maxColor;\n private double minAbv;\n private double maxAbv;\n\n // More\n private long ownerId;\n\n // Defines\n public static String TYPE_ALE = \"Ale\";\n public static String TYPE_LAGER = \"Lager\";\n public static String TYPE_MEAD = \"Mead\";\n public static String TYPE_WHEAT = \"Wheat\";\n public static String TYPE_MIXED = \"Mixed\";\n public static String TYPE_CIDER = \"Cider\";\n\n public BeerStyle(String name) {\n setName(name);\n setType(\"\");\n setCategory(\"\");\n setStyleLetter(\"\");\n setNotes(\"\");\n setExamples(\"\");\n setIngredients(\"\");\n setProfile(\"\");\n setStyleGuide(\"\");\n setCategoryNumber(\"\");\n setVersion(1);\n setOwnerId(- 1);\n\n this.MinOg = 1;\n this.MaxOg = 2;\n this.MinFg = 1;\n this.MaxFg = 2;\n this.MinIbu = 0;\n this.MaxIbu = 200;\n this.minColor = 0;\n this.maxColor = 100;\n this.minAbv = 0;\n this.maxAbv = 100;\n }\n\n public BeerStyle(Parcel p) {\n // Categories based on beerXMl standard\n name = p.readString();\n category = p.readString();\n version = p.readInt();\n categoryNumber = p.readString();\n styleLetter = p.readString();\n styleGuide = p.readString();\n type = p.readString();\n notes = p.readString();\n profile = p.readString();\n ingredients = p.readString();\n examples = p.readString();\n MinOg = p.readDouble();\n MaxOg = p.readDouble();\n MinFg = p.readDouble();\n MaxFg = p.readDouble();\n MinIbu = p.readDouble();\n MaxIbu = p.readDouble();\n minColor = p.readDouble();\n maxColor = p.readDouble();\n minAbv = p.readDouble();\n maxAbv = p.readDouble();\n ownerId = p.readLong();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Categories based on beerXMl standard\n p.writeString(name);\n p.writeString(category);\n p.writeInt(version);\n p.writeString(categoryNumber);\n p.writeString(styleLetter);\n p.writeString(styleGuide);\n p.writeString(type);\n p.writeString(notes);\n p.writeString(profile);\n p.writeString(ingredients);\n p.writeString(examples);\n p.writeDouble(MinOg);\n p.writeDouble(MaxOg);\n p.writeDouble(MinFg);\n p.writeDouble(MaxFg);\n p.writeDouble(MinIbu);\n p.writeDouble(MaxIbu);\n p.writeDouble(minColor);\n p.writeDouble(maxColor);\n p.writeDouble(minAbv);\n p.writeDouble(maxAbv);\n p.writeLong(ownerId);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<BeerStyle> CREATOR =\n new Parcelable.Creator<BeerStyle>() {\n @Override\n public BeerStyle createFromParcel(Parcel p) {\n return new BeerStyle(p);\n }\n\n @Override\n public BeerStyle[] newArray(int size) {\n return new BeerStyle[]{};\n }\n };\n\n @Override\n public boolean equals(Object o) {\n // Fist make sure its a BeerStyle\n if (! (o instanceof BeerStyle)) {\n return false;\n }\n\n // Based only off the name\n if (this.toString().equals(o.toString())) {\n return true;\n }\n else {\n return false;\n }\n\n }\n\n public String toString() {\n return name;\n }\n\n public void setOwnerId(long i) {\n this.ownerId = i;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setMinCarb(double d) {\n // TODO\n }\n\n public void setMaxCarb(double d) {\n // TODO\n }\n\n public void setName(String s) {\n this.name = s;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setType(String s) {\n this.type = s;\n }\n\n public void setCategory(String s) {\n this.category = s;\n }\n\n public void setStyleLetter(String s) {\n this.styleLetter = s;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public void setExamples(String s) {\n this.examples = s;\n }\n\n public void setProfile(String s) {\n this.profile = s;\n }\n\n public void setCategoryNumber(String s) {\n this.categoryNumber = s;\n }\n\n public void setStyleGuide(String s) {\n this.styleGuide = s;\n }\n\n public void setIngredients(String s) {\n this.ingredients = s;\n }\n\n public void setVersion(int i) {\n this.version = i;\n }\n\n // Methods for getting individual mins and maxes\n public double getMinOg() {\n return MinOg;\n }\n\n public void setMinOg(double minGrav) {\n this.MinOg = minGrav;\n }\n\n public double getMaxOg() {\n return MaxOg;\n }\n\n public void setMaxOg(double maxGrav) {\n this.MaxOg = maxGrav;\n }\n\n public double getMinIbu() {\n return MinIbu;\n }\n\n public void setMinIbu(double MinIbu) {\n this.MinIbu = MinIbu;\n }\n\n public double getMaxIbu() {\n return MaxIbu;\n }\n\n public void setMaxIbu(double MaxIbu) {\n this.MaxIbu = MaxIbu;\n }\n\n public double getMinColor() {\n return minColor;\n }\n\n public void setMinColor(double minColor) {\n this.minColor = minColor;\n }\n\n public double getMaxColor() {\n return maxColor;\n }\n\n public void setMaxColor(double maxColor) {\n this.maxColor = maxColor;\n }\n\n public double getAverageColor() {\n return (this.minColor + this.maxColor) / 2;\n }\n\n public double getMinAbv() {\n return minAbv;\n }\n\n public void setMinAbv(double minAbv) {\n this.minAbv = minAbv;\n }\n\n public double getMaxAbv() {\n return maxAbv;\n }\n\n public void setMaxAbv(double maxAbv) {\n this.maxAbv = maxAbv;\n }\n\n public double getMaxFg() {\n return MaxFg;\n }\n\n public void setMaxFg(double MaxFg) {\n this.MaxFg = MaxFg;\n }\n\n public double getMinFg() {\n return MinFg;\n }\n\n public void setMinFg(double MinFg) {\n this.MinFg = MinFg;\n }\n\n public String getCategory() {\n return this.category;\n }\n\n public String getCatNum() {\n return this.categoryNumber;\n }\n\n public String getStyleLetter() {\n return this.styleLetter;\n }\n\n public String getStyleGuide() {\n return this.styleGuide;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getMinCarb() {\n return 0; // TODO\n }\n\n public double getMaxCarb() {\n return 0; // TODO\n }\n\n public String getNotes() {\n // Return the string without any newlines or tabs.\n return this.notes.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getProfile() {\n return this.profile.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getIngredients() {\n return this.ingredients.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getExamples() {\n return this.examples.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n}", "public class Constants {\n\n // New Objects\n public static final BeerStyle BEERSTYLE_OTHER = new BeerStyle(\"Other\");\n\n // Master recipe's ID. This is the ID of the dummy recipe we create on first use.\n // This recipe is used as a placeholder when a user-created recipe is not available.\n // For example, when a custom ingredient is added to the database, but is not in a recipe.\n public static final long MASTER_RECIPE_ID = 1;\n\n // Keys for passing objects\n public static final String KEY_RECIPE_ID = \"biermacht.brews.recipe.id\";\n public static final String KEY_RECIPE = \"biermacht.brews.recipe\";\n public static final String KEY_PROFILE_ID = \"biermacht.brews.mash.profile.id\";\n public static final String KEY_PROFILE = \"biermacht.brews.mash.profile\";\n public static final String KEY_INGREDIENT_ID = \"biermacht.brews.ingredient.id\";\n public static final String KEY_INGREDIENT = \"biermacht.brews.ingredient\";\n public static final String KEY_MASH_STEP = \"biermacht.brews.mash.step\";\n public static final String KEY_MASH_STEP_ID = \"biermacht.brews.mash.step.id\";\n public static final String KEY_MASH_STEP_LIST = \"biermacht.brews.mash.profile.steps\";\n public static final String KEY_MASH_PROFILE = \"biermacht.brews.mash.profile\";\n public static final String KEY_INSTRUCTION = \"biermacht.brews.instruction\";\n public static final String KEY_DATABASE_ID = \"biermacht.brews.database.id\";\n public static final String KEY_SECONDS = \"biermacht.brews.remaining.seconds\";\n public static final String KEY_TITLE = \"biermacht.brews.title\";\n public static final String KEY_COMMAND = \"biermacht.brews.command\";\n public static final String KEY_STEP_NUMBER = \"biermacht.brews.stepnumber\";\n public static final String KEY_TIMER_STATE = \"biermacht.brews.timer.state\";\n public static final String KEY_STYLE = \"biermacht.brews.style\";\n\n public static final int INVALID_ID = - 1;\n\n public static final String BREW_DATE_FMT = \"dd MMM yyyy\";\n public static final String LAST_MODIFIED_DATE_FMT = \"dd MMM yyyy HH:mm:ss\";\n\n // Indicates if a recipe should be displayed after it is created.\n public static final String DISPLAY_ON_CREATE = \"biermacht.brews.recipe.display.on.create\";\n\n // Valid commands\n public static final String COMMAND_START = \"biermacht.brews.commands.start\";\n public static final String COMMAND_STOP = \"biermacht.brews.commands.stop\";\n public static final String COMMAND_PAUSE = \"biermacht.brews.commands.pause\";\n public static final String COMMAND_QUERY = \"biermacht.brews.commands.query\";\n public static final String COMMAND_STOP_ALARM = \"biermacht.brews.commands.stop.alarm\";\n\n // Database identifiers used to slice SQLite database into\n // multiple zones, each with a different purpose.\n\n // System DB - imported from assets. Contains the selection of \"default\" ingredients /\n // profiles / styles / etc that come with the application.\n public static final long DATABASE_SYSTEM_RESOURCES = 2;\n\n // User DB - custom resources added by the user. Constains the selection of ingredients / profiles\n // styles / etc that a user has specifically added to the application.\n public static final long DATABASE_USER_RESOURCES = 1;\n\n // User DB - stores recipes and specific instances of the \"rubber-stamp\"\n // ingredients / profiles / styles / etc from one of SYSTEM_ADDED or USER_ADDED\n // that are related to those recipes.\n public static final long DATABASE_USER_RECIPES = 0;\n\n // No owner ID for use in database\n public static final long OWNER_NONE = - 1;\n\n // Broadcast types\n public static final String BROADCAST_TIMER = \"com.biermacht.brews.broadcast.timer\";\n public static final String BROADCAST_REMAINING_TIME = \"com.biermacht.brews.broadcast.timer.remaining\";\n public static final String BROADCAST_TIMER_CONTROLS = \"com.biermacht.brews.broadcast.timer.controls\";\n public static final String BROADCAST_QUERY_RESP = \"com.biermacht.brews.broadcast.query.resp\";\n\n // Shared preferences Constants\n public static final String PREFERENCES = \"com.biermacht.brews.preferences\";\n public static final String PREF_USED_BEFORE = \"com.biermacht.brews.usedBefore\";\n public static final String PREF_LAST_OPENED = \"com.biermacht.brews.lastOpened\";\n public static final String PREF_BREWER_NAME = \"com.biermacht.brews.brewerName\";\n public static final String PREF_MEAS_SYSTEM = \"com.biermacht.brews.measurementSystem\";\n public static final String PREF_FIXED_RATIOS = \"com.biermacht.brews.waterToGrainRatiosFixed\";\n public static final String PREF_HYDROMETER_CALIBRATION_TEMP = \"com.biermacht.brews.hydrometerCalibrationTemp\";\n public static final String PREF_SORT_STRATEGY = \"com.biermacht.brews.recipe_sort_strategy\";\n\n // Value of this preference indicates the last time db contents were updated.\n public static final String PREF_NEW_CONTENTS_VERSION = \"com.biermacht.brews.newIngredientsVersion\";\n\n // Incremented when new database contents are added.\n public static int NEW_DB_CONTENTS_VERSION = 5;\n\n // Valid recipe sort strategies.\n public static final String SORT_STRATEGY_ALPHABETICAL = \"Name (A to Z)\";\n public static final String SORT_STRATEGY_REV_ALPHABETICAL = \"Name (Z to A)\";\n public static final String SORT_STRATEGY_BREW_DATE = \"Created (Newest first)\";\n public static final String SORT_STRATEGY_REV_BREW_DATE = \"Created (Oldest first)\";\n public static final String SORT_STRATEGY_MODIFIED = \"Modified (Latest first)\";\n\n // Activity for result return codes\n public static final int RESULT_DELETED = 1;\n public static final int RESULT_OK = 2;\n public static final int RESULT_CANCELED = 3;\n\n // Request codes for activities\n public static final int REQUEST_NEW_MASH_STEP = 1;\n public static final int REQUEST_EDIT_MASH_STEP = 2;\n public static final int REQUEST_EDIT_RECIPE = 3;\n public static final int REQUEST_IMPORT_FILE = 4;\n public static final int REQUEST_CONNECT_TO_DRIVE = 5;\n public static final int REQUEST_DRIVE_FILE_OPEN = 6;\n public static final int REQUEST_DRIVE_FILE_CREATE = 7;\n\n // Possible timer states\n public static int PAUSED = 0;\n public static int RUNNING = 1;\n public static int STOPPED = 2;\n\n // Constant messages\n public static String MESSAGE_AUTO_CALC_W2GR = \"Water-to-grain ratio is calculated automatically for this step.\";\n\n // Other Constants\n private static final String[] hop_uses = {Hop.USE_BOIL, Hop.USE_AROMA, Hop.USE_DRY_HOP, Hop.USE_FIRST_WORT};\n private static final String[] hop_forms = {Hop.FORM_PELLET, Hop.FORM_WHOLE, Hop.FORM_PLUG};\n private static final String[] ferm_types = {Fermentable.TYPE_GRAIN, Fermentable.TYPE_EXTRACT, Fermentable.TYPE_SUGAR, Fermentable.TYPE_ADJUNCT};\n private static final String[] step_types = {MashStep.INFUSION, MashStep.DECOCTION, MashStep.TEMPERATURE};\n private static final String[] unit_systems = {Units.IMPERIAL, Units.METRIC};\n private static final String[] mash_types = {MashProfile.MASH_TYPE_DECOCTION, MashProfile.MASH_TYPE_INFUSION, MashProfile.MASH_TYPE_TEMPERATURE, MashProfile.MASH_TYPE_BIAB};\n private static final String[] sparge_types = {MashProfile.SPARGE_TYPE_BATCH, MashProfile.SPARGE_TYPE_FLY, MashProfile.SPARGE_TYPE_BIAB};\n private static final String[] sort_strats = {SORT_STRATEGY_ALPHABETICAL, SORT_STRATEGY_REV_ALPHABETICAL, SORT_STRATEGY_BREW_DATE, SORT_STRATEGY_REV_BREW_DATE, SORT_STRATEGY_MODIFIED};\n\n public static final ArrayList<String> HOP_USES = new ArrayList<String>(Arrays.asList(hop_uses));\n public static final ArrayList<String> HOP_FORMS = new ArrayList<String>(Arrays.asList(hop_forms));\n public static final ArrayList<String> FERMENTABLE_TYPES = new ArrayList<String>(Arrays.asList(ferm_types));\n public static final ArrayList<String> MASH_STEP_TYPES = new ArrayList<String>(Arrays.asList(step_types));\n public static final ArrayList<String> UNIT_SYSTEMS = new ArrayList<String>(Arrays.asList(unit_systems));\n public static final ArrayList<String> MASH_TYPES = new ArrayList<String>(Arrays.asList(mash_types));\n public static final ArrayList<String> SPARGE_TYPES = new ArrayList<String>(Arrays.asList(sparge_types));\n public static final ArrayList<String> RECIPE_SORT_STRATEGIES = new ArrayList(Arrays.asList(sort_strats));\n\n}", "public class IngredientHandler {\n\n private Context mContext;\n private DatabaseAPI databaseApi;\n private ArrayList<Ingredient> fermentablesList;\n private ArrayList<Ingredient> yeastsList;\n private ArrayList<Ingredient> hopsList;\n private ArrayList<Ingredient> miscsList;\n private ArrayList<BeerStyle> styleList;\n private ArrayList<MashProfile> profileList;\n\n public IngredientHandler(Context c) {\n this.mContext = c;\n this.databaseApi = new DatabaseAPI(c);\n }\n\n // First time use - put ingredients and mash profiles into SQLite\n public void ImportAssets() {\n try {\n // Import all ingredient assets.\n this.importIngredients();\n\n // Import mash profile assets.\n this.databaseApi.addMashProfileList(Constants.DATABASE_USER_RESOURCES,\n getProfilesFromXml(),\n Constants.OWNER_NONE);\n\n // Import style assets.\n this.databaseApi.addStyleList(Constants.DATABASE_SYSTEM_RESOURCES,\n getStylesFromXml(),\n Constants.OWNER_NONE);\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // Imports ingredient assets only (not mash profiles).\n public void importIngredients() throws IOException {\n databaseApi.addIngredientList(Constants.DATABASE_SYSTEM_RESOURCES,\n getFermentablesFromXml(),\n Constants.OWNER_NONE);\n databaseApi.addIngredientList(Constants.DATABASE_SYSTEM_RESOURCES,\n getYeastsFromXml(),\n Constants.OWNER_NONE);\n databaseApi.addIngredientList(Constants.DATABASE_SYSTEM_RESOURCES,\n getHopsFromXml(),\n Constants.OWNER_NONE);\n databaseApi.addIngredientList(Constants.DATABASE_SYSTEM_RESOURCES,\n getMiscsFromXml(),\n Constants.OWNER_NONE);\n }\n\n public void importIngredients(String filePath) throws IOException {\n databaseApi.addIngredientList(Constants.DATABASE_SYSTEM_RESOURCES,\n getIngredientsFromXml(filePath),\n Constants.OWNER_NONE);\n }\n\n /**\n * Returns a list of valid fermentables for use in recipes\n *\n * @return ArrayList of ingredient objects\n */\n public ArrayList<Ingredient> getFermentablesList() {\n if (this.fermentablesList == null) {\n Log.d(\"getFermentablesList\", \"List is null, creating\");\n fermentablesList = new ArrayList<Ingredient>();\n }\n\n fermentablesList.removeAll(fermentablesList);\n fermentablesList.addAll(databaseApi.getIngredients(Constants.DATABASE_USER_RESOURCES,\n Ingredient.FERMENTABLE));\n fermentablesList.addAll(databaseApi.getIngredients(Constants.DATABASE_SYSTEM_RESOURCES, Ingredient.FERMENTABLE));\n\n Collections.sort(fermentablesList, new ToStringComparator());\n Log.d(\"getFermentablesList\", \"Returning \" + fermentablesList.size() + \" fermentables\");\n return this.fermentablesList;\n }\n\n /**\n * Returns a list of valid yeasts for use in recipes\n *\n * @return ArrayList of ingredient objects\n */\n public ArrayList<Ingredient> getYeastsList() {\n if (this.yeastsList == null) {\n Log.d(\"getYeastsList\", \"List is null, creating\");\n yeastsList = new ArrayList<Ingredient>();\n }\n\n yeastsList.removeAll(yeastsList);\n yeastsList.addAll(databaseApi.getIngredients(Constants.DATABASE_USER_RESOURCES,\n Ingredient.YEAST));\n yeastsList.addAll(databaseApi.getIngredients(Constants.DATABASE_SYSTEM_RESOURCES,\n Ingredient.YEAST));\n\n Collections.sort(yeastsList, new ToStringComparator());\n return this.yeastsList;\n }\n\n /**\n * Returns a list of valid hops for use in recipes\n *\n * @return ArrayList of ingredient objects\n */\n public ArrayList<Ingredient> getHopsList() {\n if (this.hopsList == null) {\n Log.d(\"getHopsList\", \"List is null, creating\");\n hopsList = new ArrayList<Ingredient>();\n }\n\n hopsList.removeAll(hopsList);\n hopsList.addAll(databaseApi.getIngredients(Constants.DATABASE_USER_RESOURCES,\n Ingredient.HOP));\n hopsList.addAll(databaseApi.getIngredients(Constants.DATABASE_SYSTEM_RESOURCES,\n Ingredient.HOP));\n\n Collections.sort(hopsList, new ToStringComparator());\n return this.hopsList;\n }\n\n /**\n * Returns a list of valid miscs for use in recipes\n *\n * @return ArrayList of ingredient objects\n */\n public ArrayList<Ingredient> getMiscsList() {\n if (this.miscsList == null) {\n Log.d(\"getMiscsList\", \"List is null, creating\");\n miscsList = new ArrayList<Ingredient>();\n }\n\n miscsList.removeAll(miscsList);\n miscsList.addAll(databaseApi.getIngredients(Constants.DATABASE_USER_RESOURCES,\n Ingredient.MISC));\n miscsList.addAll(databaseApi.getIngredients(Constants.DATABASE_SYSTEM_RESOURCES,\n Ingredient.MISC));\n\n Collections.sort(miscsList, new ToStringComparator());\n return this.miscsList;\n }\n\n /**\n * Returns a list of valid styles for use in recipes\n *\n * @return ArrayList of style objects\n */\n public ArrayList<BeerStyle> getStylesList() {\n if (this.styleList == null) {\n this.styleList = this.databaseApi.getStyles(Constants.DATABASE_SYSTEM_RESOURCES);\n this.styleList.addAll(this.databaseApi.getStyles(Constants.DATABASE_USER_RESOURCES));\n }\n\n return styleList;\n }\n\n /**\n * @return ArrayList of MashProfiles\n */\n public ArrayList<MashProfile> getMashProfileList() {\n if (this.profileList == null) {\n Log.d(\"getMashProfileList\", \"List is null, creating\");\n profileList = new ArrayList<MashProfile>();\n }\n\n profileList.removeAll(profileList);\n profileList.addAll(databaseApi.getMashProfiles(Constants.DATABASE_USER_RESOURCES));\n profileList.addAll(databaseApi.getMashProfiles(Constants.DATABASE_SYSTEM_RESOURCES));\n\n Collections.sort(profileList, new ToStringComparator());\n return this.profileList;\n }\n\n /**\n * Gets fermentables from XMl files in assets/Fermentables Some fermentables from..\n * http://byo.com/resources/grains\n *\n * @return ArrayList of Ingredient Objects\n * @throws IOException\n */\n private ArrayList<Ingredient> getFermentablesFromXml() throws IOException {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n\n for (String s : mContext.getAssets().list(\"Fermentables\")) {\n list.addAll(getIngredientsFromXml(\"Fermentables/\" + s));\n }\n\n return list;\n }\n\n /**\n * Gets yeasts from XMl files in assets/Yeasts\n *\n * @return ArrayList of Ingredient Objects\n * @throws IOException\n */\n private ArrayList<Ingredient> getYeastsFromXml() throws IOException {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n\n for (String s : mContext.getAssets().list(\"Yeasts\")) {\n list.addAll(getIngredientsFromXml(\"Yeasts/\" + s));\n }\n\n return list;\n }\n\n /**\n * Gets hops from XMl files in assets/Hops\n *\n * @return ArrayList of Ingredient Objects\n * @throws IOException\n */\n private ArrayList<Ingredient> getHopsFromXml() throws IOException {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n\n for (String s : mContext.getAssets().list(\"Hops\")) {\n list.addAll(getIngredientsFromXml(\"Hops/\" + s));\n }\n\n Log.d(\"IngredientHandler\", \"Got \" + list.size() + \" hops from XML\");\n return list;\n }\n\n /**\n * Gets Styles from XMl files in assets/Styles\n *\n * @return ArrayList of BeerStyle Objects\n * @throws IOException\n */\n public ArrayList<BeerStyle> getStylesFromXml() throws IOException {\n ArrayList<BeerStyle> list = new ArrayList<BeerStyle>();\n\n for (String s : mContext.getAssets().list(\"Styles\")) {\n list.addAll(getStylesFromXml(\"Styles/\" + s));\n }\n\n Collections.sort(list, new BeerStyleComparator<BeerStyle>());\n return list;\n }\n\n public ArrayList<BeerStyle> getStylesFromXml(String filePath) throws IOException {\n ArrayList<BeerStyle> list = new ArrayList<BeerStyle>();\n BeerXmlReader myXMLHandler = new BeerXmlReader();\n SAXParserFactory spf = SAXParserFactory.newInstance();\n\n try {\n SAXParser sp = spf.newSAXParser();\n InputStream is = mContext.getAssets().open(filePath);\n sp.parse(is, myXMLHandler);\n\n list.addAll(myXMLHandler.getBeerStyles());\n } catch (Exception e) {\n Log.e(\"getStylesFromXml\", e.toString());\n }\n\n return list;\n }\n\n /**\n * Gets Miscs from XMl files in assets/Miscs\n *\n * @return ArrayList of Ingredient Objects\n * @throws IOException\n */\n private ArrayList<Ingredient> getMiscsFromXml() throws IOException {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n\n for (String s : mContext.getAssets().list(\"Miscs\")) {\n list.addAll(getIngredientsFromXml(\"Miscs/\" + s));\n }\n\n Collections.sort(list, new RecipeIngredientsComparator());\n return list;\n }\n\n private ArrayList<Ingredient> getIngredientsFromXml(String filePath) throws IOException {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n BeerXmlReader myXMLHandler = new BeerXmlReader();\n SAXParserFactory spf = SAXParserFactory.newInstance();\n\n Log.d(\"IngredientHandler\", \"Importing ingredients from: \" + filePath);\n\n try {\n SAXParser sp = spf.newSAXParser();\n InputStream is = mContext.getAssets().open(filePath);\n sp.parse(is, myXMLHandler);\n\n list.addAll(myXMLHandler.getAllIngredients());\n } catch (Exception e) {\n Log.e(\"IngredientHandler\", e.toString());\n }\n\n Collections.sort(list, new RecipeIngredientsComparator());\n Log.d(\"IngredientHandler\", filePath + \" had \" + list.size() + \" ingredients\");\n return list;\n }\n\n /**\n * Gets Recipes from XMl file passed in path s.\n * <p/>\n * If the file extension if .bsmx, will use the .bsmx parser. Otherwise, the BeerXML parser is\n * used.\n *\n * @return ArrayList of Ingredient Objects\n * @throws IOException\n */\n public ArrayList<Recipe> getRecipesFromXml(InputStream is, String path) throws Exception {\n ArrayList<Recipe> retlist = new ArrayList<Recipe>();\n ArrayList<Recipe> list;\n BeerXmlReader beerXmlReader = new BeerXmlReader();\n BsmxXmlReader bsmxXmlReader = new BsmxXmlReader();\n SAXParserFactory spf = SAXParserFactory.newInstance();\n SAXParser sp = spf.newSAXParser();\n\n // Read the input source to a String for use below.\n String asString = Utils.convertStreamToString(is);\n\n Log.d(\"IngredientHandler\", \"Parsing file: \" + path);\n try {\n // First, try to parse this as a BeerXML file. If it fails then try BeerSmith format.\n Log.d(\"IngredientHandler\", \"Attempting to parse BeerXML file\");\n InputSource inSrc = new InputSource(new StringReader(asString));\n inSrc.setEncoding(\"ISO-8859-2\");\n sp.parse(inSrc, beerXmlReader);\n list = beerXmlReader.getRecipes();\n } catch (Exception e) {\n try {\n Log.d(\"IngredientHandler\", \"Failed to parse as .xml, attempting to parse as a .bsmx file\");\n // Failed to parse as a .xml file. Attempt to parse as .bsmx format instead.\n // If this fails, then we'll raise both errors to the user.\n\n // .bsmx files generated by BeerSmith include HTML encoded characters without declaring\n // the encoding - pull in the whole file as a string and escape any HTML entities before\n // passing to the XML parser.\n String escaped = StringEscapeUtils.unescapeHtml4(asString);\n\n // Re-escape things properly as XML.\n escaped = StringEscapeUtils.escapeXml11(escaped);\n escaped = escaped.replaceAll(\"&lt;\", \"<\");\n escaped = escaped.replaceAll(\"&gt;\", \">\");\n\n // Now, parse the String.\n sp.parse(new InputSource(new StringReader(escaped)), bsmxXmlReader);\n list = bsmxXmlReader.getRecipes();\n\n } catch (Exception e2) {\n // Failed to parse the file as beerXML, as well as Beersmith format.\n // Raise an error to the user that the file is not valid.\n Log.e(\"IngredientHandler\", \"Failed to parse as either .bsmx, or .xml format\");\n String eTrace = Log.getStackTraceString(e);\n String e2Trace = Log.getStackTraceString(e2);\n String estr = \"The following errors were raised:\\n\\n\" +\n \".xml parse errror: \\n%s\\n\\n--------\\n\\n\" +\n \".bsmx parse error: \\n%s\\n\\n--------\\n\";\n estr = String.format(estr, eTrace, e2Trace);\n throw new Exception(estr);\n }\n }\n\n retlist.addAll(list);\n\n return retlist;\n }\n\n /**\n * Gets MashProfiles from XMl files in assets/Profiles\n *\n * @return ArrayList of MashProfile Objects\n * @throws IOException\n */\n public ArrayList<MashProfile> getProfilesFromXml() throws IOException {\n ArrayList<MashProfile> list = new ArrayList<MashProfile>();\n AssetManager am = mContext.getAssets();\n\n for (String s : am.list(\"Profiles\")) {\n list.addAll(getProfilesFromXml(\"Profiles/\" + s));\n }\n return list;\n }\n\n public ArrayList<MashProfile> getProfilesFromXml(String path) throws IOException {\n ArrayList<MashProfile> list = new ArrayList<MashProfile>();\n BeerXmlReader myXMLHandler = new BeerXmlReader();\n SAXParserFactory spf = SAXParserFactory.newInstance();\n AssetManager am = mContext.getAssets();\n\n try {\n // Parse files.\n SAXParser sp = spf.newSAXParser();\n InputStream is = am.open(path);\n sp.parse(is, myXMLHandler);\n\n // Default mash profiles should auto-calculate infustion temp / amount,\n // so set that here.\n list = myXMLHandler.getMashProfiles();\n for (MashProfile p : list) {\n for (MashStep step : p.getMashStepList()) {\n if (step.getType().equals(MashStep.INFUSION)) {\n Log.d(\"IngredientHandler\", \"Enabling auto-calculation for: \" + p.getName());\n step.setAutoCalcInfuseAmt(true);\n step.setAutoCalcInfuseTemp(true);\n }\n }\n }\n\n } catch (Exception e) {\n Log.e(\"getProfilesFromXml\", e.toString());\n }\n return list;\n }\n\n}", "public class ToStringComparator implements Comparator<Object> {\n\n public int compare(Object o, Object p) {\n return o.toString().compareTo(p.toString());\n }\n}", "public interface BiermachtFragment {\n // Method to call when a click event occurs\n public void handleClick(View v);\n\n // Method to call when this fragmet should update.\n public void update();\n\n // Method to call when an options item is selected.\n public boolean onOptionsItemSelected(MenuItem i);\n\n // Returns the name of this fragment (user visible).\n public String name();\n}" ]
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.biermacht.brews.R; import com.biermacht.brews.frontend.DisplayStyleActivity; import com.biermacht.brews.frontend.adapters.BeerStyleArrayAdapter; import com.biermacht.brews.recipe.BeerStyle; import com.biermacht.brews.utils.Constants; import com.biermacht.brews.utils.IngredientHandler; import com.biermacht.brews.utils.comparators.ToStringComparator; import com.biermacht.brews.utils.interfaces.BiermachtFragment; import java.util.ArrayList; import java.util.Collections;
package com.biermacht.brews.frontend.fragments; public class ViewStylesFragment extends Fragment implements BiermachtFragment { private static int resource = R.layout.fragment_view; ; private OnItemClickListener mClickListener; private ListView listView; private ArrayList<BeerStyle> list; private BeerStyleArrayAdapter arrayAdapter; View pageView; Context c; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { pageView = inflater.inflate(resource, container, false); setHasOptionsMenu(true); // Context c = getActivity(); // Get ingredient list list = new IngredientHandler(c).getStylesList(); Collections.sort(list, new ToStringComparator()); // Set up the list adapter arrayAdapter = new BeerStyleArrayAdapter(c, list); // Initialize important junk listView = (ListView) pageView.findViewById(R.id.listview); // Set up the onClickListener mClickListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parentView, View childView, int pos, long id) { BeerStyle s = list.get(pos); Intent i = new Intent(c, DisplayStyleActivity.class);
i.putExtra(Constants.KEY_STYLE, s);
3
kawasima/solr-jdbc
src/main/java/net/unit8/solr/jdbc/parser/ConditionParser.java
[ "public abstract class Expression {\n\tprotected SolrType type;\n\tprotected String columnName;\n\tprotected String tableName;\n\tprotected String alias;\n\tprotected SolrType originalType;\n\n\tpublic SolrType getType() {\n\t\tif(type == null)\n\t\t\treturn SolrType.UNKNOWN;\n\t\treturn type;\n\t}\n\n\t/**\n\t * JDBCとしてのカラム名を返します\n\t *\n\t * @return JDBCカラム名\n\t */\n\tpublic String getColumnName() {\n\t\treturn columnName;\n\t}\n\n\t/**\n\t * テーブル名を返します\n\t *\n\t * @return テーブル名\n\t */\n\tpublic String getTableName() {\n\t\treturn tableName;\n\t}\n\n\n\tpublic String getAlias() {\n\t\treturn alias;\n\t}\n\n\tpublic void setAlias(String alias) {\n\t\tthis.alias = alias;\n\t}\n\n\t/**\n\t * Solr内部のフィールド名を返します\n\t *\n\t * @return Solrの内部フィールド名\n\t */\n\tpublic String getSolrColumnName() {\n\t\tString typeName = (originalType == null) ? type.name() : \"M_\"+originalType.name();\n\t\treturn tableName + \".\" + columnName + \".\" + typeName;\n\t}\n\n\tpublic String getResultName() {\n\t\tif (StringUtils.isNotEmpty(alias)) {\n\t\t\treturn alias;\n\t\t}\n\t\treturn columnName;\n\t}\n\n\tpublic abstract long getPrecision();\n\n\tpublic abstract int getScale();\n\n\tpublic int getNullable() {\n\t\treturn ResultSetMetaData.columnNullableUnknown;\n\t}\n\n\tpublic String getSchemaName() {\n\t\treturn null;\n\t}\n\n public String getTypeName() {\n\n return (originalType == null) ? type.name() : DataType.getDataType(originalType).name + \"_ARRAY\";\n }\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getColumnName();\n\t}\n}", "public interface Item {\n\tpublic SolrValue getValue();\n}", "public class Parameter implements Item {\n private static final String SQL_WILDCARD_CHARS = \"%_%_\";\n\n\tprivate SolrValue value;\n\tprivate int index;\n\tprivate boolean needsLikeEscape;\n\tprivate String likeEscapeChar = \"%\";\n\tprivate Expression targetColumn;\n\n\tpublic Parameter(int index) {\n\t\tthis.index = index;\n\t}\n\n\tpublic void setValue(SolrValue value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic SolrValue getValue() {\n\t\tif(value == null) {\n\t\t\treturn ValueNull.INSTANCE;\n\t\t}\n\t\treturn value;\n\t}\n\n\tpublic void setColumn(Expression column) {\n\t\tthis.targetColumn = column;\n\t}\n\tpublic SolrType getType() {\n\t\tif (value != null) {\n\t\t\treturn value.getType();\n\t\t}\n\t\treturn SolrType.UNKNOWN;\n\t}\n\n\tpublic String getQueryString() {\n\t\tif (value != null) {\n\t\t\tif (needsLikeEscape) {\n\t\t\t\tif (targetColumn != null && targetColumn.getType() == SolrType.TEXT) {\n StringBuilder sb = processWildcard(value.getString());\n // If the parameter matched partially in the middle,\n // trim the first & last wildcards for the syntax of proper solr query.\n if (sb.charAt(sb.length() - 1) == '*') {\n if (sb.charAt(0) == '*')\n sb.deleteCharAt(0);\n sb.deleteCharAt(sb.length() - 1);\n return sb.toString();\n } else {\n throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n \"In TEXT type, supports partial matching in the middle of words only.\");\n }\n\t\t\t\t} else if (targetColumn.getType() == SolrType.STRING) {\n StringBuilder sb = processWildcard(value.getString());\n if (sb.charAt(0) != '*' && sb.charAt(sb.length() - 1) == '*') {\n return sb.toString();\n } else {\n throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n \"In STRING type, supports partial matching in the beginning of words only.\");\n }\n\t\t\t\t} else {\n throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n \"Like is not supported in this type.\");\n }\n\t\t\t} else {\n\t\t\t\treturn value.getQueryString();\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic int getIndex() {\n\t\treturn index;\n\t}\n\n\tpublic void setNeedsLikeEscape() {\n\t\tthis.needsLikeEscape = true;\n\t}\n\n\tpublic void setLikeEscapeChar(String likeEscapeChar) {\n\t\tthis.likeEscapeChar = likeEscapeChar;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn getQueryString();\n\t}\n\n private StringBuilder processWildcard(String value) {\n String escapedValue = value\n .replaceAll(\"\\\\*\", \"\\\\\\\\*\")\n .replaceAll(\"(?<!\\\\\" + likeEscapeChar + \")[\" + SQL_WILDCARD_CHARS + \"]\", \"*\")\n .replaceAll(\"\\\\\" + likeEscapeChar + \"([\" + SQL_WILDCARD_CHARS + \"])\", \"$1\");\n\n String[] tokens = escapedValue.split(\"(?<!\\\\\\\\)\\\\*\", -1);\n StringBuilder sb = new StringBuilder(escapedValue.length() + 20);\n for (int i=0; i < tokens.length; i++) {\n sb.append(ClientUtils.escapeQueryChars(tokens[i].replaceAll(\"\\\\\\\\\\\\*\", \"*\")));\n if (i < tokens.length -1)\n sb.append(\"*\");\n }\n return sb;\n }\n}", "public class DatabaseMetaDataImpl implements DatabaseMetaData {\n\tprivate final SolrConnection conn;\n\tprivate Map<String, List<Expression>> tableColumns = new HashMap<String, List<Expression>>();\n private Map<String, List<String>> tablePrimaryKeys = new HashMap<String, List<String>>();\n\tprivate Map<String, String> originalTables = new HashMap<String, String>();\n\n\tpublic DatabaseMetaDataImpl(SolrConnection conn) {\n\t\tthis.conn = conn;\n\t\tbuildMetadata();\n\t}\n\n\tprivate void buildMetadata() {\n\t\ttry {\n\t\t\tQueryResponse res = this.conn.getSolrServer().query(\n\t\t\t\t\tnew SolrQuery(\"meta.name:*\"));\n\n\t\t\tfor (SolrDocument doc : res.getResults()) {\n\t\t\t\tString tableName = doc.getFieldValue(\"meta.name\").toString();\n\t\t\t\tList<Expression> columns = new ArrayList<Expression>();\n\t\t\t\tfor (Object cols : doc.getFieldValues(\"meta.columns\")) {\n\t\t\t\t\tcolumns.add(new ColumnExpression(tableName + \".\"\n\t\t\t\t\t\t\t+ cols.toString()));\n\t\t\t\t}\n List<String> primaryKeys = new ArrayList<String>();\n Collection<Object> pkColumns = doc.getFieldValues(\"meta.primaryKeys\");\n if (pkColumns != null) {\n for (Object pkColumn : pkColumns) {\n primaryKeys.add(tableName + \".\" + pkColumn.toString());\n }\n }\n\t\t\t\ttableColumns.put(StringUtils.upperCase(tableName), columns);\n tablePrimaryKeys.put(StringUtils.upperCase(tableName), primaryKeys);\n\t\t\t\toriginalTables.put(StringUtils.upperCase(tableName), tableName);\n\t\t\t}\n\n\t\t} catch (Exception e) {\n\t\t\tthrow DbException.get(ErrorCode.IO_EXCEPTION, e, e.getLocalizedMessage());\n\t\t}\n\t}\n\n\tpublic Expression getSolrColumn(String tableName, String columnName) {\n\t\tfor (Expression solrColumn : this.tableColumns.get(StringUtils.upperCase(tableName))) {\n\t\t\tif (StringUtils.equals(solrColumn.getColumnName(), columnName)) {\n\t\t\t\treturn solrColumn;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\n\t}\n\n\tpublic List<Expression> getSolrColumns(String tableName) {\n\t\tif (tableColumns == null)\n\t\t\tbuildMetadata();\n\t\treturn this.tableColumns.get(StringUtils.upperCase(tableName));\n\t}\n\n\tpublic boolean hasTable(String tableName) {\n\t\treturn originalTables.containsKey(StringUtils.upperCase(tableName));\n\t}\n\n\tpublic String getOriginalTableName(String tableName) {\n\t\treturn originalTables.get(StringUtils.upperCase(tableName));\n\t}\n\n\t/**\n\t * Checks if all procedures callable.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean allProceduresAreCallable() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if it possible to query all tables returned by getTables.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean allTablesAreSelectable() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether an exception while auto commit is on closes all result\n\t * sets.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean autoCommitFailureClosesAllResultSets() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether data manipulation and CREATE/DROP is supported in\n\t * transactions.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean dataDefinitionCausesTransactionCommit() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether CREATE/DROP do not affect transactions.\n\t *\n\t * @return fasle\n\t */\n\t@Override\n\tpublic boolean dataDefinitionIgnoredInTransactions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether deletes are detected.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean deletesAreDetected(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the maximum row size includes blobs.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean doesMaxRowSizeIncludeBlobs() throws SQLException {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic ResultSet getAttributes(String catalog, String schemaPattern,\n\t\t\tString typeNamePattern, String attributeNamePattern)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getAttributes\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getBestRowIdentifier(String s, String s1, String s2,\n\t\t\tint i, boolean flag) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getBestRowIdentifier\").getSQLException();\n\t}\n\n\t@Override\n\tpublic String getCatalogSeparator() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getCatalogSeparator\").getSQLException();\n\t}\n\n\t@Override\n\tpublic String getCatalogTerm() throws SQLException {\n\t\tthrow DbException\n\t\t\t\t.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getCatalogTerm\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getCatalogs() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getCatalogs\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getClientInfoProperties() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getClientInfoProperties\").getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getColumnPrivileges(String s, String s1, String s2,\n\t\t\tString s3) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getColumnPrivileges\").getSQLException();\n\t}\n\n\t@Override\n\tpublic ResultSet getColumns(String catalog, String schema, String table,\n\t\t\tString columnNamePattern) throws SQLException {\n\t\tif (tableColumns == null) {\n\t\t\tbuildMetadata();\n\t\t}\n\n\t\tCollectionResultSet rs;\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"COLUMN_NAME\", \"DATA_TYPE\", \"TYPE_NAME\", \"COLUMN_SIZE\",\n\t\t\t\t\"BUFFER_LENGTH\", \"DECIMAL_DIGITS\", \"NUM_PREC_RADIX\",\n\t\t\t\t\"NULLABLE\", \"REMARKS\", \"COLUMN_DEF\", \"SQL_DATA_TYPE\",\n\t\t\t\t\"SQL_DATETIME_SUB\", \"CHAR_OCTET_LENGTH\", \"ORDINAL_POSITION\",\n\t\t\t\t\"IS_NULLABLE\", \"SCOPE_CATLOG\", \"SCOPE_SCHEMA\", \"SCOPE_TABLE\",\n\t\t\t\t\"SOURCE_DATA_TYPE\" };\n\t\trs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\n\t\tfor (Expression column : tableColumns.get(StringUtils.upperCase(table))) {\n\t\t\tObject[] columnMeta = new Object[22];\n\t\t\tcolumnMeta[1] = \"\"; // TABLE_SCHEM\n\t\t\tcolumnMeta[2] = column.getTableName();\n\t\t\tcolumnMeta[3] = column.getColumnName(); // COLUMN_NAME\n\n\t\t\tcolumnMeta[4] = DataType.getDataType(column.getType()).sqlType; // DATA_TYPE\n\t\t\tcolumnMeta[5] = column.getTypeName(); // TYPE_NAME\n\t\t\tcolumnMeta[6] = 0; // COLUMN_SIZE\n\t\t\tcolumnMeta[8] = 0; // DECIMAL_DIGITS\n\t\t\tcolumnMeta[10] = DatabaseMetaData.columnNullableUnknown; // NULLABLE\n\t\t\trs.add(Arrays.asList(columnMeta));\n\t\t}\n\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic Connection getConnection() throws SQLException {\n\t\treturn conn;\n\t}\n\n\t@Override\n\tpublic ResultSet getCrossReference(String s, String s1, String s2,\n\t\t\tString s3, String s4, String s5) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getCrossReference\");\n\t}\n\n\t@Override\n\tpublic String getDatabaseProductName() throws SQLException {\n\t\treturn \"solr\";\n\t}\n\n\t@Override\n\tpublic int getDatabaseMajorVersion() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getDatabaseMinorVersion() throws SQLException {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic String getDatabaseProductVersion() throws SQLException {\n\t\treturn \"0.1.4-SNAPSHOT\";\n\t}\n\n\t/**\n\t * Returns default transaction isolation.\n\t *\n\t * @return Connection.TRANSACTION_READ_COMMITTED\n\t */\n\t@Override\n\tpublic int getDefaultTransactionIsolation() throws SQLException {\n\t\treturn Connection.TRANSACTION_READ_COMMITTED;\n\t}\n\n\t@Override\n\tpublic int getDriverMajorVersion() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getDriverMinorVersion() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic String getDriverName() throws SQLException {\n\t\treturn \"solr-jdbc\";\n\t}\n\n\t@Override\n\tpublic String getDriverVersion() throws SQLException {\n\t\treturn \"0.1.4-SNAPSHOT\";\n\t}\n\n\t@Override\n\tpublic ResultSet getExportedKeys(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getExportedKeys\");\n\t}\n\n\t@Override\n\tpublic String getExtraNameCharacters() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getExtraNameCharacters\");\n\t}\n\n\t@Override\n\tpublic ResultSet getFunctionColumns(String s, String s1, String s2,\n\t\t\tString s3) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getFunctionColumns\");\n\t}\n\n\t@Override\n\tpublic ResultSet getFunctions(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getFunctions\");\n\t}\n\n\t@Override\n\tpublic String getIdentifierQuoteString() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getFunctionColumns\");\n\t}\n\n\t@Override\n\tpublic ResultSet getImportedKeys(String catalog, String schema, String table)\n\t\t\tthrows SQLException {\n\t\tCollectionResultSet rs = new CollectionResultSet();\n\t\tString[] columns = { \"PKTABLE_CAT\", \"PKTABLE_SCHEM\", \"PKTABLE_NAME\",\n\t\t\t\t\"PKCOLUMN_NAME\", \"FKTABLE_CAT\", \"FKTABLE_SCHEM\",\n\t\t\t\t\"FKTABLE_NAME\", \"FKCOLUMN_NAME\", \"KEY_SEQ\", \"UPDATE_RULE\",\n\t\t\t\t\"DELETE_RULE\", \"FK_NAME\", \"PK_NAME\", \"DEFERRABILITY\" };\n\t\trs.setColumns(Arrays.asList(columns));\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic ResultSet getIndexInfo(String catalog, String schema, String table,\n\t\t\tboolean unique, boolean approximate) throws SQLException {\n\t\tCollectionResultSet rs = new CollectionResultSet();\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"NON_UNIQUE\", \"INDEX_QUALIFIER\", \"INDEX_NAME\", \"TYPE\",\n\t\t\t\t\"ORDINAL_POSITION\", \"COLUMN_NAME\", \"ASC_OR_DESC\",\n\t\t\t\t\"CARDINALITY\", \"PAGES\", \"FILTER_CONDITION\" };\n\t\trs.setColumns(Arrays.asList(columns));\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic int getJDBCMajorVersion() throws SQLException {\n\t\treturn 2;\n\t}\n\n\t@Override\n\tpublic int getJDBCMinorVersion() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxBinaryLiteralLength() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getMaxBinaryLiteralLength\");\n\t}\n\n\t/**\n\t * Returns the maximum length for a catalog name.\n\t *\n\t * @return 0 for limit is unknown.\n\t */\n\t@Override\n\tpublic int getMaxCatalogNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Returns the maximum length of literals.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxCharLiteralLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Returns the maximum length of column names.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxColumnNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * SolrのFacetの仕様のため、1を返す.\n\t *\n\t */\n\t@Override\n\tpublic int getMaxColumnsInGroupBy() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInIndex() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInOrderBy() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInSelect() throws SQLException {\n\t\treturn 255;\n\t}\n\n\t@Override\n\tpublic int getMaxColumnsInTable() throws SQLException {\n\t\treturn 255;\n\t}\n\n\t@Override\n\tpublic int getMaxConnections() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxCursorNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxIndexLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxProcedureNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxRowSize() throws SQLException {\n\t\treturn 0; // No limitation\n\t}\n\n\t@Override\n\tpublic int getMaxSchemaNameLength() throws SQLException {\n\t\treturn 0; // No limitation\n\t}\n\n\t/**\n\t * Returns the maximum length of a statement.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxStatementLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Returns the maximum number of open statements.\n\t *\n\t * @return 0 for limit is unknown\n\t */\n\t@Override\n\tpublic int getMaxStatements() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxTableNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxTablesInSelect() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxUserNameLength() throws SQLException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic String getNumericFunctions() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getNumericFunctions\");\n\t}\n\n\t@Override\n\tpublic ResultSet getPrimaryKeys(String catalog, String schema, String table)\n\t\t\tthrows SQLException {\n\t\tCollectionResultSet rs;\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"COLUMN_NAME\", \"KEY_SEQ\", \"PK_NAME\" };\n\t\trs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\n\n short keySeq = 0;\n\t\tfor (String primaryKey : tablePrimaryKeys.get(StringUtils.upperCase(table))) {\n String[] pkTokens = StringUtils.split(primaryKey, \".\", 2);\n\t\t\tObject[] columnMeta = new Object[6];\n\t\t\tcolumnMeta[2] = pkTokens[0];\n\t\t\tcolumnMeta[3] = pkTokens[1]; //COLUMN_NAME\n\t\t\tcolumnMeta[4] = keySeq++; //KEY_SEQ\n\t\t\tcolumnMeta[5] = null; // PK_NAME\n\t\t\trs.add(Arrays.asList(columnMeta));\n\t\t}\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic ResultSet getProcedureColumns(String s, String s1, String s2,\n\t\t\tString s3) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getProcedureColumns\");\n\t}\n\n\t@Override\n\tpublic String getProcedureTerm() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getProcedureTerm\");\n\t}\n\n\t@Override\n\tpublic ResultSet getProcedures(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getProcedureTerm\");\n\t}\n\n\t@Override\n\tpublic int getResultSetHoldability() throws SQLException {\n\t\treturn ResultSet.HOLD_CURSORS_OVER_COMMIT;\n\t}\n\n\t@Override\n\tpublic RowIdLifetime getRowIdLifetime() throws SQLException {\n\t\treturn RowIdLifetime.ROWID_UNSUPPORTED;\n\t}\n\n\t@Override\n\tpublic String getSQLKeywords() throws SQLException {\n\t\tthrow DbException\n\t\t\t\t.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSQLKeywords\");\n\t}\n\n\t@Override\n\tpublic int getSQLStateType() throws SQLException {\n\t\treturn sqlStateXOpen;\n\t}\n\n\t@Override\n\tpublic String getSchemaTerm() throws SQLException {\n\t\treturn \"schema\";\n\t}\n\n\t@Override\n\tpublic ResultSet getSchemas() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSchemas\");\n\t}\n\n\t@Override\n\tpublic ResultSet getSchemas(String s, String s1) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSchemas\");\n\t}\n\n\t@Override\n\tpublic String getSearchStringEscape() throws SQLException {\n\t\treturn \"%\";\n\t}\n\n\t@Override\n\tpublic String getStringFunctions() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getStringFunctions\");\n\t}\n\n\t@Override\n\tpublic ResultSet getSuperTables(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException\n\t\t\t\t.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSuperTables\");\n\t}\n\n\t@Override\n\tpublic ResultSet getSuperTypes(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getSuperTypes\");\n\t}\n\n\t@Override\n\tpublic String getSystemFunctions() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getSystemFunctions\");\n\t}\n\n\t@Override\n\tpublic ResultSet getTablePrivileges(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getTablePrivileges\");\n\t}\n\n\t@Override\n\tpublic ResultSet getTableTypes() throws SQLException {\n\t\tString[] columns = { \"TABLE_TYPE\" };\n\t\tCollectionResultSet rs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\t\tObject[] record = { \"TABLE\" };\n\t\trs.add(Arrays.asList(record));\n\t\treturn rs;\n\t}\n\n\t@Override\n\tpublic ResultSet getTables(String catalog, String schema,\n\t\t\tString tableNamePattern, String[] types) throws SQLException {\n\t\tif (tableColumns == null) {\n\t\t\tbuildMetadata();\n\t\t}\n if (tableNamePattern == null)\n tableNamePattern = \"%\";\n\n\t\tCollectionResultSet rs;\n\t\tString[] columns = { \"TABLE_CAT\", \"TABLE_SCHEM\", \"TABLE_NAME\",\n\t\t\t\t\"TABLE_TYPE\", \"REMARKS\", \"TYPE_CAT\", \"TYPE_SCHEM\", \"TYPE_NAME\",\n\t\t\t\t\"SELF_REFERENCING_COL_NAME\", \"REF_GENERATION\" };\n\t\trs = new CollectionResultSet();\n\t\trs.setColumns(Arrays.asList(columns));\n\n\t\tPattern ptn = getPattern(tableNamePattern);\n\t\tfor (String tableName : tableColumns.keySet()) {\n\t\t\tif(ptn.matcher(tableName).matches()) {\n\t\t\t\tObject[] tableMeta = { null, \"\", tableName, \"TABLE\", \"\", null,\n\t\t\t\t\tnull, null, null, null };\n\t\t\t\trs.add(Arrays.asList(tableMeta));\n\t\t\t}\n\t\t}\n\n\t\treturn rs;\n\t}\n\n\tprotected Pattern getPattern(String ptnStr) {\n\t\tptnStr = ptnStr.replaceAll(\"(?<!\\\\\\\\)_\", \".?\").replaceAll(\"(?<!\\\\\\\\)%\", \".*?\");\n\t\treturn Pattern.compile(\"^\" + ptnStr + \"$\", Pattern.CASE_INSENSITIVE);\n\t}\n\n\t@Override\n\tpublic String getTimeDateFunctions() throws SQLException {\n\t\treturn \"\";\n\t}\n\n\t@Override\n\tpublic ResultSet getTypeInfo() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getTypeInfo\");\n\t}\n\n\t@Override\n\tpublic ResultSet getUDTs(String s, String s1, String s2, int[] ai)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getUDTs\");\n\t}\n\n\t@Override\n\tpublic String getURL() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getURL\");\n\t}\n\n\t@Override\n\tpublic String getUserName() throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"getUserName\");\n\t}\n\n\t@Override\n\tpublic ResultSet getVersionColumns(String s, String s1, String s2)\n\t\t\tthrows SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED,\n\t\t\t\t\"getVersionColumns\");\n\t}\n\n\t/**\n\t * Returns whether inserts are detected.\n\t */\n\t@Override\n\tpublic boolean insertsAreDetected(int i) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the catalog is at the beginning.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean isCatalogAtStart() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns the same as Connection.isReadOnly().\n\t *\n\t * @return if read only optimization is switched on\n\t */\n\t@Override\n\tpublic boolean isReadOnly() throws SQLException {\n\t\treturn conn.isReadOnly();\n\t}\n\n\t/**\n\t * Does the database make a copy before updating.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean locatorsUpdateCopy() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether NULL+1 is NULL or not.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean nullPlusNonNullIsNull() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted at the beginning (no matter if ASC or DESC is used).\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedAtStart() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted at the end (no matter if ASC or DESC is used).\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedAtEnd() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted high (bigger than anything that is not null).\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedHigh() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if NULL is sorted low (bigger than anything that is not null).\n\t */\n\t@Override\n\tpublic boolean nullsAreSortedLow() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether other deletes are visible.\n\t */\n\t@Override\n\tpublic boolean othersDeletesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether other inserts are visible.\n\t */\n\t@Override\n\tpublic boolean othersInsertsAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether other updates are visible.\n\t */\n\t@Override\n\tpublic boolean othersUpdatesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether own deletes are visible\n\t */\n\t@Override\n\tpublic boolean ownDeletesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether own inserts are visible\n\t */\n\t@Override\n\tpublic boolean ownInsertsAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether own updates are visible\n\t */\n\t@Override\n\tpublic boolean ownUpdatesAreVisible(int type) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns test as the\n\t * table name.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesLowerCaseIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE \"Test\"(ID INT), getTables returns test as the\n\t * table name.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesLowerCaseQuotedIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns Test as the\n\t * table name\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesMixedCaseIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE \"Test\"(ID INT), getTables returns Test as the\n\t * table name.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean storesMixedCaseQuotedIdentifiers() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns TEST as the\n\t * table name.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean storesUpperCaseIdentifiers() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE \"Test\"(ID INT), getTables returns TEST as the\n\t * table name.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean storesUpperCaseQuotedIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether SQL-92 entry level grammar is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsANSI92EntryLevelSQL() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether SQL-92 full level grammer is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsANSI92FullSQL() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether SQL-92 intermediate level grammar is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsANSI92IntermediateSQL() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsAlterTableWithAddColumn() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsAlterTableWithDropColumn() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether batch updates is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsBatchUpdates() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether the catalog name in INSERT, UPDATE, DELETE is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInDataManipulation() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInIndexDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInProcedureCalls() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCatalogsInTableDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether column aliasing is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsColumnAliasing() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether CONVERT is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsConvert() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether CONVERT is supported for one datatype to another.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsConvert(int fromType, int toType) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether ODBC Core SQL grammar is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsCoreSQLGrammar() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsCorrelatedSubqueries() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether data manipulation and CREATE/DROP is supported in\n\t * transactions.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsDataDefinitionAndDataManipulationTransactions()\n\t\t\tthrows SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether only data manipulations are supported in transactions.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsDataManipulationTransactionsOnly()\n\t\t\tthrows SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsDifferentTableCorrelationNames() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsExpressionsInOrderBy() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsExtendedSQLGrammar() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsFullOuterJoins() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsGetGeneratedKeys() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsGroupBy() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks whether a GROUP BY clause can use columns that are not in the\n\t * SELECT clause, provided that it specifies all the columns in the SELECT\n\t * clause.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsGroupByBeyondSelect() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether GROUP BY is supported if the column is not in the SELECT\n\t * list.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsGroupByUnrelated() throws SQLException {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean supportsIntegrityEnhancementFacility() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsLikeEscapeClause() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsLimitedOuterJoins() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether ODBC Minimum SQL grammar is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMinimumSQLGrammar() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if for CREATE TABLE Test(ID INT), getTables returns Test as the\n\t * table name.\n\t *\n\t * TODO case sensitiveに変更する。\n\t */\n\t@Override\n\tpublic boolean supportsMixedCaseIdentifiers() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks if a table created with CREATE TABLE \"Test\"(ID INT) is a different\n\t * table than a table created with CREATE TABLE TEST(ID INT).\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Does the database support multiple open result sets.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsMultipleOpenResults() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether multiple result sets are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMultipleResultSets() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether multiple transactions are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsMultipleTransactions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Does the database support named parameters.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsNamedParameters() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether columns with NOT NULL are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsNonNullableColumns() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether open result sets across commits are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsOpenCursorsAcrossCommit() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether open result sets across rollback are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsOpenCursorsAcrossRollback() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether open statements across commit are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsOpenStatementsAcrossCommit() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether open statements across rollback are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsOpenStatementsAcrossRollback() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether ORDER BY is supported if the column is not in the SELECT\n\t * list.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsOrderByUnrelated() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether outer joins are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsOuterJoins() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether positioned deletes are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsPositionedDelete() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether positioned updates are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsPositionedUpdate() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether a specific result set concurrency is supported.\n\t */\n\t@Override\n\tpublic boolean supportsResultSetConcurrency(int type, int concurrency)\n\t\t\tthrows SQLException {\n\t\treturn type != ResultSet.TYPE_SCROLL_SENSITIVE;\n\t}\n\n\t/**\n\t * Does this database supports a result set holdability.\n\t *\n\t * @return true if the holdability is ResultSet.CLOSE_CURSORS_AT_COMMIT\n\t */\n\t@Override\n\tpublic boolean supportsResultSetHoldability(int holdability)\n\t\t\tthrows SQLException {\n\t\treturn holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT;\n\t}\n\n\t/**\n\t * Returns whether a specific result set type is supported.\n\t */\n\t@Override\n\tpublic boolean supportsResultSetType(int type) throws SQLException {\n\t\treturn type != ResultSet.TYPE_SCROLL_SENSITIVE;\n\t}\n\n\t/**\n\t * Returns wheter savepoints is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSavepoints() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the schema name in INSERT, UPDATE, DELETE is supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInDataManipulation() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether the schema name in CREATE INDEX is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInIndexDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInProcedureCalls() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSchemasInTableDefinitions() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSelectForUpdate() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Does the database support statement pooling.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsStatementPooling() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether the database supports calling functions using the call syntax.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether stored procedures are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsStoredProcedures() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether subqueries (SELECT) in comparisons are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInComparisons() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether SELECT in EXISTS is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInExists() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether IN(SELECT...) is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInIns() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether subqueries in quantified expression are supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsSubqueriesInQuantifieds() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether table correlation names (table alias) are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsTableCorrelationNames() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether a specific transaction isolation level.\n\t *\n\t * @return true, if level is TRANSACTION_READ_COMMITTED\n\t */\n\t@Override\n\tpublic boolean supportsTransactionIsolationLevel(int level)\n\t\t\tthrows SQLException {\n\t\tswitch (level) {\n\t\tcase Connection.TRANSACTION_READ_COMMITTED:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Returns whether transactions are supported.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean supportsTransactions() throws SQLException {\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns whether UNION SELECT is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsUnion() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether UNION ALL SELECT is supported.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean supportsUnionAll() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether updates are detected.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean updatesAreDetected(int i) throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if this database use one file per table.\n\t *\n\t * @return false\n\t */\n\t@Override\n\tpublic boolean usesLocalFilePerTable() throws SQLException {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if this database store data in local files.\n\t *\n\t * @return true\n\t */\n\t@Override\n\tpublic boolean usesLocalFiles() throws SQLException {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isWrapperFor(Class<?> iface) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"isWrapperFor\")\n\t\t\t\t.getSQLException();\n\t}\n\n\t@Override\n\tpublic <T> T unwrap(Class<T> iface) throws SQLException {\n\t\tthrow DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, \"unwrap\")\n\t\t\t\t.getSQLException();\n\t}\n}", "public class DbException extends RuntimeException {\n\tprivate static final long serialVersionUID = -2273043887990931388L;\n\tprivate static final ResourceBundle MESSAGES;\n\n\tstatic {\n\t\tMESSAGES = ResourceBundle.getBundle(\"net.unit8.solr.jdbc.message.messages\");\n\t}\n\n\tprivate DbException(SQLException e) {\n\t\tsuper(e.getMessage(), e);\n\t}\n\n\tpublic static DbException get(int errorCode) {\n\t\treturn get(errorCode, (String)null);\n\t}\n\n\tpublic static DbException get(int errorCode, Throwable cause, String...params) {\n\t\treturn new DbException(getSQLException(errorCode, cause, params));\n\t}\n\n public static DbException get(int errorCode, String... params) {\n return new DbException(getSQLException(errorCode, null, params));\n }\n\n\tprivate static String translate(String key, String ... params) {\n\t\tString message = null;\n\t\tif(MESSAGES != null) {\n\t\t\tmessage = MESSAGES.getString(key);\n\t\t}\n\t\tif (message == null) {\n\t\t\tmessage = \"(Message \" + key + \" not found)\";\n\t\t}\n\t\tif (params != null) {\n\t\t\tmessage = MessageFormat.format(message, (Object[])params);\n\t\t}\n\t\treturn message;\n\t}\n\n\tpublic SQLException getSQLException() {\n\t\treturn (SQLException) getCause();\n\t}\n\tprivate static SQLException getSQLException(int errorCode, Throwable cause, String ... params) {\n\t\tString sqlstate = ErrorCode.getState(errorCode);\n\t\tString message = translate(sqlstate, params);\n\t\tSQLException sqlException = new SQLException(message, sqlstate, errorCode);\n if (cause != null)\n sqlException.initCause(cause);\n return sqlException;\n\t}\n\n public static SQLException toSQLException(Exception e) {\n if (e instanceof SQLException) {\n return (SQLException) e;\n }\n return convert(e).getSQLException();\n }\n\n public static DbException convert(Throwable e) {\n if (e instanceof DbException) {\n return (DbException) e;\n } else if (e instanceof SQLException) {\n return new DbException((SQLException) e);\n } else if (e instanceof InvocationTargetException) {\n return convertInvocation((InvocationTargetException) e, null);\n } else if (e instanceof IOException) {\n return get(ErrorCode.IO_EXCEPTION, e, e.toString());\n } else if (e instanceof OutOfMemoryError) {\n return get(ErrorCode.OUT_OF_MEMORY, e);\n } else if (e instanceof StackOverflowError || e instanceof LinkageError) {\n return get(ErrorCode.GENERAL_ERROR, e, e.toString());\n } else if (e instanceof Error) {\n throw (Error) e;\n }\n return get(ErrorCode.GENERAL_ERROR, e, e.toString());\n }\n\n public static DbException convertInvocation(InvocationTargetException te, String message) {\n Throwable t = te.getTargetException();\n if (t instanceof SQLException || t instanceof DbException) {\n return convert(t);\n }\n message = message == null ? t.getMessage() : message + \": \" + t.getMessage();\n return get(ErrorCode.EXCEPTION_IN_FUNCTION, t, message);\n }\n\n\tpublic static DbException getInvalidValueException(String value, String param) {\n\t\treturn get(ErrorCode.INVALID_VALUE, value, param);\n\t}\n\n}", "public class ErrorCode {\n\tpublic static final int NO_DATA_AVAILABLE = 2000;\n\tpublic static final int COLUMN_COUNT_DOES_NOT_MATCH = 21002;\n\tpublic static final int NUMERIC_VALUE_OUT_OF_RANGE = 22003;\n public static final int DATA_CONVERSION_ERROR_1 = 22018;\n\tpublic static final int DUPLICATE_KEY_1 = 23505;\n\n\tpublic static final int SYNTAX_ERROR = 42000;\n\tpublic static final int TABLE_OR_VIEW_ALREADY_EXISTS = 42101;\n\tpublic static final int TABLE_OR_VIEW_NOT_FOUND = 42102;\n\tpublic static final int COLUMN_NOT_FOUND = 42122;\n\n\tpublic static final int GENERAL_ERROR = 50000;\n\tpublic static final int UNKNOWN_DATA_TYPE = 50004;\n\tpublic static final int FEATURE_NOT_SUPPORTED = 50100;\n\n\tpublic static final int METHOD_NOT_ALLOWED_FOR_QUERY = 90001;\n\tpublic static final int METHOD_ONLY_ALLOWED_FOR_QUERY = 90002;\n\tpublic static final int NULL_NOT_ALLOWED = 90006;\n\tpublic static final int OBJECT_CLOSED = 90007;\n\tpublic static final int INVALID_VALUE = 90008;\n\tpublic static final int IO_EXCEPTION = 90028;\n public static final int URL_FORMAT_ERROR_2 = 90046;\n\tpublic static final int EXCEPTION_IN_FUNCTION = 90105;\n\tpublic static final int OUT_OF_MEMORY = 90108;\n\tpublic static final int METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT = 90130;\n\n\tpublic static String getState(int errorCode) {\n\t\tswitch(errorCode) {\n\t\tcase NO_DATA_AVAILABLE: return \"02000\";\n\t\tcase COLUMN_COUNT_DOES_NOT_MATCH: return \"21S02\";\n\t\tcase SYNTAX_ERROR: return \"42000\";\n\t\tcase TABLE_OR_VIEW_ALREADY_EXISTS: return \"42S01\";\n\t\tcase TABLE_OR_VIEW_NOT_FOUND: return \"42S02\";\n\t\tcase COLUMN_NOT_FOUND: return \"42S22\";\n\t\tcase FEATURE_NOT_SUPPORTED: return \"HYC00\";\n\t\tcase GENERAL_ERROR: return \"HY000\";\n\t\tdefault:\n\t\t\treturn \"\"+errorCode;\n\t\t}\n\t}\n}", "public class ValueDate extends SolrValue{\n\t\n\tprivate final Date value;\n\tprivate static final String[] parsePatterns = new String[]{\n\t\t\"yyyy/MM/dd\",\n\t\t\"yyyy/MM/dd HH:mm:ss\",\n\t\t\"yyyy-MM-dd\",\n\t\t\"yyyy-MM-dd'T'HH:mm:ssZZ\"\n\t};\n\t\n\tprivate ValueDate(Date value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic static Date parseDate(String s) {\n\t\tjava.util.Date date; \n\t\ttry {\n\t\t\tdate = DateUtils.parseDate(s, parsePatterns);\n\t\t} catch (ParseException e) {\n\t\t\treturn null;\n\t\t}\n\t\treturn (Date)date;\n\t}\n\t\n\t@Override\n\tpublic Date getDate() {\n\t\treturn (Date)value.clone();\n\t}\n\t\n\t@Override\n\tpublic Date getDateNoCopy() {\n\t\treturn value;\n\t}\n\t\n\tpublic static ValueDate get(Date date){\n\t\treturn new ValueDate(date);\n\t}\n\t\n\t@Override\n\tpublic String getQueryString() {\n\t\treturn DateFormatUtils.formatUTC(value,\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n\t}\n\t\n\t@Override\n\tpublic SolrType getType() {\n\t\treturn SolrType.DATE;\n\t}\n\n\t@Override\n\tpublic String getString() {\n\t\treturn DateFormatUtils.formatUTC(value,\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n\t}\n\n\t@Override\n\tpublic Object getObject() {\n\t\treturn getDate();\n\t}\n}", "public class ValueDouble extends SolrValue {\n\n\tprivate static final double DOUBLE_ZERO = 0.0;\n private static final double DOUBLE_ONE = 1.0;\n private static final ValueDouble ZERO = new ValueDouble(DOUBLE_ZERO);\n private static final ValueDouble ONE = new ValueDouble(DOUBLE_ONE);\n private static final ValueDouble NAN = new ValueDouble(Double.NaN);\n\n private final double value;\n\n private ValueDouble(double value) {\n \tthis.value = value;\n }\n\n @Override\n\tpublic SolrType getType() {\n return SolrType.DOUBLE;\n }\n\n\t@Override\n\tpublic Object getObject() {\n\t\treturn Double.valueOf(value);\n\t}\n\n\t@Override\n\tpublic String getQueryString() {\n\t\treturn getString();\n\t}\n\n\t@Override\n\tpublic String getString() {\n\t\treturn String.valueOf(value);\n\t}\n\n @Override\n\tpublic int getSignum() {\n return value == 0 ? 0 : (value < 0 ? -1 : 1);\n }\n\n public static ValueDouble get(double d) {\n if (DOUBLE_ZERO == d) {\n return ZERO;\n } else if (DOUBLE_ONE == d) {\n return ONE;\n } else if (Double.isNaN(d)) {\n return NAN;\n }\n return new ValueDouble(d);\n }\n\n}", "public class ValueLong extends SolrValue {\n\n\tprivate final long value;\n\t\n\tprivate ValueLong(long value) {\n\t\tthis.value = value;\n\t}\n\t\n\t@Override\n\tpublic int getSignum() {\n\t\treturn Long.signum(value);\n\t}\n\t\n\t@Override\n\tpublic SolrType getType() {\n\t\treturn SolrType.LONG;\n\t}\n\n\t@Override\n\tpublic Object getObject() {\n\t\treturn value;\n\t}\n\n\t@Override\n\tpublic String getQueryString() {\n\t\treturn getString();\n\t}\n\n\t@Override\n\tpublic String getString() {\n\t\treturn String.valueOf(value);\n\t}\n\t\n\tpublic static ValueLong get(long i) {\n\t\treturn new ValueLong(i);\n\t}\n\n}" ]
import java.sql.Date; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.jsqlparser.expression.AllComparisonExpression; import net.sf.jsqlparser.expression.AnyComparisonExpression; import net.sf.jsqlparser.expression.CaseExpression; import net.sf.jsqlparser.expression.DateValue; import net.sf.jsqlparser.expression.DoubleValue; import net.sf.jsqlparser.expression.ExpressionVisitor; import net.sf.jsqlparser.expression.Function; import net.sf.jsqlparser.expression.InverseExpression; import net.sf.jsqlparser.expression.JdbcParameter; import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.expression.NullValue; import net.sf.jsqlparser.expression.Parenthesis; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.TimeValue; import net.sf.jsqlparser.expression.TimestampValue; import net.sf.jsqlparser.expression.WhenClause; import net.sf.jsqlparser.expression.operators.arithmetic.Addition; import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd; import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseOr; import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseXor; import net.sf.jsqlparser.expression.operators.arithmetic.Concat; import net.sf.jsqlparser.expression.operators.arithmetic.Division; import net.sf.jsqlparser.expression.operators.arithmetic.Multiplication; import net.sf.jsqlparser.expression.operators.arithmetic.Subtraction; import net.sf.jsqlparser.expression.operators.conditional.AndExpression; import net.sf.jsqlparser.expression.operators.conditional.OrExpression; import net.sf.jsqlparser.expression.operators.relational.Between; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExistsExpression; import net.sf.jsqlparser.expression.operators.relational.GreaterThan; import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals; import net.sf.jsqlparser.expression.operators.relational.InExpression; import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; import net.sf.jsqlparser.expression.operators.relational.LikeExpression; import net.sf.jsqlparser.expression.operators.relational.Matches; import net.sf.jsqlparser.expression.operators.relational.MinorThan; import net.sf.jsqlparser.expression.operators.relational.MinorThanEquals; import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.statement.select.SubSelect; import org.apache.commons.lang.StringUtils; import net.unit8.solr.jdbc.expression.Expression; import net.unit8.solr.jdbc.expression.Item; import net.unit8.solr.jdbc.expression.Parameter; import net.unit8.solr.jdbc.impl.DatabaseMetaDataImpl; import net.unit8.solr.jdbc.message.DbException; import net.unit8.solr.jdbc.message.ErrorCode; import net.unit8.solr.jdbc.value.ValueDate; import net.unit8.solr.jdbc.value.ValueDouble; import net.unit8.solr.jdbc.value.ValueLong;
package net.unit8.solr.jdbc.parser; public class ConditionParser implements ExpressionVisitor { private final StringBuilder query; private List<Parameter> parameters; private String tableName; private final DatabaseMetaDataImpl metaData; private String likeEscapeChar; private ParseContext context = ParseContext.NONE; private Expression currentColumn = null; private static final Pattern pattern = Pattern.compile("\\?(\\d+)"); public ConditionParser(DatabaseMetaDataImpl metaData) { this.metaData = metaData; query = new StringBuilder(); parameters = new ArrayList<Parameter>(); } public ConditionParser(DatabaseMetaDataImpl metaData, List<Parameter> parameters) { this(metaData); this.parameters.addAll(parameters); } public void setTableName(String tableName) { this.tableName = metaData.getOriginalTableName(tableName); } public List<Parameter> getParameters() { return parameters; } public String getQuery(List<Parameter> params) { String queryString; if(query.length() == 0) { queryString = "id:@"+tableName+".*"; } else { queryString = query.toString(); } Matcher matcher = pattern.matcher(queryString); StringBuffer sb = new StringBuffer(); while(matcher.find()) { String index = matcher.group(1); int paramIndex = Integer.parseInt(index); String paramStr = params.get(paramIndex).getQueryString(); // In appendReplacement method, '\' is interpreted for escape sequence. matcher.appendReplacement(sb, StringUtils.replace(paramStr, "\\", "\\\\")); } matcher.appendTail(sb); return sb.toString(); } @Override public void visit(SubSelect arg0) { throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, "subquery"); } @Override public void visit(NullValue arg0) { query.append("\"\""); } @Override public void visit(Function func) { throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, func.getName()); } @Override public void visit(InverseExpression arg0) { throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED, "-"); } @Override public void visit(JdbcParameter ph) { Parameter p = new Parameter(parameters.size()); if(context == ParseContext.LIKE) { p.setNeedsLikeEscape(); if(StringUtils.isNotBlank(likeEscapeChar)) { p.setLikeEscapeChar(likeEscapeChar); } } p.setColumn(currentColumn); parameters.add(p); query.append("?").append(p.getIndex()); } @Override public void visit(DoubleValue value) { query.append(ValueDouble.get(value.getValue()).getQueryString()); } @Override public void visit(LongValue value) {
query.append(ValueLong.get(value.getValue()).getQueryString());
8
cjstehno/ersatz
ersatz/src/test/java/io/github/cjstehno/ersatz/expectations/ErsatzServerAnyExpectationsTest.java
[ "public class ErsatzServer implements Closeable {\r\n\r\n private final UnderlyingServer underlyingServer;\r\n private final ServerConfigImpl serverConfig;\r\n\r\n /**\r\n * Creates a new Ersatz server instance with empty (default) configuration.\r\n */\r\n public ErsatzServer() {\r\n this.serverConfig = new ServerConfigImpl();\r\n this.serverConfig.setStarter(this::start);\r\n\r\n this.underlyingServer = new UndertowUnderlyingServer(serverConfig);\r\n }\r\n\r\n /**\r\n * Creates a new Ersatz server instance configured by the provided <code>Consumer</code>, which will have an instance of <code>ServerConfig</code>\r\n * passed into it for server configuration.\r\n *\r\n * @param consumer the configuration consumer\r\n */\r\n public ErsatzServer(final Consumer<ServerConfig> consumer) {\r\n this();\r\n if (consumer != null) {\r\n consumer.accept(serverConfig);\r\n }\r\n }\r\n\r\n /**\r\n * Used to retrieve the port where the HTTP server is running.\r\n *\r\n * @return the HTTP port\r\n */\r\n public int getHttpPort() {\r\n return underlyingServer.getActualHttpPort();\r\n }\r\n\r\n /**\r\n * Used to retrieve the port where the HTTPS server is running.\r\n *\r\n * @return the HTTPS port\r\n */\r\n public int getHttpsPort() {\r\n return underlyingServer.getActualHttpsPort();\r\n }\r\n\r\n /**\r\n * Used to retrieve whether HTTPS is enabled or not.\r\n *\r\n * @return true if HTTPS is enabled\r\n */\r\n public boolean isHttpsEnabled() {\r\n return serverConfig.isHttpsEnabled();\r\n }\r\n\r\n /**\r\n * Used to retrieve the full URL of the HTTP server.\r\n *\r\n * @return the full URL of the HTTP server\r\n */\r\n public String getHttpUrl() {\r\n return getUrl(\"http\", getHttpPort());\r\n }\r\n\r\n /**\r\n * Used to retrieve the full URL of the HTTPS server.\r\n *\r\n * @return the full URL of the HTTP server\r\n */\r\n public String getHttpsUrl() {\r\n return getUrl(\"https\", getHttpsPort());\r\n }\r\n\r\n private String getUrl(final String prefix, final int port) {\r\n if (port > 0) {\r\n return prefix + \"://localhost:\" + port;\r\n } else {\r\n throw new IllegalStateException(\"The port (\" + port + \") is invalid: Has the server been started?\");\r\n }\r\n }\r\n\r\n /**\r\n * A helper method which may be used to append the given path to the server HTTP url.\r\n *\r\n * @param path the path to be applied\r\n * @return the resulting URL\r\n */\r\n public String httpUrl(final String path) {\r\n return getHttpUrl() + path;\r\n }\r\n\r\n /**\r\n * A helper method which may be used to append the given path to the server HTTPS url.\r\n *\r\n * @param path the path to be applied\r\n * @return the resulting URL\r\n */\r\n public String httpsUrl(final String path) {\r\n return getHttpsUrl() + path;\r\n }\r\n\r\n /**\r\n * Used to configure HTTP expectations on the server; the provided <code>Consumer&lt;Expectations&gt;</code> implementation will have an active\r\n * <code>Expectations</code> object passed into it for configuring server interaction expectations.\r\n * <p>\r\n * Calling this method when auto-start is enabled will start the server.\r\n *\r\n * @param expects the <code>Consumer&lt;Expectations&gt;</code> instance to perform the configuration\r\n * @return a reference to this server\r\n */\r\n public ErsatzServer expectations(final Consumer<Expectations> expects) {\r\n serverConfig.expectations(expects);\r\n\r\n if (serverConfig.isAutoStartEnabled()) {\r\n underlyingServer.start();\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * An alternate means of starting the expectation chain.\r\n * <p>\r\n * Calling this method when auto-start is enabled will <b>NOT</b> start the server. Use one of the other expectation configuration method if\r\n * auto-start functionality is desired.\r\n *\r\n * @return the reference to the Expectation configuration object\r\n */\r\n public Expectations expects() {\r\n return serverConfig.expects();\r\n }\r\n\r\n /**\r\n * Used to specify the server request timeout property value on the server.\r\n * <p>\r\n * The IDLE_TIMEOUT, NO_REQUEST_TIMEOUT, REQUEST_PARSE_TIMEOUT, READ_TIMEOUT and WRITE_TIMEOUT are all configured to the same specified\r\n * value.\r\n *\r\n * @param value the timeout value\r\n * @param units the units the timeout is specified with\r\n * @return a reference to the server being configured\r\n */\r\n public ServerConfig timeout(final int value, final TimeUnit units) {\r\n return serverConfig.timeout(value, units);\r\n }\r\n\r\n /**\r\n * Used to specify the server request timeout property value on the server (in seconds).\r\n * <p>\r\n * The IDLE_TIMEOUT, NO_REQUEST_TIMEOUT, REQUEST_PARSE_TIMEOUT, READ_TIMEOUT and WRITE_TIMEOUT are all configured to the same specified\r\n * value.\r\n *\r\n * @param value the timeout value\r\n * @return a reference to the server being configured\r\n */\r\n public ServerConfig timeout(final int value) {\r\n return timeout(value, SECONDS);\r\n }\r\n\r\n /**\r\n * Used to start the HTTP server for test interactions. This method should be called after configuration of expectations and before the test\r\n * interactions are executed against the server.\r\n *\r\n * @return a reference to this server\r\n */\r\n public ErsatzServer start() {\r\n underlyingServer.start();\r\n return this;\r\n }\r\n\r\n /**\r\n * Clears all configured expectations from the server. Does not affect global encoders or decoders.\r\n */\r\n public void clearExpectations() {\r\n serverConfig.clearExpectations();\r\n }\r\n\r\n /**\r\n * Used to stop the HTTP server. The server may be restarted after it has been stopped.\r\n */\r\n public void stop() {\r\n underlyingServer.stop();\r\n }\r\n\r\n /**\r\n * An alias to the <code>stop()</code> method.\r\n */\r\n @Override\r\n public void close() {\r\n stop();\r\n }\r\n\r\n /**\r\n * Used to verify that all of the expected request interactions were called the appropriate number of times. This method should be called after\r\n * all test interactions have been performed. This is an optional step since generally you will also be receiving the expected response back\r\n * from the server; however, this verification step can come in handy when simply needing to know that a request is actually called or not.\r\n *\r\n * @param timeout the timeout value\r\n * @param unit the timeout unit\r\n * @return <code>true</code> if all call criteria were met during test execution.\r\n */\r\n public boolean verify(final long timeout, final TimeUnit unit) {\r\n return serverConfig.getExpectations().verify(timeout, unit);\r\n }\r\n\r\n /**\r\n * Used to verify that all of the expected request interactions were called the appropriate number of times. This method should be called after\r\n * all test interactions have been performed. This is an optional step since generally you will also be receiving the expected response back\r\n * from the server; however, this verification step can come in handy when simply needing to know that a request is actually called or not.\r\n *\r\n * @param timeout the timeout value (in seconds)\r\n * @return <code>true</code> if all call criteria were met during test execution.\r\n */\r\n public boolean verify(final long timeout) {\r\n return verify(timeout, SECONDS);\r\n }\r\n\r\n /**\r\n * Used to verify that all of the expected request interactions were called the appropriate number of times. This method should be called after\r\n * all test interactions have been performed. This is an optional step since generally you will also be receiving the expected response back\r\n * from the server; however, this verification step can come in handy when simply needing to know that a request is actually called or not.\r\n *\r\n * @return <code>true</code> if all call criteria were met during test execution.\r\n */\r\n public boolean verify() {\r\n return verify(1, SECONDS);\r\n }\r\n}\r", "public class ErsatzServerExtension implements BeforeEachCallback, AfterEachCallback {\r\n\r\n @Override public void beforeEach(final ExtensionContext context) throws Exception {\r\n findInstance(context.getRequiredTestInstance(), true).start();\r\n }\r\n\r\n @Override public void afterEach(final ExtensionContext context) throws Exception {\r\n val ersatzInstance = findInstance(context.getRequiredTestInstance(), false);\r\n if (ersatzInstance != null) {\r\n ersatzInstance.close();\r\n ersatzInstance.clearExpectations();\r\n }\r\n }\r\n\r\n private static ErsatzServer findInstance(final Object testInstance, final boolean create) throws Exception {\r\n try {\r\n val field = findField(testInstance);\r\n Object instance = field.get(testInstance);\r\n\r\n if (instance == null && create) {\r\n instance = field.getType().getDeclaredConstructor().newInstance();\r\n field.set(testInstance, instance);\r\n }\r\n\r\n return (ErsatzServer) instance;\r\n\r\n } catch (Exception throwable) {\r\n throw new Exception(throwable);\r\n }\r\n }\r\n\r\n private static Field findField(final Object testInstance) throws Exception {\r\n val field = stream(testInstance.getClass().getDeclaredFields())\r\n .filter(f -> f.getType().getSimpleName().endsWith(\"ErsatzServer\"))\r\n .findFirst()\r\n .orElseThrow((Supplier<Exception>) () -> new IllegalArgumentException(\"An ErsatzServer field must be specified.\"));\r\n\r\n field.setAccessible(true);\r\n return field;\r\n }\r\n}", "public class HttpClientExtension implements BeforeEachCallback {\n\n @Override public void beforeEach(final ExtensionContext context) throws Exception {\n val testInstance = context.getRequiredTestInstance();\n\n val server = findInstance(testInstance).start();\n\n val https = server.isHttpsEnabled();\n val client = new Client(server.getHttpUrl(), https ? server.getHttpsUrl() : server.getHttpUrl(), https);\n findField(testInstance, \"Client\").set(testInstance, client);\n }\n\n private static ErsatzServer findInstance(final Object testInstance) throws Exception {\n return (ErsatzServer) findField(testInstance, \"ErsatzServer\").get(testInstance);\n }\n\n private static Field findField(final Object testInstance, final String type) throws Exception {\n val field = stream(testInstance.getClass().getDeclaredFields())\n .filter(f -> f.getType().getSimpleName().endsWith(type))\n .findFirst()\n .orElseThrow(() -> new IllegalArgumentException(\"A field of type \" + type + \" must be specified.\"));\n field.setAccessible(true);\n\n return field;\n }\n\n /**\n * The HTTP client wrapper used by the HttpClientExtension. It may be used outside the extension.\n */\n public static class Client {\n\n private final String httpUrl;\n private final String httpsUrl;\n private final OkHttpClient client;\n\n public Client(final String httpUrl, final String httpsUrl, final boolean httpsEnabled) throws Exception {\n this.httpUrl = httpUrl;\n this.httpsUrl = httpsUrl;\n\n client = configureHttps(\n new OkHttpClient.Builder().cookieJar(new InMemoryCookieJar()),\n httpsEnabled\n ).build();\n }\n\n public Response get(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).get();\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response get(final String path, final Consumer<Request.Builder> config) throws IOException {\n return get(path, config, false);\n }\n\n public Response get(final String path, final boolean https) throws IOException {\n return get(path, null, https);\n }\n\n public Response get(final String path) throws IOException {\n return get(path, null, false);\n }\n\n public CompletableFuture<Response> aget(final String path, final Consumer<Request.Builder> config, final boolean https) {\n return supplyAsync(() -> {\n try {\n return get(path, config, https);\n } catch (IOException io) {\n throw new IllegalArgumentException(io.getMessage());\n }\n });\n }\n\n public CompletableFuture<Response> aget(final String path) {\n return aget(path, null, false);\n }\n\n public Response head(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).head();\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response head(final String path, final Consumer<Request.Builder> config) throws IOException {\n return head(path, config, false);\n }\n\n public Response head(final String path, final boolean https) throws IOException {\n return head(path, null, https);\n }\n\n public Response head(final String path) throws IOException {\n return head(path, null, false);\n }\n\n public Response delete(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).delete();\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response delete(final String path, final Consumer<Request.Builder> config) throws IOException {\n return delete(path, config, false);\n }\n\n public Response delete(final String path, final boolean https) throws IOException {\n return delete(path, null, https);\n }\n\n public Response delete(final String path) throws IOException {\n return delete(path, null, false);\n }\n\n public Response trace(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).method(\"TRACE\", null);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response options(final String path, final Consumer<Request.Builder> config, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).method(\"OPTIONS\", null);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response post(final String path, final Consumer<Request.Builder> config, final RequestBody body, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).post(body);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response post(final String path, final Consumer<Request.Builder> config, final RequestBody body) throws IOException {\n return post(path, config, body, false);\n }\n\n public Response post(final String path, final RequestBody body, final boolean https) throws IOException {\n return post(path, null, body, https);\n }\n\n public Response post(final String path, final RequestBody body) throws IOException {\n return post(path, null, body, false);\n }\n\n public Response put(final String path, final Consumer<Request.Builder> config, final RequestBody body, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).put(body);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response put(final String path, final Consumer<Request.Builder> config, final RequestBody body) throws IOException {\n return put(path, config, body, false);\n }\n\n public Response put(final String path, final RequestBody body, final boolean https) throws IOException {\n return put(path, null, body, https);\n }\n\n public Response put(final String path, final RequestBody body) throws IOException {\n return put(path, null, body, false);\n }\n\n public Response patch(final String path, final Consumer<Request.Builder> config, final RequestBody body, final boolean https) throws IOException {\n val request = new Request.Builder().url((https ? httpsUrl : httpUrl) + path).patch(body);\n if (config != null) config.accept(request);\n\n return client.newCall(request.build()).execute();\n }\n\n public Response patch(final String path, final Consumer<Request.Builder> config, final RequestBody body) throws IOException {\n return patch(path, config, body, false);\n }\n\n public Response patch(final String path, final RequestBody body, final boolean https) throws IOException {\n return patch(path, null, body, https);\n }\n\n public Response patch(final String path, final RequestBody body) throws IOException {\n return patch(path, null, body, false);\n }\n\n public static Request.Builder basicAuthHeader(final Request.Builder builder, final String user, final String pass) {\n return builder.header(AUTHORIZATION_HEADER, header(user, pass));\n }\n\n private static OkHttpClient.Builder configureHttps(final OkHttpClient.Builder builder, final boolean enabled) throws KeyManagementException, NoSuchAlgorithmException {\n if (enabled) {\n // Create a trust manager that does not validate certificate chains\n final var trustAllCerts = new TrustManager[]{\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n }\n };\n\n // Install the all-trusting trust manager\n val sslContext = SSLContext.getInstance(\"SSL\");\n sslContext.init(null, trustAllCerts, new SecureRandom());\n\n // Create an ssl socket factory with our all-trusting manager\n val sslSocketFactory = sslContext.getSocketFactory();\n\n builder.sslSocketFactory(\n sslSocketFactory,\n (X509TrustManager) trustAllCerts[0]\n )\n .hostnameVerifier((s, sslSession) -> true);\n }\n\n return builder;\n }\n }\n}", "static void assertOkWithString(final String content, final Response response) throws IOException {\n assertStatusWithString(200, content, response);\n}", "static void verify(final ErsatzServer server) {\n assertTrue(server.verify());\n}", "public static final ContentType TEXT_PLAIN = new ContentType(\"text/plain\");\r" ]
import io.github.cjstehno.ersatz.ErsatzServer; import io.github.cjstehno.ersatz.junit.ErsatzServerExtension; import io.github.cjstehno.ersatz.util.HttpClientExtension; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import static io.github.cjstehno.ersatz.TestAssertions.assertOkWithString; import static io.github.cjstehno.ersatz.TestAssertions.verify; import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN; import static okhttp3.MediaType.parse; import static okhttp3.RequestBody.create; import static org.hamcrest.Matchers.startsWith;
/** * Copyright (C) 2022 Christopher J. Stehno * * 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 io.github.cjstehno.ersatz.expectations; @ExtendWith({ErsatzServerExtension.class, HttpClientExtension.class}) public class ErsatzServerAnyExpectationsTest { private final ErsatzServer server = new ErsatzServer(cfg -> { cfg.https(); }); @SuppressWarnings("unused") private HttpClientExtension.Client client; @ParameterizedTest(name = "[{index}] path only: https({0}) -> {1}") @MethodSource("io.github.cjstehno.ersatz.TestArguments#httpAndHttpsWithContent") void withPath(final boolean https, final String responseText) throws IOException { server.expectations(expect -> {
expect.ANY("/something").secure(https).called(2).responds().body(responseText, TEXT_PLAIN);
5
BoD/irondad
src/main/java/org/jraf/irondad/handler/itsthisforthat/IsThisForThat.java
[ "public class Config {\n\n public static final boolean LOGD = true;\n\n}", "public class Constants {\n public static final String TAG = \"irondad/\";\n\n public static final String PROJECT_FULL_NAME = \"BoD irondad\";\n public static final String PROJECT_URL = \"https://github.com/BoD/irondad\";\n public static final String VERSION_NAME = \"v1.11.1\"; // xxx When updating this, don't forget to update the version in pom.xml as well\n}", "public abstract class CommandHandler extends BaseHandler {\n protected abstract String getCommand();\n\n @Override\n public boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext) {\n String command = getCommand();\n return text.trim().toLowerCase(Locale.getDefault()).startsWith(command.toLowerCase(Locale.getDefault()));\n }\n}", "public class HandlerContext extends HashMap<String, Object> {\n private final HandlerConfig mHandlerConfig;\n private final String mChannelName;\n private Connection mConnection;\n\n public HandlerContext(HandlerConfig handlerConfig, String channelName) {\n mHandlerConfig = handlerConfig;\n mChannelName = channelName;\n }\n\n public HandlerConfig getHandlerConfig() {\n return mHandlerConfig;\n }\n\n public void setConnection(Connection connection) {\n mConnection = connection;\n }\n\n public Connection getConnection() {\n return mConnection;\n }\n\n /**\n * @return {@code null} if this is a privmsg context.\n */\n public String getChannelName() {\n return mChannelName;\n }\n}", "public enum Command {\n //@formatter:off\n \n /*\n * Messages.\n */\n \n PING,\n PONG,\n NICK,\n USER,\n JOIN,\n PART,\n PRIVMSG,\n NAMES,\n QUIT,\n \n UNKNOWN, \n \n \n /*\n * Replies.\n */\n \n RPL_WELCOME(1),\n \n RPL_NAMREPLY(353),\n \n ERR_ERRONEUSNICKNAME(432),\n ERR_NICKNAMEINUSE(433),\n ERR_NICKCOLLISION(436),\n \n ;\n\n //@formatter:on\n\n private static final HashMap<String, Command> sCommandByName = new HashMap<String, Command>(40);\n private static final HashMap<Integer, Command> sCommandByCode = new HashMap<Integer, Command>(40);\n\n static {\n for (Command command : values()) {\n sCommandByName.put(command.name(), command);\n if (command.mCode != -1) sCommandByCode.put(command.mCode, command);\n }\n }\n\n private int mCode;\n\n private Command() {\n mCode = -1;\n }\n\n private Command(int code) {\n mCode = code;\n }\n\n public static Command from(String commandStr) {\n if (StringUtils.isNumeric(commandStr)) {\n // Reply (numeric command)\n return from(Integer.valueOf(commandStr));\n }\n // Message (string command)\n Command res = sCommandByName.get(commandStr);\n if (res == null) return UNKNOWN;\n return res;\n }\n\n public static Command from(int code) {\n Command res = sCommandByCode.get(code);\n if (res == null) return UNKNOWN;\n return res;\n }\n}", "public class Connection {\n private static final String TAG = Constants.TAG + Connection.class.getSimpleName();\n private static final String CR_LF = \"\\r\\n\";\n\n private Client mClient;\n private final BufferedReader mBufferedReader;\n private final OutputStream mOutputStream;\n\n public Connection(Client client, Socket socket) throws IOException {\n mClient = client;\n mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), \"utf-8\"));\n mOutputStream = socket.getOutputStream();\n }\n\n public void send(String line) throws IOException {\n Log.d(TAG, \"SND \" + line);\n mOutputStream.write((line + CR_LF).getBytes(\"utf-8\"));\n }\n\n public void send(Command command, String... params) throws IOException {\n String[] paramsCopy = params.clone();\n if (paramsCopy.length > 0) {\n // Add a colon to the last param if it contains spaces\n if (paramsCopy[paramsCopy.length - 1].contains(\" \")) {\n paramsCopy[paramsCopy.length - 1] = \":\" + paramsCopy[paramsCopy.length - 1];\n }\n send(command.name() + \" \" + StringUtils.join(paramsCopy, \" \"));\n } else {\n send(command.name());\n }\n }\n\n public void send(Command command, List<String> params) throws IOException {\n String[] paramArray = params.toArray(new String[params.size()]);\n send(command, paramArray);\n }\n\n public String receiveLine() throws IOException {\n String line = mBufferedReader.readLine();\n Log.i(TAG, \"RCV \" + line);\n return line;\n }\n\n public Message receive() throws IOException {\n String line = receiveLine();\n if (line == null) return null;\n Message res = Message.parse(line);\n // if (Config.LOGD) Log.d(TAG, \"receive res=\" + res);\n return res;\n }\n\n public Client getClient() {\n return mClient;\n }\n}", "public class Message {\n /**\n * Origin of the message (can be {@code null}).\n */\n public final Origin origin;\n public final Command command;\n public final ArrayList<String> parameters;\n\n public Message(Origin origin, Command command, ArrayList<String> parameters) {\n this.origin = origin;\n this.command = command;\n this.parameters = parameters;\n }\n\n public static Message parse(String line) {\n ArrayList<String> split = split(line);\n Origin origin = null;\n if (split.get(0).startsWith(\":\")) {\n // Prefix is an optional origin\n String originStr = split.remove(0);\n // Remove colon\n originStr = originStr.substring(1);\n origin = new Origin(originStr);\n }\n String commandStr = split.remove(0);\n Command command = Command.from(commandStr);\n return new Message(origin, command, split);\n }\n\n\n\n private static ArrayList<String> split(String line) {\n ArrayList<String> split = new ArrayList<String>(10);\n int len = line.length();\n StringBuilder currentToken = new StringBuilder(10);\n boolean previousCharIsSpace = false;\n boolean lastParam = false;\n for (int i = 0; i < len; i++) {\n char c = line.charAt(i);\n if (c == ' ' && !lastParam) {\n // Space\n split.add(currentToken.toString());\n currentToken = new StringBuilder(10);\n previousCharIsSpace = true;\n } else if (c == ':' && i != 0 && previousCharIsSpace) {\n // Colon: if at start of token, the remainder is the last param (can have spaces)\n lastParam = true;\n // currentToken.append(c);\n } else {\n // Other characters\n currentToken.append(c);\n previousCharIsSpace = false;\n }\n }\n split.add(currentToken.toString());\n return split;\n }\n\n @Override\n public String toString() {\n return \"Message [origin=\" + origin + \", command=\" + command + \", parameters=\" + parameters + \"]\";\n }\n}", "public class Log {\n public static void w(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" W \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void w(String tag, String msg) {\n System.out.print(getDate() + \" W \" + tag + \" \" + msg + \"\\n\");\n }\n\n public static void e(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" E \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void e(String tag, String msg) {\n System.out.print(getDate() + \" E \" + tag + \" \" + msg + \"\\n\");\n }\n\n public static void d(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" D \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void d(String tag, String msg) {\n System.out.print(getDate() + \" D \" + tag + \" \" + msg + \"\\n\");\n }\n\n public static void i(String tag, String msg, Throwable t) {\n System.out.print(getDate() + \" I \" + tag + \" \" + msg + \"\\n\" + getStackTraceString(t));\n }\n\n public static void i(String tag, String msg) {\n System.out.print(getDate() + \" I \" + tag + \" \" + msg + \"\\n\");\n }\n\n private static String getDate() {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd/HH:mm:ss\");\n return sdf.format(new Date());\n }\n\n private static String getStackTraceString(Throwable tr) {\n if (tr == null) {\n return \"\";\n }\n\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n tr.printStackTrace(pw);\n return sw.toString();\n }\n}" ]
import org.json.JSONObject; import com.github.kevinsawicki.http.HttpRequest; import org.jraf.irondad.Config; import org.jraf.irondad.Constants; import org.jraf.irondad.handler.CommandHandler; import org.jraf.irondad.handler.HandlerContext; import org.jraf.irondad.protocol.Command; import org.jraf.irondad.protocol.Connection; import org.jraf.irondad.protocol.Message; import org.jraf.irondad.util.Log; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2016 Nicolas Pomepuy * Copyright (C) 2013 Benoit 'BoD' Lubek ([email protected]) * * 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.jraf.irondad.handler.itsthisforthat; public class IsThisForThat extends CommandHandler { private static final String TAG = Constants.TAG + IsThisForThat.class.getSimpleName(); private static final String URL_HTML = "http://itsthisforthat.com/api.php?json"; private final ExecutorService mThreadPool = Executors.newCachedThreadPool(); @Override protected String getCommand() { return "!tft"; } @Override
protected void handleChannelMessage(final Connection connection, final String channel, String fromNickname, String text, List<String> textAsList,
5
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/uuid/CommandUuidResolver.java
[ "public static String colorize(String text) {\n if (text == null) return null;\n\n // Works best with interned strings\n String cacheResult = colorizeCache.get(text);\n if (cacheResult != null) return cacheResult;\n\n StringBuilder out = new StringBuilder();\n\n ColorizeState state = ColorizeState.TEXT;\n StringBuilder color = null;\n\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n\n if (state == ColorizeState.TEXT) {\n if (c == '{') {\n state = ColorizeState.COLOR_OPEN;\n }\n else if (c == '}') {\n state = ColorizeState.COLOR_CLOSE;\n }\n else if (c == '`') {\n state = ColorizeState.COLOR_ESCAPE;\n }\n else {\n out.append(c);\n }\n }\n else if (state == ColorizeState.COLOR_OPEN) {\n if (c == '{') { // Escaped bracket\n out.append('{');\n state = ColorizeState.TEXT;\n }\n else if (Character.isUpperCase(c)) {\n // First character of color name\n color = new StringBuilder();\n color.append(c);\n state = ColorizeState.COLOR_NAME;\n }\n else {\n // Invalid\n throw new IllegalArgumentException(\"Invalid color name\");\n }\n }\n else if (state == ColorizeState.COLOR_NAME) {\n if (Character.isUpperCase(c) || c == '_') {\n color.append(c);\n }\n else if (c == '}') {\n ChatColor chatColor = ChatColor.valueOf(color.toString());\n out.append(chatColor);\n state = ColorizeState.TEXT;\n }\n else {\n // Invalid\n throw new IllegalArgumentException(\"Invalid color name\");\n }\n }\n else if (state == ColorizeState.COLOR_CLOSE) {\n // Optional, but for sanity's sake, to keep brackets matched\n if (c == '}') {\n out.append('}'); // Collapse to single bracket\n }\n else {\n out.append('}');\n out.append(c);\n }\n state = ColorizeState.TEXT;\n }\n else if (state == ColorizeState.COLOR_ESCAPE) {\n out.append(decodeColor(c));\n state = ColorizeState.TEXT;\n }\n else\n throw new AssertionError(\"Unknown ColorizeState\");\n }\n \n // End of string\n if (state == ColorizeState.COLOR_CLOSE) {\n out.append('}');\n }\n else if (state != ColorizeState.TEXT) {\n // Was in the middle of color name\n throw new IllegalArgumentException(\"Invalid color name\");\n }\n\n cacheResult = out.toString();\n colorizeCache.putIfAbsent(text, cacheResult);\n\n return cacheResult;\n}", "public static void sendMessage(CommandSender sender, String format, Object... args) {\n String message = String.format(format, args);\n for (String line : message.split(\"\\n\")) {\n sender.sendMessage(line);\n }\n}", "public static boolean hasText(String text) {\n return text != null && text.trim().length() > 0;\n}", "public static void abortBatchProcessing() {\n if (isBatchProcessing())\n abortFlags.set(Boolean.TRUE);\n}", "public static boolean isBatchProcessing() {\n return abortFlags.get() != null;\n}", "public static UuidDisplayName parseUuidDisplayName(String name) {\n Matcher m = UUID_NAME_RE.matcher(name);\n if (m.matches()) {\n String uuidString = m.group(1);\n String displayName = m.group(2);\n \n if (uuidString.length() == 32)\n uuidString = shortUuidToLong(uuidString);\n UUID uuid;\n try {\n uuid = UUID.fromString(uuidString);\n }\n catch (IllegalArgumentException e) {\n return null;\n }\n return new UuidDisplayName(uuid, displayName);\n }\n return null;\n}" ]
import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.command.reader.CommandReader.abortBatchProcessing; import static org.tyrannyofheaven.bukkit.util.command.reader.CommandReader.isBatchProcessing; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import java.util.UUID; import java.util.concurrent.Executor; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin;
/* * Copyright 2014 ZerothAngel <[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.tyrannyofheaven.bukkit.util.uuid; public class CommandUuidResolver { private final Plugin plugin; private final UuidResolver uuidResolver; private final Executor executor; private final boolean abortInline; public CommandUuidResolver(Plugin plugin, UuidResolver uuidResolver, Executor executor, boolean abortInline) { this.plugin = plugin; this.uuidResolver = uuidResolver; this.executor = executor; this.abortInline = abortInline; } public void resolveUsername(CommandSender sender, String name, boolean skip, boolean forceInline, CommandUuidResolverHandler handler) { if (sender == null) throw new IllegalArgumentException("sender cannot be null"); if (handler == null) throw new IllegalArgumentException("handler cannot be null"); if (skip || name == null) { // Simple case: no need to resolve because skip is true or name is null, run inline handler.process(sender, name, null, skip); } else { // See if it's UUID or UUID/DisplayName UuidDisplayName udn = parseUuidDisplayName(name); if (udn != null) { String displayName; OfflinePlayer player = Bukkit.getOfflinePlayer(udn.getUuid()); if (player != null && player.getName() != null) { // Use last known name displayName = player.getName(); } else { // Default display name (either what was passed in or the UUID in string form) displayName = hasText(udn.getDisplayName()) ? udn.getDisplayName() : udn.getUuid().toString(); } handler.process(sender, displayName, udn.getUuid(), skip); } else { // Is the named player online? Player player = Bukkit.getPlayerExact(name); if (player != null) { // Simply run inline, no explicit lookup necessary handler.process(sender, player.getName(), player.getUniqueId(), skip); } else if (forceInline) { // Lookup & run inline udn = uuidResolver.resolve(name); if (udn == null) { fail(sender, name); } else { handler.process(sender, udn.getDisplayName(), udn.getUuid(), skip); } } else { // Check if cached by resolver udn = uuidResolver.resolve(name, true); if (udn != null) { // If so, run inline handler.process(sender, udn.getDisplayName(), udn.getUuid(), skip); } else { // As an absolute last resort, resolve and run async sendMessage(sender, colorize("{GRAY}(Resolving UUID...)")); Runnable task = new UsernameResolverHandlerRunnable(this, plugin, uuidResolver, sender, name, skip, handler); // NB Bukkit#getOfflinePlayer(String) provides almost the same service // However, it's not known whether it is fully thread-safe. executor.execute(task); } } } } } private static class UsernameResolverHandlerRunnable implements Runnable { private final CommandUuidResolver commandUuidResolver; private final Plugin plugin; private final UuidResolver uuidResolver; private final CommandSender sender; private final UUID senderUuid; private final String name; private final boolean skip; private final CommandUuidResolverHandler handler; private UsernameResolverHandlerRunnable(CommandUuidResolver commandUuidResolver, Plugin plugin, UuidResolver uuidResolver, CommandSender sender, String name, boolean skip, CommandUuidResolverHandler handler) { this.commandUuidResolver = commandUuidResolver; this.plugin = plugin; this.uuidResolver = uuidResolver; this.sender = sender instanceof Player ? null : sender; this.senderUuid = sender instanceof Player ? ((Player)sender).getUniqueId() : null; this.name = name; this.skip = skip; this.handler = handler; } private CommandSender getSender() { return sender; } @Override public void run() { // Perform lookup final UuidDisplayName udn = uuidResolver.resolve(name); // Run the rest in the main thread Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { // Re-lookup sender CommandSender sender = getSender() != null ? getSender() : Bukkit.getPlayer(senderUuid); // Only execute if sender is still around if (sender != null) { if (udn == null) { commandUuidResolver.fail(sender, name); } else { handler.process(sender, udn.getDisplayName(), udn.getUuid(), skip); } } } }); } } public void resolveUsername(CommandSender sender, String name, boolean skip, CommandUuidResolverHandler handler) { resolveUsername(sender, name, skip, isBatchProcessing(), handler); } public void resolveUsername(CommandSender sender, String name, CommandUuidResolverHandler handler) { resolveUsername(sender, name, false, isBatchProcessing(), handler); } private void fail(CommandSender sender, String name) { sendMessage(sender, colorize("{RED}Failed to lookup UUID for {AQUA}%s"), name);
if (abortInline) abortBatchProcessing();
3
kasirgalabs/ETUmulator
src/main/java/com/kasirgalabs/etumulator/visitor/BranchVisitor.java
[ "@Singleton\npublic class APSR implements Observable {\n private boolean negative;\n private boolean zero;\n private boolean carry;\n private boolean overflow;\n private final Dispatcher dispatcher;\n\n /**\n * Construct an APSR with {@link BaseDispatcher}.\n *\n * @see BaseDispatcher\n */\n public APSR() {\n this.dispatcher = new BaseDispatcher();\n }\n\n /**\n * Construct an APSR with the given dispatcher as parameter.\n *\n * @param dispatcher The dispatcher which will be used to notify observers.\n *\n * @see Dispatcher\n */\n @Inject\n public APSR(Dispatcher dispatcher) {\n this.dispatcher = dispatcher;\n }\n\n /**\n * Adds an observer to the list of observers for this object.\n *\n * @param observer The observer to be deleted.\n *\n * @see Observer\n */\n @Override\n public void addObserver(Observer observer) {\n dispatcher.addObserver(observer);\n }\n\n /**\n * @return The negative.\n */\n public boolean isNegative() {\n return negative;\n }\n\n /**\n * @param negative The negative to set.\n */\n public void setNegative(boolean negative) {\n this.negative = negative;\n dispatcher.notifyObservers(APSR.class);\n }\n\n /**\n * @return The zero.\n */\n public boolean isZero() {\n return zero;\n }\n\n /**\n * @param zero The zero to set.\n */\n public void setZero(boolean zero) {\n this.zero = zero;\n dispatcher.notifyObservers(APSR.class);\n }\n\n /**\n * @return The carry.\n */\n public boolean isCarry() {\n return carry;\n }\n\n /**\n * @param carry The carry to set.\n */\n public void setCarry(boolean carry) {\n this.carry = carry;\n dispatcher.notifyObservers(APSR.class);\n }\n\n /**\n * @return The overflow.\n */\n public boolean isOverflow() {\n return overflow;\n }\n\n /**\n * @param overflow The overflow to set.\n */\n public void setOverflow(boolean overflow) {\n this.overflow = overflow;\n dispatcher.notifyObservers(APSR.class);\n }\n\n /**\n * Updates negative and zero flag depending on the given value as parameter.\n *\n * @param value The value used to update negative and zero flag.\n *\n * @return The returns the given value.\n */\n public int updateNZ(int value) {\n negative = value < 0;\n zero = value == 0;\n dispatcher.notifyObservers(APSR.class);\n return value;\n }\n\n /**\n * Sets all the flags to false.\n */\n public void reset() {\n negative = false;\n zero = false;\n carry = false;\n overflow = false;\n dispatcher.notifyObservers(APSR.class);\n }\n}", "@Singleton\npublic class LR implements Observable {\n private int lr;\n private final Dispatcher dispatcher;\n\n /**\n * Construct a LR with {@link BaseDispatcher}.\n *\n * @see BaseDispatcher\n */\n public LR() {\n dispatcher = new BaseDispatcher();\n }\n\n /**\n * Construct a LR with the given dispatcher as parameter.\n *\n * @param dispatcher The dispatcher which will be used to notify observers.\n *\n * @see Dispatcher\n */\n @Inject\n public LR(Dispatcher dispatcher) {\n this.dispatcher = dispatcher;\n }\n\n /**\n * Adds an observer to the list of observers for this object.\n *\n * @param observer The observer to be deleted.\n *\n * @see Observer\n */\n @Override\n public void addObserver(Observer observer) {\n dispatcher.addObserver(observer);\n }\n\n /**\n * @param value The LR value to set.\n */\n public void setValue(int value) {\n lr = value;\n dispatcher.notifyObservers(LR.class);\n }\n\n /**\n * @return The value of LR.\n */\n public int getValue() {\n return lr;\n }\n\n /**\n * Sets LR value to zero.\n */\n public void reset() {\n lr = 0;\n dispatcher.notifyObservers(LR.class);\n }\n}", "@Singleton\npublic class PC implements Observable {\n private int pc;\n private final Dispatcher dispatcher;\n\n /**\n * Construct a PC with {@link BaseDispatcher}.\n *\n * @see BaseDispatcher\n */\n public PC() {\n dispatcher = new BaseDispatcher();\n }\n\n /**\n * Construct a PC with the given dispatcher as parameter.\n *\n * @param dispatcher The dispatcher which will be used to notify observers.\n *\n * @see Dispatcher\n */\n @Inject\n public PC(Dispatcher dispatcher) {\n this.dispatcher = dispatcher;\n }\n\n /**\n * Adds an observer to the list of observers for this object.\n *\n * @param observer The observer to be deleted.\n *\n * @see Observer\n */\n @Override\n public void addObserver(Observer observer) {\n dispatcher.addObserver(observer);\n }\n\n /**\n * Increases the value of PC by one.\n */\n public void increment() {\n pc++;\n dispatcher.notifyObservers(PC.class);\n }\n\n /**\n * @param value The PC value to set.\n */\n public void setValue(int value) {\n pc = value;\n dispatcher.notifyObservers(PC.class);\n }\n\n /**\n * @return The value of PC.\n */\n public int getValue() {\n return pc;\n }\n\n /**\n * Sets PC value to zero.\n */\n public void reset() {\n pc = 0;\n dispatcher.notifyObservers(PC.class);\n }\n}", "@Singleton\npublic class UART implements Observable {\n private RegisterFile registerFile;\n private char input;\n private final Dispatcher dispatcher;\n private CountDownLatch latch;\n\n public UART(RegisterFile registerFile) {\n this.registerFile = registerFile;\n this.dispatcher = new BaseDispatcher();\n }\n\n @Inject\n public UART(RegisterFile registerFile, Dispatcher dispatcher) {\n this.registerFile = registerFile;\n this.dispatcher = dispatcher;\n }\n\n public void setRegisterFile(RegisterFile registerFile) {\n this.registerFile = registerFile;\n }\n\n @Override\n public void addObserver(Observer observer) {\n dispatcher.addObserver(observer);\n }\n\n public void read() throws InterruptedException {\n latch = new CountDownLatch(1);\n dispatcher.notifyObservers(UART.class, \"read\");\n latch.await();\n registerFile.setValue(\"r0\", input);\n }\n\n public void write() {\n dispatcher.notifyObservers(UART.class, (char) registerFile.getValue(\"r0\"));\n }\n\n public void feed(char input) {\n this.input = input;\n latch.countDown();\n }\n}", "public class ProcessorBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements ProcessorVisitor<T> {\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitProg(ProcessorParser.ProgContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLine(ProcessorParser.LineContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitInstruction(ProcessorParser.InstructionContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitArithmetic(ProcessorParser.ArithmeticContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMultiplyAndDivide(ProcessorParser.MultiplyAndDivideContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMove(ProcessorParser.MoveContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitShift(ProcessorParser.ShiftContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitCompare(ProcessorParser.CompareContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLogical(ProcessorParser.LogicalContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitReverse(ProcessorParser.ReverseContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBranch(ProcessorParser.BranchContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSingleDataMemory(ProcessorParser.SingleDataMemoryContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitStack(ProcessorParser.StackContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBitfield(ProcessorParser.BitfieldContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAdd(ProcessorParser.AddContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAdds(ProcessorParser.AddsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAdc(ProcessorParser.AdcContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAdcs(ProcessorParser.AdcsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSub(ProcessorParser.SubContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSubs(ProcessorParser.SubsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSbc(ProcessorParser.SbcContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSbcs(ProcessorParser.SbcsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRsb(ProcessorParser.RsbContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRsbs(ProcessorParser.RsbsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRsc(ProcessorParser.RscContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRscs(ProcessorParser.RscsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMul(ProcessorParser.MulContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMuls(ProcessorParser.MulsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMla(ProcessorParser.MlaContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMlas(ProcessorParser.MlasContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMls(ProcessorParser.MlsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSdiv(ProcessorParser.SdivContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitUdiv(ProcessorParser.UdivContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMov(ProcessorParser.MovContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMovs(ProcessorParser.MovsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMvn(ProcessorParser.MvnContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMvns(ProcessorParser.MvnsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMovt(ProcessorParser.MovtContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAsr(ProcessorParser.AsrContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAsrs(ProcessorParser.AsrsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLsl(ProcessorParser.LslContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLsls(ProcessorParser.LslsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLsr(ProcessorParser.LsrContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLsrs(ProcessorParser.LsrsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRor(ProcessorParser.RorContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRors(ProcessorParser.RorsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRrx(ProcessorParser.RrxContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRrxs(ProcessorParser.RrxsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitCmp(ProcessorParser.CmpContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitCmn(ProcessorParser.CmnContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitTst(ProcessorParser.TstContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitTeq(ProcessorParser.TeqContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAnd(ProcessorParser.AndContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAnds(ProcessorParser.AndsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitEor(ProcessorParser.EorContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitEors(ProcessorParser.EorsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOrr(ProcessorParser.OrrContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOrrs(ProcessorParser.OrrsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOrn(ProcessorParser.OrnContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOrns(ProcessorParser.OrnsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBic(ProcessorParser.BicContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBics(ProcessorParser.BicsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRbit(ProcessorParser.RbitContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitB(ProcessorParser.BContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBeq(ProcessorParser.BeqContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBne(ProcessorParser.BneContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBcs(ProcessorParser.BcsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBhs(ProcessorParser.BhsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBcc(ProcessorParser.BccContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBlo(ProcessorParser.BloContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBmi(ProcessorParser.BmiContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBpl(ProcessorParser.BplContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBvs(ProcessorParser.BvsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBvc(ProcessorParser.BvcContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBhi(ProcessorParser.BhiContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBls(ProcessorParser.BlsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBge(ProcessorParser.BgeContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBlt(ProcessorParser.BltContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBgt(ProcessorParser.BgtContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBle(ProcessorParser.BleContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBal(ProcessorParser.BalContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBl(ProcessorParser.BlContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLdr(ProcessorParser.LdrContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLdrb(ProcessorParser.LdrbContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLdrh(ProcessorParser.LdrhContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitStr(ProcessorParser.StrContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitStrb(ProcessorParser.StrbContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitStrh(ProcessorParser.StrhContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitMemoryAddress(ProcessorParser.MemoryAddressContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitImmediateOffset(ProcessorParser.ImmediateOffsetContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitPostIndexedImmediate(ProcessorParser.PostIndexedImmediateContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRegisterOffset(ProcessorParser.RegisterOffsetContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitPostIndexedRegister(ProcessorParser.PostIndexedRegisterContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitPush(ProcessorParser.PushContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitPop(ProcessorParser.PopContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRegList(ProcessorParser.RegListContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRd(ProcessorParser.RdContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRn(ProcessorParser.RnContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRm(ProcessorParser.RmContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRs(ProcessorParser.RsContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOperand2(ProcessorParser.Operand2Context ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRegisterShiftedByRegister(ProcessorParser.RegisterShiftedByRegisterContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitRegisterShiftedByConstant(ProcessorParser.RegisterShiftedByConstantContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitShiftOption(ProcessorParser.ShiftOptionContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBfc(ProcessorParser.BfcContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitBfi(ProcessorParser.BfiContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLsb(ProcessorParser.LsbContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitWidth(ProcessorParser.WidthContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOpsh(ProcessorParser.OpshContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitSh(ProcessorParser.ShContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitOffset(ProcessorParser.OffsetContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitImm16(ProcessorParser.Imm16Context ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitImm12(ProcessorParser.Imm12Context ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitImm8m(ProcessorParser.Imm8mContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitLabel(ProcessorParser.LabelContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitData(ProcessorParser.DataContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitAsciz(ProcessorParser.AscizContext ctx) { return visitChildren(ctx); }\n\t/**\n\t * {@inheritDoc}\n\t *\n\t * <p>The default implementation returns the result of calling\n\t * {@link #visitChildren} on {@code ctx}.</p>\n\t */\n\t@Override public T visitNumber(ProcessorParser.NumberContext ctx) { return visitChildren(ctx); }\n}" ]
import com.kasirgalabs.etumulator.processor.APSR; import com.kasirgalabs.etumulator.processor.LR; import com.kasirgalabs.etumulator.processor.PC; import com.kasirgalabs.etumulator.processor.UART; import com.kasirgalabs.thumb2.ProcessorBaseVisitor; import com.kasirgalabs.thumb2.ProcessorParser; import java.util.concurrent.CancellationException;
package com.kasirgalabs.etumulator.visitor; public class BranchVisitor extends ProcessorBaseVisitor<Void> { private final APSR apsr;
private final UART uart;
3
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/bean/Issue.java
[ "public enum Include {\n // these values MUST BE exactly as they are written here,\n // can't use capital letters or rename.\n // they are provided in \"?include=...\" HTTP request\n journals, relations, attachments, changesets, watchers, children\n}", "public class NotFoundException extends RedmineException {\n\n private static final long serialVersionUID = 1L;\n\n public NotFoundException(String msg) {\n super(msg);\n }\n}", "public class RedmineAuthenticationException extends RedmineSecurityException {\n\tprivate static final long serialVersionUID = -2494397318821827279L;\n\n\tpublic RedmineAuthenticationException(String message) {\n super(message);\n }\n}", "public class RedmineException extends Exception {\n\tprivate static final long serialVersionUID = -1592189045756043062L;\n\n\tpublic RedmineException() {\n }\n\n public RedmineException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public RedmineException(String message) {\n super(message);\n }\n\n public RedmineException(Throwable cause) {\n super(cause);\n }\n}", "public class RequestParam {\n\n private final String name;\n private final String value;\n\n public RequestParam(final String name, final String value) {\n this.name = Objects.requireNonNull(name, \"Name may not be null\");\n this.value = Objects.requireNonNull(value, \"Value may not be null\");\n }\n\n public String getName() {\n return name;\n }\n\n public String getValue() {\n return value;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n RequestParam that = (RequestParam) o;\n return name.equals(that.name) &&\n value.equals(that.value);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, value);\n }\n\n @Override\n public String toString() {\n return \"RequestParam{\" +\n \"name='\" + name + '\\'' +\n \", value='\" + value + '\\'' +\n '}';\n }\n}", "public class Transport {\n\tprivate static final Map<Class<?>, EntityConfig<?>> OBJECT_CONFIGS = new HashMap<>();\n\tprivate static final String CONTENT_TYPE = \"application/json; charset=utf-8\";\n\tprivate static final int DEFAULT_OBJECTS_PER_PAGE = 25;\n\tprivate static final String KEY_TOTAL_COUNT = \"total_count\";\n\tprivate static final String KEY_LIMIT = \"limit\";\n\tprivate static final String KEY_OFFSET = \"offset\";\n\n\tprivate final Logger logger = LoggerFactory.getLogger(RedmineManager.class);\n\tprivate SimpleCommunicator<String> communicator;\n\tprivate Communicator<BasicHttpResponse> errorCheckingCommunicator;\n\tprivate Communicator<HttpResponse> authenticator;\n\n private String onBehalfOfUser = null;\n\n static {\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tProject.class,\n\t\t\t\tconfig(\"project\", \"projects\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeProject,\n\t\t\t\t\t\tRedmineJSONParser::parseProject));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssue.class,\n\t\t\t\tconfig(\"issue\", \"issues\", RedmineJSONBuilder::writeIssue,\n\t\t\t\t\t\tRedmineJSONParser::parseIssue));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tUser.class,\n\t\t\t\tconfig(\"user\", \"users\", RedmineJSONBuilder::writeUser,\n\t\t\t\t\t\tRedmineJSONParser::parseUser));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tGroup.class,\n\t\t\t\tconfig(\"group\", \"groups\", RedmineJSONBuilder::writeGroup,\n\t\t\t\t\t\tRedmineJSONParser::parseGroup));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssueCategory.class,\n\t\t\t\tconfig(\"issue_category\", \"issue_categories\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeCategory,\n\t\t\t\t\t\tRedmineJSONParser::parseCategory));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tVersion.class,\n\t\t\t\tconfig(\"version\", \"versions\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeVersion,\n\t\t\t\t\t\tRedmineJSONParser::parseVersion));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tTimeEntry.class,\n\t\t\t\tconfig(\"time_entry\", \"time_entries\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeTimeEntry,\n\t\t\t\t\t\tRedmineJSONParser::parseTimeEntry));\n\t\tOBJECT_CONFIGS.put(News.class,\n\t\t\t\tconfig(\"news\", \"news\", null, RedmineJSONParser::parseNews));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssueRelation.class,\n\t\t\t\tconfig(\"relation\", \"relations\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeRelation,\n\t\t\t\t\t\tRedmineJSONParser::parseRelation));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tTracker.class,\n\t\t\t\tconfig(\"tracker\", \"trackers\", null,\n\t\t\t\t\t\tRedmineJSONParser::parseTracker));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tIssueStatus.class,\n\t\t\t\tconfig(\"status\", \"issue_statuses\", null,\n\t\t\t\t\t\tRedmineJSONParser::parseStatus));\n\t\tOBJECT_CONFIGS\n\t\t\t\t.put(SavedQuery.class,\n\t\t\t\t\t\tconfig(\"query\", \"queries\", null,\n\t\t\t\t\t\t\t\tRedmineJSONParser::parseSavedQuery));\n\t\tOBJECT_CONFIGS.put(Role.class,\n\t\t\t\tconfig(\"role\", \"roles\", null, RedmineJSONParser::parseRole));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tMembership.class,\n\t\t\t\tconfig(\"membership\", \"memberships\",\n\t\t\t\t\t\tRedmineJSONBuilder::writeMembership,\n\t\t\t\t\t\tRedmineJSONParser::parseMembership));\n OBJECT_CONFIGS.put(\n IssuePriority.class,\n config(\"issue_priority\", \"issue_priorities\", null,\n RedmineJSONParser::parseIssuePriority));\n OBJECT_CONFIGS.put(\n TimeEntryActivity.class,\n config(\"time_entry_activity\", \"time_entry_activities\", null,\n RedmineJSONParser::parseTimeEntryActivity));\n\n OBJECT_CONFIGS.put(\n Watcher.class,\n config(\"watcher\", \"watchers\", null,\n RedmineJSONParser::parseWatcher));\n\n OBJECT_CONFIGS.put(\n WikiPage.class,\n config(\"wiki_page\", \"wiki_pages\", null, RedmineJSONParser::parseWikiPage)\n );\n\n OBJECT_CONFIGS.put(\n WikiPageDetail.class,\n config(\"wiki_page\", null, RedmineJSONBuilder::writeWikiPageDetail, RedmineJSONParser::parseWikiPageDetail)\n );\n OBJECT_CONFIGS.put(\n CustomFieldDefinition.class,\n config(\"custom_field\", \"custom_fields\", null,\n RedmineJSONParser::parseCustomFieldDefinition));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tAttachment.class,\n\t\t\t\tconfig(\"attachment\", \"attachments\", null,\n\t\t\t\t\t\tRedmineJSONParser::parseAttachments));\n\t\tOBJECT_CONFIGS.put(\n\t\t\t\tFile.class,\n\t\t\t\tconfig(\"file\", \"files\", null, RedmineJSONParser::parseFiles));\n }\n\n\tprivate URIConfigurator configurator;\n\tprivate int objectsPerPage = DEFAULT_OBJECTS_PER_PAGE;\n\tprivate static final String CHARSET = \"UTF-8\";\n\n\tpublic Transport(URIConfigurator configurator, HttpClient client) {\n\t\tvar baseCommunicator = new BaseCommunicator(client);\n\t\tvar redmineAuthenticator = new RedmineAuthenticator<>(baseCommunicator, CHARSET);\n\t\tconfigure(configurator, redmineAuthenticator);\n\t}\n\n\tpublic Transport(URIConfigurator configurator, Communicator communicator) {\n\t\tconfigure(configurator, communicator);\n\t}\n\n\tprivate void configure(URIConfigurator configurator, Communicator communicator) {\n\t\tthis.configurator = configurator;\n\t\tthis.authenticator = communicator;\n\t\tfinal ContentHandler<BasicHttpResponse, BasicHttpResponse> errorProcessor = new RedmineErrorHandler();\n\t\terrorCheckingCommunicator = Communicators.fmap(\n\t\t\t\tauthenticator,\n\t\t\t\tCommunicators.compose(errorProcessor,\n\t\t\t\t\t\tCommunicators.transportDecoder()));\n\t\tCommunicator<String> coreCommunicator = Communicators.fmap(errorCheckingCommunicator,\n\t\t\t\tCommunicators.contentReader());\n\t\tthis.communicator = Communicators.simplify(coreCommunicator,\n\t\t\t\tCommunicators.<String>identityHandler());\n\t}\n\n\tpublic User getCurrentUser(RequestParam... params) throws RedmineException {\n\t\tURI uri = getURIConfigurator().createURI(\"users/current.json\", params);\n\t\tHttpGet http = new HttpGet(uri);\n\t\tString response = send(http);\n\t\treturn parseResponse(response, \"user\", RedmineJSONParser::parseUser);\n\t}\n\n\t/**\n\t * Performs an \"add object\" request.\n\t * \n\t * @param object\n\t * object to use.\n\t * @param params\n\t * name params.\n\t * @return object to use.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <T> T addObject(T object, RequestParam... params)\n\t\t\tthrows RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(object.getClass());\n if (config.writer == null) {\n throw new RuntimeException(\"can't create object: writer is not implemented or is not registered in RedmineJSONBuilder for object \" + object);\n }\n\t\tURI uri = getURIConfigurator().getObjectsURI(object.getClass(), params);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tString body = RedmineJSONBuilder.toSimpleJSON(config.singleObjectName, object, config.writer);\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t\treturn parseResponse(response, config.singleObjectName, config.parser);\n\t}\n\n\t/**\n\t * Performs an \"add child object\" request.\n\t * \n\t * @param parentClass\n\t * parent object id.\n\t * @param object\n\t * object to use.\n\t * @param params\n\t * name params.\n\t * @return object to use.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <T> T addChildEntry(Class<?> parentClass, String parentId, T object,\n\t\t\tRequestParam... params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(object.getClass());\n\t\tURI uri = getURIConfigurator().getChildObjectsURI(parentClass,\n\t\t\t\tparentId, object.getClass(), params);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tString body = RedmineJSONBuilder.toSimpleJSON(config.singleObjectName,\n\t\t\t\tobject, config.writer);\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t\treturn parseResponse(response, config.singleObjectName, config.parser);\n\t}\n\n\t/*\n\t * note: This method cannot return the updated object from Redmine because\n\t * the server does not provide any XML in response.\n\t * \n\t * @since 1.8.0\n\t */\n\tpublic <T extends Identifiable> void updateObject(T obj,\n\t\t\tRequestParam... params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(obj.getClass());\n\t\tfinal Integer id = obj.getId();\n\t\tif (id == null) {\n\t\t\tthrow new RuntimeException(\"'id' field cannot be NULL in the given object:\" +\n\t\t\t\t\t\" it is required to identify the object in the target system\");\n\t\t}\n\t\tfinal URI uri = getURIConfigurator().getObjectURI(obj.getClass(),\n\t\t\t\tInteger.toString(id), params);\n\t\tfinal HttpPut http = new HttpPut(uri);\n\t\tfinal String body = RedmineJSONBuilder.toSimpleJSON(\n\t\t\t\tconfig.singleObjectName, obj, config.writer);\n\t\tsetEntity(http, body);\n\t\tsend(http);\n\t}\n\n\t/*\n\t * note: This method cannot return the updated object from Redmine because\n\t * the server does not provide anything in response.\n\t */\n\tpublic <T> void updateChildEntry(Class<?> parentClass, String parentId,\n\t\t\tT obj, String objId, RequestParam... params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(obj.getClass());\n\t\tURI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, obj.getClass(), objId, params);\n\t\tfinal HttpPut http = new HttpPut(uri);\n\t\tfinal String body = RedmineJSONBuilder.toSimpleJSON(config.singleObjectName, obj, config.writer);\n\t\tsetEntity(http, body);\n\t\tsend(http);\n\t}\n\n\t/**\n\t * Performs \"delete child Id\" request.\n\t * \n\t * @param parentClass\n\t * parent object id.\n\t * @param object\n\t * object to use.\n\t * @param value\n\t * child object id.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n public <T> void deleteChildId(Class<?> parentClass, String parentId, T object, Integer value) throws RedmineException {\n URI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, object.getClass(), value);\n HttpDelete httpDelete = new HttpDelete(uri);\n String response = send(httpDelete);\n logger.debug(response);\n }\n\n\t/**\n\t * Deletes an object.\n\t * \n\t * @param classs\n\t * object class.\n\t * @param id\n\t * object id.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <T extends Identifiable> void deleteObject(Class<T> classs, String id)\n\t\t\tthrows RedmineException {\n\t\tfinal URI uri = getURIConfigurator().getObjectURI(classs, id);\n\t\tfinal HttpDelete http = new HttpDelete(uri);\n\t\tsend(http);\n\t}\n\n\t/**\n\t * @param classs\n\t * target class\n\t * @param key\n\t * item key\n\t * @param params\n\t * extra arguments.\n\t * @throws RedmineAuthenticationException\n\t * invalid or no API access key is used with the server, which\n\t * requires authorization. Check the constructor arguments.\n\t * @throws NotFoundException\n\t * the object with the given key is not found\n\t * @throws RedmineException\n\t */\n\tpublic <T> T getObject(Class<T> classs, String key, RequestParam... params)\n\t\t\tthrows RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(classs);\n\t\tfinal URI uri = getURIConfigurator().getObjectURI(classs, key, params);\n\t\tfinal HttpGet http = new HttpGet(uri);\n\t\tString response = send(http);\n\t\tlogger.debug(response);\n\t\treturn parseResponse(response, config.singleObjectName, config.parser);\n\t}\n\n\t/**\n\t * Downloads redmine content.\n\t * \n\t * @param uri\n\t * target uri.\n\t * @param handler\n\t * content handler.\n\t * @return handler result.\n\t * @throws RedmineException\n\t * if something goes wrong.\n\t */\n\tpublic <R> R download(String uri,\n\t\t\tContentHandler<BasicHttpResponse, R> handler)\n\t\t\tthrows RedmineException {\n\t\tfinal HttpGet request = new HttpGet(uri);\n if (onBehalfOfUser != null) {\n request.addHeader(\"X-Redmine-Switch-User\", onBehalfOfUser);\n }\n return errorCheckingCommunicator.sendRequest(request, handler);\n }\n\n\t/**\n\t * Deprecated because Redmine server can return invalid string depending on its configuration.\n\t * See https://github.com/taskadapter/redmine-java-api/issues/78 .\n\t * <p>Use {@link #upload(InputStream, long)} instead.\n\t *\n\t * <p>\n\t * Uploads content on a server. This method calls {@link #upload(InputStream, long)} with -1 as content length.\n\t * \n\t * @param content the content stream.\n\t * @return uploaded item token.\n\t * @throws RedmineException if something goes wrong.\n\t */\n\t@Deprecated\n\tpublic String upload(InputStream content) throws RedmineException {\n\t\treturn upload(content, -1);\n\t}\n\n\t/**\n\t * @param content the content\n\t * @param contentLength the length of the content in bytes. you can provide -1 but be aware that some\n\t * users reported Redmine configuration problems that prevent it from processing -1 correctly.\n\t * See https://github.com/taskadapter/redmine-java-api/issues/78 for details.\n\t * @return the string token of the uploaded item. see {@link Attachment#getToken()}\n\t */\n\tpublic String upload(InputStream content, long contentLength) throws RedmineException {\n\t\tfinal URI uploadURI = getURIConfigurator().getUploadURI();\n\t\tfinal HttpPost request = new HttpPost(uploadURI);\n\t\tfinal AbstractHttpEntity entity = new InputStreamEntity(content, contentLength);\n\t\t/* Content type required by a Redmine */\n\t\tentity.setContentType(\"application/octet-stream\");\n\t\trequest.setEntity(entity);\n\n\t\tfinal String result = send(request);\n\t\treturn parseResponse(result, \"upload\", input -> JsonInput.getStringNotNull(input, \"token\"));\n\t}\n\n\t/**\n\t * @param classs\n\t * target class\n\t * @param key\n\t * item key\n\t * @param params\n\t * extra arguments.\n\t * @throws RedmineAuthenticationException\n\t * invalid or no API access key is used with the server, which\n\t * requires authorization. Check the constructor arguments.\n\t * @throws NotFoundException\n\t * the object with the given key is not found\n\t * @throws RedmineException\n\t */\n\tpublic <T> T getObject(Class<T> classs, Integer key, RequestParam... params) throws RedmineException {\n\t\treturn getObject(classs, key.toString(), params);\n\t}\n\n\tpublic <T> List<T> getObjectsList(Class<T> objectClass, RequestParam... params) throws RedmineException {\n\t\treturn getObjectsList(objectClass, Arrays.asList(params));\n\t}\n\n\t/**\n\t * Returns all objects found using the provided parameters.\n\t * This method IGNORES \"limit\" and \"offset\" parameters and handles paging AUTOMATICALLY for you.\n\t * Please use getObjectsListNoPaging() method if you want to control paging yourself with \"limit\" and \"offset\" parameters.\n\t * \n\t * @return objects list, never NULL\n\t *\n\t * @see #getObjectsListNoPaging(Class, Collection)\n\t */\n\tpublic <T> List<T> getObjectsList(Class<T> objectClass,\n\t\t\t\t\t\t\t\t\t Collection<? extends RequestParam> params) throws RedmineException {\n\t\tfinal List<T> result = new ArrayList<>();\n\t\tint offset = 0;\n\n\t\tInteger totalObjectsFoundOnServer;\n\t\tdo {\n\t\t\tfinal List<RequestParam> newParams = new ArrayList<>(params);\n\t\t\tnewParams.add(new RequestParam(\"limit\", String.valueOf(objectsPerPage)));\n\t\t\tnewParams.add(new RequestParam(\"offset\", String.valueOf(offset)));\n\n\t\t\tfinal ResultsWrapper<T> wrapper = getObjectsListNoPaging(objectClass, newParams);\n\t\t\tresult.addAll(wrapper.getResults());\n\n\t\t\ttotalObjectsFoundOnServer = wrapper.getTotalFoundOnServer();\n\t\t\t// Necessary for trackers.\n\t\t\t// TODO Alexey: is this still necessary for Redmine 2.x?\n\t\t\tif (totalObjectsFoundOnServer == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!wrapper.hasSomeResults()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toffset += wrapper.getResultsNumber();\n\t\t} while (offset < totalObjectsFoundOnServer);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns an object list. Provide your own \"limit\" and \"offset\" parameters if you need those, otherwise\n\t * this method will return the first page of some default size only (this default is controlled by\n\t * your Redmine configuration).\n\t *\n\t * @return objects list, never NULL\n\t */\n\tpublic <T> ResultsWrapper<T> getObjectsListNoPaging(Class<T> objectClass,\n\t\t\t\t\t\t\t\t\t\t\t Collection<? extends RequestParam> params) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(objectClass);\n\t\ttry {\n\t\t\tfinal JSONObject responseObject = getJsonResponseFromGet(objectClass, params);\n\t\t\tList<T> results = JsonInput.getListOrNull(responseObject, config.multiObjectName, config.parser);\n\t\t\tInteger totalFoundOnServer = JsonInput.getIntOrNull(responseObject, KEY_TOTAL_COUNT);\n\t\t\tInteger limitOnServer = JsonInput.getIntOrNull(responseObject, KEY_LIMIT);\n\t\t\tInteger offsetOnServer = JsonInput.getIntOrNull(responseObject, KEY_OFFSET);\n\t\t\treturn new ResultsWrapper<>(totalFoundOnServer, limitOnServer, offsetOnServer, results);\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineFormatException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Use this method if you need direct access to Json results.\n\t <pre>\n\t Params params = new Params()\n\t .add(...)\n getJsonResponseFromGet(Issue.class, params);\n\t </pre>\n\t */\n\tpublic <T> JSONObject getJsonResponseFromGet(Class<T> objectClass,\n\t\t\t\t\t\t\t\t\t\t\t\t Collection<? extends RequestParam> params) throws RedmineException, JSONException {\n\t\tfinal List<RequestParam> newParams = new ArrayList<>(params);\n\t\tList<RequestParam> paramsList = new ArrayList<>(newParams);\n\t\tfinal URI uri = getURIConfigurator().getObjectsURI(objectClass, paramsList);\n\t\tfinal HttpGet http = new HttpGet(uri);\n\t\tfinal String response = send(http);\n\t\treturn RedmineJSONParser.getResponse(response);\n\t}\n\n\tpublic <T> List<T> getChildEntries(Class<?> parentClass, int parentId, Class<T> classs) throws RedmineException {\n\t\treturn getChildEntries(parentClass, parentId + \"\", classs);\n\t}\n\n\t/**\n\t * Delivers a list of a child entries.\n\t * \n\t * @param classs\n\t * target class.\n\t */\n\tpublic <T> List<T> getChildEntries(Class<?> parentClass, String parentKey, Class<T> classs) throws RedmineException {\n\t\tfinal EntityConfig<T> config = getConfig(classs);\n\t\tfinal URI uri = getURIConfigurator().getChildObjectsURI(parentClass,\n\t\t\t\tparentKey, classs, new RequestParam(\"limit\", String.valueOf(objectsPerPage)));\n\n\t\tHttpGet http = new HttpGet(uri);\n\t\tString response = send(http);\n\t\tfinal JSONObject responseObject;\n\t\ttry {\n\t\t\tresponseObject = RedmineJSONParser.getResponse(response);\n\t\t\treturn JsonInput.getListNotNull(responseObject, config.multiObjectName, config.parser);\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineFormatException(\"Bad categories response \" + response, e);\n\t\t}\n\t}\n\n /**\n * Delivers a single child entry by its identifier.\n */\n public <T> T getChildEntry(Class<?> parentClass, String parentId,\n Class<T> classs, String childId, RequestParam... params) throws RedmineException {\n final EntityConfig<T> config = getConfig(classs);\n\t\tfinal URI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, classs, childId, params);\n HttpGet http = new HttpGet(uri);\n String response = send(http);\n\n return parseResponse(response, config.singleObjectName, config.parser);\n }\n\n /**\n\t * This number of objects (tasks, projects, users) will be requested from\n\t * Redmine server in 1 request.\n\t */\n\tpublic void setObjectsPerPage(int pageSize) {\n\t\tif (pageSize <= 0) {\n\t\t\tthrow new IllegalArgumentException(\"Page size must be >= 0. You provided: \" + pageSize);\n\t\t}\n\t\tthis.objectsPerPage = pageSize;\n\t}\n\t\n\tpublic void addUserToGroup(int userId, int groupId) throws RedmineException {\n\t\tlogger.debug(\"adding user \" + userId + \" to group \" + groupId + \"...\");\n\t\tURI uri = getURIConfigurator().getChildObjectsURI(Group.class, Integer.toString(groupId), User.class);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tfinal StringWriter writer = new StringWriter();\n\t\tfinal JSONWriter jsonWriter = new JSONWriter(writer);\n\t\ttry {\n\t\t\tjsonWriter.object().key(\"user_id\").value(userId).endObject();\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineInternalError(\"Unexpected exception\", e);\n\t\t}\n\t\tString body = writer.toString();\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t}\n\n\tpublic void addWatcherToIssue(int watcherId, int issueId) throws RedmineException {\n\t\tlogger.debug(\"adding watcher \" + watcherId + \" to issue \" + issueId + \"...\");\n\t\tURI uri = getURIConfigurator().getChildObjectsURI(Issue.class, Integer.toString(issueId), Watcher.class);\n\t\tHttpPost httpPost = new HttpPost(uri);\n\t\tfinal StringWriter writer = new StringWriter();\n\t\tfinal JSONWriter jsonWriter = new JSONWriter(writer);\n\t\ttry {\n\t\t\tjsonWriter.object().key(\"user_id\").value(watcherId).endObject();\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineInternalError(\"Unexpected exception\", e);\n\t\t}\n\t\tString body = writer.toString();\n\t\tsetEntity(httpPost, body);\n\t\tString response = send(httpPost);\n\t\tlogger.debug(response);\n\t}\n\n private String send(HttpRequestBase http) throws RedmineException {\n if (onBehalfOfUser != null) {\n http.addHeader(\"X-Redmine-Switch-User\", onBehalfOfUser);\n }\n return communicator.sendRequest(http);\n }\n\n\tprivate <T> T parseResponse(String response, String tag,\n JsonObjectParser<T> parser) throws RedmineFormatException {\n\t\ttry {\n\t\t\tT parse = parser.parse(RedmineJSONParser.getResponseSingleObject(response, tag));\n\t\t\tif (parse instanceof FluentStyle) {\n\t\t\t\t((FluentStyle) parse).setTransport(this);\n\t\t\t}\n\t\t\treturn parse;\n\t\t} catch (JSONException e) {\n\t\t\tthrow new RedmineFormatException(e);\n\t\t}\n\t}\n\n\tprivate static void setEntity(HttpEntityEnclosingRequest request, String body) {\n\t\tsetEntity(request, body, CONTENT_TYPE);\n\t}\n\n\tprivate static void setEntity(HttpEntityEnclosingRequest request, String body, String contentType) {\n\t\tStringEntity entity;\n\t\ttry {\n\t\t\tentity = new StringEntity(body, CHARSET);\n\t\t} catch (UnsupportedCharsetException e) {\n\t\t\tthrow new RedmineInternalError(\"Required charset \" + CHARSET\n\t\t\t\t\t+ \" is not supported\", e);\n\t\t}\n\t\tentity.setContentType(contentType);\n\t\trequest.setEntity(entity);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate <T> EntityConfig<T> getConfig(Class<?> class1) {\n\t\tfinal EntityConfig<?> guess = OBJECT_CONFIGS.get(class1);\n\t\tif (guess == null)\n\t\t\tthrow new RedmineInternalError(\"Unsupported class \" + class1);\n\t\treturn (EntityConfig<T>) guess;\n\t}\n\n\tprivate URIConfigurator getURIConfigurator() {\n\t\treturn configurator;\n\t}\n\n\tprivate static <T> EntityConfig<T> config(String objectField,\n\t\t\tString urlPrefix, JsonObjectWriter<T> writer,\n\t\t\tJsonObjectParser<T> parser) {\n\t\treturn new EntityConfig<>(objectField, urlPrefix, writer, parser);\n\t}\n\n /**\n * This works only when the main authentication has led to Redmine Admin level user.\n * The given user name will be sent to the server in \"X-Redmine-Switch-User\" HTTP Header\n * to indicate that the action (create issue, delete issue, etc) must be done\n * on behalf of the given user name.\n *\n * @param loginName Redmine user login name to provide to the server\n *\n * @see <a href=\"http://www.redmine.org/issues/11755\">Redmine issue 11755</a>\n */\n public void setOnBehalfOfUser(String loginName) {\n this.onBehalfOfUser = loginName;\n }\n\n\t/**\n\t * Entity config.\n\t */\n\tstatic class EntityConfig<T> {\n\t\tfinal String singleObjectName;\n\t\tfinal String multiObjectName;\n\t\tfinal JsonObjectWriter<T> writer;\n\t\tfinal JsonObjectParser<T> parser;\n\n\t\tpublic EntityConfig(String objectField, String urlPrefix,\n\t\t\t\tJsonObjectWriter<T> writer, JsonObjectParser<T> parser) {\n\t\t\tsuper();\n\t\t\tthis.singleObjectName = objectField;\n\t\t\tthis.multiObjectName = urlPrefix;\n\t\t\tthis.writer = writer;\n\t\t\tthis.parser = parser;\n\t\t}\n\t}\n\n}" ]
import com.taskadapter.redmineapi.Include; import com.taskadapter.redmineapi.NotFoundException; import com.taskadapter.redmineapi.RedmineAuthenticationException; import com.taskadapter.redmineapi.RedmineException; import com.taskadapter.redmineapi.internal.RequestParam; import com.taskadapter.redmineapi.internal.Transport; import java.util.*;
package com.taskadapter.redmineapi.bean; /** * Redmine's Issue. * <p> * Note that methods returning lists of elements (like getRelations(), getWatchers(), etc return * unmodifiable collections. * You need to use methods like addRelations() if you want to add elements, e.g.: * <pre> * issue.addRelations(Collections.singletonList(relation)); * </pre> * * @see <a href="http://www.redmine.org/projects/redmine/wiki/Rest_Issues">http://www.redmine.org/projects/redmine/wiki/Rest_Issues</a> */ public class Issue implements Identifiable, FluentStyle { private final PropertyStorage storage = new PropertyStorage(); public final static Property<Integer> DATABASE_ID = new Property<>(Integer.class, "id"); public final static Property<String> SUBJECT = new Property<>(String.class, "subject"); public final static Property<Date> START_DATE = new Property<>(Date.class, "startDate"); public final static Property<Date> DUE_DATE = new Property<>(Date.class, "dueDate"); public final static Property<Date> CREATED_ON = new Property<>(Date.class, "createdOn"); public final static Property<Date> UPDATED_ON = new Property<>(Date.class, "updatedOn"); public final static Property<Integer> DONE_RATIO = new Property<>(Integer.class, "doneRatio"); public final static Property<Integer> PARENT_ID = new Property<>(Integer.class, "parentId"); public final static Property<Integer> PRIORITY_ID = new Property<>(Integer.class, "priorityId"); public final static Property<Float> ESTIMATED_HOURS = new Property<>(Float.class, "estimatedHours"); public final static Property<Float> SPENT_HOURS = new Property<>(Float.class, "spentHours"); public final static Property<Integer> ASSIGNEE_ID = new Property<>(Integer.class, "assigneeId"); public final static Property<String> ASSIGNEE_NAME = new Property<>(String.class, "assigneeName"); /** * Some comment describing an issue update. */ public final static Property<String> NOTES = new Property<String>(String.class, "notes"); public final static Property<Boolean> PRIVATE_NOTES = new Property<>(Boolean.class, "notes"); public final static Property<String> PRIORITY_TEXT = new Property<>(String.class, "priorityText"); public final static Property<Integer> PROJECT_ID = new Property<>(Integer.class, "projectId"); public final static Property<String> PROJECT_NAME = new Property<>(String.class, "projectName"); public final static Property<Integer> AUTHOR_ID = new Property<>(Integer.class, "authorId"); public final static Property<String> AUTHOR_NAME = new Property<>(String.class, "authorName"); public final static Property<Tracker> TRACKER = new Property<>(Tracker.class, "tracker"); public final static Property<String> DESCRIPTION = new Property<>(String.class, "description"); public final static Property<Date> CLOSED_ON = new Property<>(Date.class, "closedOn"); public final static Property<Integer> STATUS_ID = new Property<>(Integer.class, "statusId"); public final static Property<String> STATUS_NAME = new Property<>(String.class, "statusName"); public final static Property<Version> TARGET_VERSION = new Property<>(Version.class, "targetVersion"); public final static Property<IssueCategory> ISSUE_CATEGORY = new Property<>(IssueCategory.class, "issueCategory"); public final static Property<Boolean> PRIVATE_ISSUE = new Property<>(Boolean.class, "privateIssue"); /** * can't have two custom fields with the same ID in the collection, that's why it is declared * as a Set, not a List. */ public final static Property<Set<CustomField>> CUSTOM_FIELDS = (Property<Set<CustomField>>) new Property(Set.class, "customFields"); public final static Property<Set<Journal>> JOURNALS = (Property<Set<Journal>>) new Property(Set.class, "journals"); public final static Property<Set<IssueRelation>> RELATIONS = (Property<Set<IssueRelation>>) new Property(Set.class, "relations"); public final static Property<Set<Attachment>> ATTACHMENTS = (Property<Set<Attachment>>) new Property(Set.class, "attachments"); public final static Property<Set<Changeset>> CHANGESETS = (Property<Set<Changeset>>) new Property(Set.class, "changesets"); public final static Property<Set<Watcher>> WATCHERS = (Property<Set<Watcher>>) new Property(Set.class, "watchers"); public final static Property<Set<Issue>> CHILDREN = (Property<Set<Issue>>) new Property(Set.class, "children");
private Transport transport;
5
tarzasai/Flucso
src/net/ggelardi/flucso/serv/FFService.java
[ "public class MainActivity extends BaseActivity implements OnFFReqsListener {\n\n\tprivate static final int REQ_SEARCH = 100;\n\tprivate static final int REQ_NEWPOST = 110;\n\t\n\tprivate String lastFeed;\n\tprivate DrawerAdapter adapter;\n\tprivate CharSequence mTitle;\n\tprivate CharSequence mDrawerTitle;\n\tprivate DrawerLayout mDrawerLayout;\n\tprivate View mDrawerView;\n\tprivate ListView mDrawerList;\n\tprivate ActionBarDrawerToggle mDrawerToggle;\n\tprivate LinearLayout mUserBox;\n\tprivate ImageView mUserIcon;\n\tprivate TextView mUserName;\n\tprivate TextView mUserLogin;\n\tprivate MenuItem miDrwUpd;\n\tprivate MenuItem miDrwCfg;\n\tprivate MenuItem miDrwAbo;\n\tprivate MenuItem miSearch;\n\tprivate MenuItem miConfig;\n\tprivate MenuItem miAboutD;\n\t\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.activity_main);\n\t\t\n\t\tif (session.cachedFeed != null)\n\t\t\tlastFeed = session.cachedFeed.id;\n\t\telse {\n\t\t\tlastFeed = session.getPrefs().getString(PK.STARTUP, \"home\");\n\t\t\tlastFeed = savedInstanceState != null ? savedInstanceState.getString(\"lastFeed\", lastFeed) : lastFeed;\n\t\t}\n\t\t\n\t\tadapter = new DrawerAdapter(this);\n\t\t\n\t\tmTitle = mDrawerTitle = getTitle();\n\t\t\n\t\tmDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);\n\t\tmDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);\n\t\t\n\t\tmDrawerView = findViewById(R.id.drawer_view);\n\t\t\n\t\tmDrawerList = (ListView) findViewById(R.id.lv_feed);\n\t\tmDrawerList.setAdapter(adapter);\n\t\tmDrawerList.setOnItemClickListener(new DrawerItemClickListener());\n\t\t\n\t\tmDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,\n\t\t\tR.string.drawer_close) {\n\t\t\t@Override\n\t\t\tpublic void onDrawerClosed(View view) {\n\t\t\t\tgetActionBar().setTitle(mTitle);\n\t\t\t\tinvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void onDrawerOpened(View drawerView) {\n\t\t\t\tgetActionBar().setTitle(mDrawerTitle);\n\t\t\t\tinvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()\n\t\t\t}\n\t\t};\n\t\t\n\t\tmDrawerLayout.setDrawerListener(mDrawerToggle);\n\t\t\n\t\tmUserBox = (LinearLayout) findViewById(R.id.user_box);\n\t\tmUserIcon = (ImageView) findViewById(R.id.user_icon);\n\t\tmUserName = (TextView) findViewById(R.id.user_name);\n\t\tmUserLogin = (TextView) findViewById(R.id.user_login);\n\t\t\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\t\n\t\t// Commons.picasso(getApplicationContext()).setIndicatorsEnabled(true);\n\t\t\n\t\tIntent intent = getIntent();\n\t\tif (!intent.getAction().equals(Intent.ACTION_MAIN))\n\t\t\tonNewIntent(intent);\n\t}\n\t\n\t@Override\n\tprotected void onResume() {\n\t\tsuper.onResume();\n\t\t\n\t\tif (!session.hasAccount()) {\n\t\t\tmUserIcon.setImageResource(R.drawable.nomugshot);\n\t\t\tmUserName.setText(R.string.noaccount_name);\n\t\t\tmUserLogin.setText(R.string.noaccount_login);\n\t\t\tmUserBox.setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tv.getContext().startActivity(new Intent(MainActivity.this, SettingsActivity.class));\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (!session.hasProfile()) {\n\t\t\tmUserLogin.setText(session.getUsername());\n\t\t\tmUserName.setText(R.string.waiting_profile);\n\t\t\tmUserBox.setOnClickListener(new View.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tSectionItem me = new SectionItem();\n\t\t\t\t\tme.id = \"me\";\n\t\t\t\t\tselectDrawerItem(me);\n\t\t\t\t\tmDrawerLayout.closeDrawer(mDrawerView);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onPause() {\n\t\tsuper.onPause();\n\t}\n\t\n\t@Override\n\tprotected void onRestoreInstanceState(Bundle savedInstanceState) {\n\t\tsuper.onRestoreInstanceState(savedInstanceState);\n\t\t\n\t\tlastFeed = savedInstanceState.getString(\"lastFeed\", session.getPrefs().getString(PK.STARTUP, \"home\"));\n\t}\n\t\n\t@Override\n\tprotected void onSaveInstanceState(Bundle outState) {\n\t\tsuper.onSaveInstanceState(outState);\n\t\t\n\t\toutState.putString(\"lastFeed\", lastFeed);\n\t}\n\t\n\t@Override\n\tpublic void setTitle(CharSequence title) {\n\t\tmTitle = title;\n\t\tgetActionBar().setTitle(mTitle);\n\t}\n\t\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mDrawerLayout.isDrawerVisible(mDrawerView))\n\t\t\tmDrawerLayout.closeDrawer(mDrawerView);\n\t\telse\n\t\t\tsuper.onBackPressed();\n\t}\n\t\n\t@Override\n\tprotected void onPostCreate(Bundle savedInstanceState) {\n\t\tsuper.onPostCreate(savedInstanceState);\n\t\t// Sync the toggle state after onRestoreInstanceState has occurred.\n\t\tmDrawerToggle.syncState();\n\t}\n\t\n\t@Override\n\tpublic void onConfigurationChanged(Configuration newConfig) {\n\t\tsuper.onConfigurationChanged(newConfig);\n\t\t// Pass any configuration change to the drawer toggles\n\t\tmDrawerToggle.onConfigurationChanged(newConfig);\n\t}\n\t\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.main, menu);\n\n\t\tmiDrwUpd = menu.findItem(R.id.drawer_refresh);\n\t\tmiDrwCfg = menu.findItem(R.id.drawer_settings);\n\t\tmiDrwAbo = menu.findItem(R.id.drawer_about);\n\t\tmiSearch = menu.findItem(R.id.action_search);\n\t\tmiConfig = menu.findItem(R.id.action_settings);\n\t\tmiAboutD = menu.findItem(R.id.action_about);\n\t\t\n\t\tmiDrwUpd.setVisible(false);\n\t\tmiDrwCfg.setVisible(false);\n\t\t\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic boolean onPrepareOptionsMenu(Menu menu) {\n\t\tmiDrwUpd.setVisible(mDrawerLayout.isDrawerVisible(mDrawerView) && session.hasProfile());\n\t\tmiDrwCfg.setVisible(mDrawerLayout.isDrawerVisible(mDrawerView));\n\t\tmiDrwAbo.setVisible(mDrawerLayout.isDrawerVisible(mDrawerView));\n\t\tmiSearch.setVisible(session.hasProfile());\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\t// The action bar home/up action should open or close the drawer.\n\t\t// ActionBarDrawerToggle will take care of this.\n\t\tif (mDrawerToggle.onOptionsItemSelected(item))\n\t\t\treturn true;\n\t\tif (item.equals(miDrwUpd)) {\n\t\t\tupdateProfile();\n\t\t\tupdateNavigation();\n\t\t\treturn true;\n\t\t}\n\t\tif (item.equals(miDrwCfg) || item.equals(miConfig)) {\n\t\t\tstartActivity(new Intent(this, SettingsActivity.class));\n\t\t\treturn true;\n\t\t}\n\t\tif (item.equals(miDrwAbo) || item.equals(miAboutD)) {\n\t\t\tAboutBox.Show(MainActivity.this);\n\t\t\treturn true;\n\t\t}\n\t\tif (item.equals(miSearch)) {\n\t\t\tstartActivityForResult(new Intent(this, SearchActivity.class), REQ_SEARCH);\n\t\t\treturn true;\n\t\t}\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\t\n\t@Override\n\tprotected void onNewIntent(Intent intent) {\n\t\tString act = intent.getAction();\n\t\tLog.v(logTag(), \"onNewIntent(): \" + act);\n\t\tif (act.equals(FFService.DM_BASE_NOTIF)) {\n\t\t\tString fid = \"filter/direct\";\n\t\t\tSectionItem si = session.hasProfile() ? session.getNavigation().getSectionByFeed(fid) : null;\n\t\t\tif (si == null) {\n\t\t\t\tsi = new SectionItem();\n\t\t\t\tsi.id = fid;\n\t\t\t\tsi.type = \"special\";\n\t\t\t\tsi.name = \"Direct Messages\";\n\t\t\t}\n\t\t\tif (getFragmentManager().findFragmentByTag(FeedFragment.FRAGMENT_TAG) == null)\n\t\t\t\tselectDrawerItem(si);\n\t\t\telse\n\t\t\t\topenFeed(si.name, fid, null);\n\t\t\tNotificationManager nmg = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n\t\t\tnmg.cancel(FFService.NOTIFICATION_ID); // remove from notification bar\n\t\t} else if (act.equals(Intent.ACTION_VIEW)) {\n\t\t\tUri data = intent.getData();\n\t\t\tif (data.getHost().equals(\"ff.im\")) {\n\t\t\t\treverseShort(data.getPath().substring(1));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (data.getHost().equals(\"friendfeed.com\") && data.getPath().startsWith(\"/search\")) {\n\t\t\t\topenFeed(\"search\", \"search\", data.getQuery().substring(2));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tToast.makeText(this, \"Unhandled intent (data: \\\"\" + data.toString() + \"\\\")\", Toast.LENGTH_LONG).show();\n\t\t}\n\t}\n\t\n\t@Override\n\tprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\t\tif (requestCode == REQ_SEARCH && resultCode == RESULT_OK) {\n\t\t\tif (data.hasExtra(\"query\"))\n\t\t\t\topenFeed(\"search\", \"search\", data.getStringExtra(\"query\"));\n\t\t\telse if (data.hasExtra(\"feed\"))\n\t\t\t\topenFeed(data.getStringExtra(\"name\"), data.getStringExtra(\"feed\"), null);\n\t\t} else if (requestCode == REQ_NEWPOST && resultCode == RESULT_OK)\n\t\t\topenEntry(data.getStringExtra(\"eid\"));\n\t}\n\t\n\t@Override\n\tpublic void openInfo(String feed_id) {\n\t\tToast.makeText(this, \"openInfo: \" + feed_id, Toast.LENGTH_LONG).show();\n\t}\n\t\n\t@Override\n\tpublic void openFeed(String name, String feed_id, String query) {\n\t\tlastFeed = feed_id;\n\t\tFragmentManager fm = getFragmentManager();\n\t\tfm.beginTransaction().replace(R.id.content_frame, FeedFragment.newInstance(name, feed_id, query),\n\t\t\tFeedFragment.FRAGMENT_TAG).addToBackStack(null).commit();\n\t}\n\t\n\t@Override\n\tpublic void openEntry(String entry_id) {\n\t\tgetFragmentManager().beginTransaction().replace(R.id.content_frame, EntryFragment.newInstance(entry_id),\n\t\t\tEntryFragment.FRAGMENT_TAG).addToBackStack(null).commit();\n\t}\n\t\n\t@Override\n\tpublic void openGallery(String entry_id, int position) {\n\t\tgetFragmentManager().beginTransaction().replace(R.id.content_frame,\n\t\t\tGalleryFragment.newInstance(entry_id, position), GalleryFragment.FRAGMENT_TAG).addToBackStack(null).commit();\n\t}\n\t\n\t@Override\n\tpublic void openPostNew(String[] dsts, String body, String link, String[] tmbs) {\n\t\tIntent intent = new Intent(this, PostActivity.class);\n\t\tintent.setAction(Intent.ACTION_INSERT);\n\t\tBundle prms = new Bundle();\n\t\tprms.putStringArray(\"dsts\", dsts);\n\t\tif (!TextUtils.isEmpty(body))\n\t\t\tprms.putString(\"body\", body);\n\t\tprms.putString(\"link\", link);\n\t\tprms.putStringArray(\"tmbs\", tmbs);\n\t\tintent.putExtras(prms);\n\t\tstartActivityForResult(intent, REQ_NEWPOST);\n\t}\n\t\n\t@Override\n\tpublic void openPostEdit(String entry_id, String body) {\n\t\tIntent intent = new Intent(this, PostActivity.class);\n\t\tintent.setAction(Intent.ACTION_EDIT);\n\t\tBundle prms = new Bundle();\n\t\tprms.putString(\"eid\", entry_id);\n\t\tprms.putString(\"body\", body);\n\t\tintent.putExtras(prms);\n\t\tstartActivity(intent);\n\t}\n\t\n\t@Override\n\tprotected void profileReady() {\n\t\tCommons.picasso(getApplicationContext()).load(session.getProfile().getAvatarUrl()).placeholder(\n\t\t\tR.drawable.nomugshot).into(mUserIcon);\n\t\tmUserLogin.setText(session.getUsername());\n\t\tmUserName.setText(session.getProfile().name);\n\t\tmUserBox.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tSectionItem me = new SectionItem();\n\t\t\t\tme.id = \"me\";\n\t\t\t\tme.name = session.getProfile().name;\n\t\t\t\tselectDrawerItem(me);\n\t\t\t\tmDrawerLayout.closeDrawer(mDrawerView);\n\t\t\t}\n\t\t});\n\t\tif (getFragmentManager().findFragmentByTag(FeedFragment.FRAGMENT_TAG) == null) {\n\t\t\t// Open the startup feed.\n\t\t\tSectionItem si = session.getNavigation().getSectionByFeed(lastFeed);\n\t\t\tselectDrawerItem(si != null ? si : session.getNavigation().sections[0].feeds[0]);\n\t\t}\n\t}\n\t\n\tprivate void updateProfile() {\n\t\tsetProgressBarIndeterminateVisibility(true);\n\t\tCallback<FeedInfo> callback = new Callback<FeedInfo>() {\n\t\t\t@Override\n\t\t\tpublic void success(FeedInfo result, Response response) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tsession.setProfile(result);\n\t\t\t\tprofileReady();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tnew AlertDialog.Builder(MainActivity.this).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(\n\t\t\t\t\tR.string.dlg_btn_retry, new OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\tupdateProfile();\n\t\t\t\t\t\t}\n\t\t\t\t\t}).setCancelable(true).create().show();\n\t\t\t}\n\t\t};\n\t\tFFAPI.client_profile(session).get_profile(\"me\", callback);\n\t}\n\t\n\tprivate void updateNavigation() {\n\t\tsetProgressBarIndeterminateVisibility(true);\n\t\tCallback<FeedList> callback = new Callback<FeedList>() {\n\t\t\t@Override\n\t\t\tpublic void success(FeedList result, Response response) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tsession.setNavigation(result);\n\t\t\t\tadapter.notifyDataSetChanged();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tnew AlertDialog.Builder(MainActivity.this).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(\n\t\t\t\t\tR.string.dlg_btn_retry, new OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\tupdateNavigation();\n\t\t\t\t\t\t}\n\t\t\t\t\t}).setCancelable(true).create().show();\n\t\t\t}\n\t\t};\n\t\tFFAPI.client_profile(session).get_navigation(callback);\n\t}\n\t\n\tprivate void reverseShort(String shcode) {\n\t\tsetProgressBarIndeterminateVisibility(true);\n\t\tCallback<Entry> callback = new Callback<Entry>() {\n\t\t\t@Override\n\t\t\tpublic void success(Entry result, Response response) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tsession.cachedEntry = result;\n\t\t\t\topenEntry(result.id);\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tnew AlertDialog.Builder(MainActivity.this).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).show();\n\t\t\t}\n\t\t};\n\t\tFFAPI.client_entry(session).rev_short(shcode, callback);\n\t}\n\t\n\tprivate void selectDrawerItem(SectionItem selection) {\n\t\tFragmentManager fm = getFragmentManager();\n\t\t// Always clear the fragments stack when we open a feed from the menu.\n\t\tif (fm.getBackStackEntryCount() > 0)\n\t\t\tfm.popBackStack(fm.getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\t\t// Check if the current fragment (if any) is on the same feed we want to open.\n\t\tFragment chk = fm.findFragmentByTag(FeedFragment.FRAGMENT_TAG);\n\t\tif (chk != null && ((FeedFragment) chk).fid.equals(selection.id))\n\t\t\treturn;\n\t\t// Open new feed fragment.\n\t\tlastFeed = selection.id;\n\t\tfm.beginTransaction().replace(R.id.content_frame, FeedFragment.newInstance(selection.name, lastFeed, selection.query),\n\t\t\tFeedFragment.FRAGMENT_TAG).commit(); // no backstack\n\t}\n\t\n\t/*\n\tpublic void subscribe(final String feed_id, final String list_id) {\n\t\tsetProgressBarIndeterminateVisibility(true);\n\t\tCallback<SimpleResponse> callback = new Callback<SimpleResponse>() {\n\t\t\t@Override\n\t\t\tpublic void success(SimpleResponse result, Response response) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tToast.makeText(MainActivity.this, result.status, Toast.LENGTH_LONG).show();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tnew AlertDialog.Builder(MainActivity.this).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(\n\t\t\t\t\tR.string.dlg_btn_retry, new DialogInterface.OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\tsubscribe(feed_id, list_id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}).setCancelable(true).create().show();\n\t\t\t}\n\t\t};\n\t\tFFAPI.client_write(session).subscribe(feed_id, list_id, callback);\n\t}\n\t\n\tpublic void unsubscribe(final String feed_id, final String list_id) {\n\t\tsetProgressBarIndeterminateVisibility(true);\n\t\tCallback<SimpleResponse> callback = new Callback<SimpleResponse>() {\n\t\t\t@Override\n\t\t\tpublic void success(SimpleResponse result, Response response) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tToast.makeText(MainActivity.this,\n\t\t\t\t\t!TextUtils.isEmpty(result.status) ? result.status : result.success ? \"ok\" : \"wtf?\",\n\t\t\t\t\tToast.LENGTH_LONG).show();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\tsetProgressBarIndeterminateVisibility(false);\n\t\t\t\tnew AlertDialog.Builder(MainActivity.this).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(\n\t\t\t\t\tR.string.dlg_btn_retry, new DialogInterface.OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\tunsubscribe(feed_id, list_id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}).setCancelable(true).create().show();\n\t\t\t}\n\t\t};\n\t\tFFAPI.client_write(session).unsubscribe(feed_id, list_id, callback);\n\t}\n\t*/\n\t\n\tprivate class DrawerItemClickListener implements ListView.OnItemClickListener {\n\t\t@Override\n\t\tpublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n\t\t\tselectDrawerItem((SectionItem) adapter.getItem(position));\n\t\t\tmDrawerList.setItemChecked(position, true);\n\t\t\tmDrawerLayout.closeDrawer(mDrawerView);\n\t\t}\n\t}\n}", "public static class PK {\n\tpublic static final String USERNAME = \"Username\";\n\tpublic static final String REMOTEKEY = \"RemoteKey\";\n\tpublic static final String STARTUP = \"pk_startup\";\n\tpublic static final String LOCALE = \"pk_locale\";\n\tpublic static final String PROXY_USED = \"pk_proxy_active\";\n\tpublic static final String PROXY_HOST = \"pk_proxy_host\";\n\tpublic static final String PROXY_PORT = \"pk_proxy_port\";\n\tpublic static final String PROF_INFO = \"pk_prof_info\";\n\tpublic static final String PROF_LIST = \"pk_prof_list\";\n\tpublic static final String FEED_UPD = \"pk_feed_upd\";\n\tpublic static final String FEED_FOF = \"pk_feed_fof\";\n\tpublic static final String FEED_HID = \"pk_feed_hid\";\n\tpublic static final String FEED_ELC = \"pk_feed_elc\";\n\tpublic static final String FEED_HBK = \"pk_feed_hbk\";\n\tpublic static final String FEED_HBF = \"pk_feed_hbf\";\n\tpublic static final String FEED_SPO = \"pk_feed_spo\";\n\tpublic static final String ENTR_IMCO = \"pk_entry_imco\";\n\tpublic static final String SERV_PROF = \"pk_serv_prof\";\n\tpublic static final String SERV_NOTF = \"pk_serv_notf\";\n\tpublic static final String SERV_MSGS = \"pk_serv_msgs\";\n\tpublic static final String SERV_MSGS_TIME = \"pk_serv_msgs_time\";\n\tpublic static final String SERV_MSGS_CURS = \"pk_serv_msgs_cursor\";\n}", "public static class Comment extends BaseEntry {\n\t// compact view only (plus body):\n\tpublic Boolean placeholder = false;\n\tpublic int num;\n\t\t\n\t@Override\n\tpublic void checkLocalHide() {\n\t\tif (placeholder)\n\t\t\treturn;\n\t\tsuper.checkLocalHide();\n\t\tif (body.toLowerCase(Locale.getDefault()).equals(\"sp\") ||\n\t\t\tbody.toLowerCase(Locale.getDefault()).equals(\"spoiler\") ||\n\t\t\trawBody.toLowerCase(Locale.getDefault()).equals(\"sp\") ||\n\t\t\trawBody.toLowerCase(Locale.getDefault()).equals(\"spoiler\"))\n\t\t\tspoiler = true;\n\t}\n}", "public static class Entry extends BaseEntry {\n\tpublic String rawLink;\n\tpublic String url;\n\tpublic List<Comment> comments = new ArrayList<Comment>();\n\tpublic List<Like> likes = new ArrayList<Like>();\n\tpublic BaseFeed[] to = new BaseFeed[] {};\n\tpublic Thumbnail[] thumbnails = new Thumbnail[] {};\n\tpublic Fof fof;\n\tpublic String fofHtml;\n\tpublic String shortId = \"\";\n\tpublic String shortUrl = \"\";\n\tpublic Attachment[] files = new Attachment[] {};\n\tpublic Coordinates geo;\n\tpublic boolean hidden = false; // undocumented\n\tpublic int thumbpos = 0; // local\n\t\t\n\t@Override\n\tpublic void update(BaseEntry item) {\n\t\tsuper.update(item);\n\t\t\t\n\t\tif (!isIt(item.id))\n\t\t\treturn;\n\t\t\t\n\t\tEntry entry = (Entry) item;\n\n\t\turl = entry.url;\n\t\tfof = entry.fof;\n\t\thidden = entry.hidden;\n\t\trawLink = entry.rawLink;\n\t\tfofHtml = entry.fofHtml;\n\t\tthumbnails = entry.thumbnails;\n\t\tfiles = entry.files;\n\t\tgeo = entry.geo;\n\n\t\tfor (Comment comm : entry.comments)\n\t\t\tif (comm.created)\n\t\t\t\tcomments.add(comm);\n\t\t\telse\n\t\t\t\tfor (Comment old : comments)\n\t\t\t\t\tif (old.isIt(comm.id)) {\n\t\t\t\t\t\told.update(comm);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\n\t\tfor (Like like : entry.likes)\n\t\t\tif (like.created)\n\t\t\t\tlikes.add(like);\n\t\t\t\n\t\tupdated = true;\n\t}\n\t\t\n\t@Override\n\tpublic void checkLocalHide() {\n\t\tsuper.checkLocalHide();\n\t\t\t\n\t\tif (canUnlike()) {\n\t\t\tbanned = false;\n\t\t\tspoiler = false;\n\t\t} else\n\t\t\tfor (BaseFeed bf: to)\n\t\t\t\tif (Commons.bFeeds.contains(bf.id)) {\n\t\t\t\t\tbanned = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\tfor (Comment c: comments)\n\t\t\tc.checkLocalHide();\n\t}\n\t\t\n\tpublic boolean isDM() {\n\t\tif (to.length <= 0)\n\t\t\treturn false;\n\t\tfor (BaseFeed f: to)\n\t\t\tif (!f.isUser() || f.isIt(from.id))\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\t\t\n\tpublic boolean canComment() {\n\t\treturn commands.contains(\"comment\");\n\t}\n\t\t\n\tpublic boolean canLike() {\n\t\treturn commands.contains(\"like\");\n\t}\n\t\t\n\tpublic boolean canUnlike() {\n\t\treturn commands.contains(\"unlike\") || hidden;\n\t}\n\t\t\n\tpublic boolean canHide() {\n\t\treturn commands.contains(\"hide\");// || !hidden;\n\t}\n\t\t\n\tpublic boolean canUnhide() {\n\t\treturn commands.contains(\"unhide\");\n\t}\n\t\t\n\tpublic String getToLine() {\n\t\tif (to.length <= 0 || to.length == 1 && (to[0].id.equals(from.id) || to[0].id.equals(id)))\n\t\t\treturn null;\n\t\tList<String> lst = new ArrayList<String>();\n\t\tfor (BaseFeed f : to)\n\t\t\tlst.add(f.isMe() ? IdentItem.accountFeed : f.getName());\n\t\treturn TextUtils.join(\", \", lst);\n\t}\n\t\t\n\tpublic String[] getFofIDs() {\n\t\tif (fof == null || TextUtils.isEmpty(fofHtml))\n\t\t\treturn null;\n\t\tPattern p = Pattern.compile(\"friendfeed\\\\.com/((\\\\d|\\\\w)+)\");\n\t\tMatcher m = p.matcher(fofHtml);\n\t\tString f1 = null;\n\t\tString f2 = null;\n\t\tif (m.find()) {\n\t\t\tf1 = m.group(1);\n\t\t\tif (m.find())\n\t\t\t\tf2 = m.group(1);\n\t\t}\n\t\tif (f2 != null)\n\t\t\treturn new String[] { f1, f2 };\n\t\tif (f1 != null)\n\t\t\treturn new String[] { f1 };\n\t\treturn null;\n\t}\n\t\t\n\tpublic int getFilesCount() {\n\t\treturn files.length + thumbnails.length;\n\t}\n\t\t\n\tpublic int getLikesCount() {\n\t\tif (likes == null)\n\t\t\treturn 0;\n\t\tfor (Like l : likes)\n\t\t\tif (l.placeholder != null && l.placeholder)\n\t\t\t\treturn l.num + likes.size() - 1;\n\t\treturn likes.size();\n\t}\n\t\t\n\tpublic int getCommentsCount() {\n\t\tif (comments == null)\n\t\t\treturn 0;\n\t\tfor (Comment c : comments)\n\t\t\tif (c.placeholder != null && c.placeholder)\n\t\t\t\treturn c.num + comments.size() - 1;\n\t\treturn comments.size();\n\t}\n\t\t\n\tpublic String[] getMediaUrls(boolean attachments) {\n\t\tString[] res = new String[attachments ? thumbnails.length + files.length : thumbnails.length];\n\t\tfor (int i = 0; i < thumbnails.length; i++)\n\t\t\tres[i] = thumbnails[i].link;\n\t\tif (attachments)\n\t\t\tfor (int i = 0; i < thumbnails.length; i++)\n\t\t\t\tres[thumbnails.length + i] = files[i].url;\n\t\treturn res;\n\t}\n\t\t\n\tpublic int indexOfComment(String cid) {\n\t\tComment c;\n\t\tfor (int i = 0; i < comments.size(); i++) {\n\t\t\tc = comments.get(i);\n\t\t\tif (!c.placeholder && c.id.equals(cid))\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t}\n\t\t\n\tpublic int indexOfLike(String userId) {\n\t\tLike l;\n\t\tfor (int i = 0; i < likes.size(); i++) {\n\t\t\tl = likes.get(i);\n\t\t\tif (!l.placeholder && l.from.id.equals(userId))\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t}\n\t\t\n\tpublic boolean hasSpoilers() {\n\t\tfor (Comment c: comments)\n\t\t\tif (c.spoiler)\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\t\n\tpublic boolean hasReplies() {\n\t\tfor (Comment c: comments)\n\t\t\tif ((c.created || c.updated) && !c.from.isMe())\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\t\n\tpublic void thumbNext() {\n\t\tthumbpos = thumbnails.length > 0 ? (thumbpos + 1) % thumbnails.length : 0;\n\t}\n\t\t\n\tpublic void thumbPrior() {\n\t\tthumbpos = thumbnails.length > 0 ? (thumbpos + (thumbnails.length - 1)) % thumbnails.length : 0;\n\t}\n\t\t\n\tpublic static class Fof {\n\t\tpublic String type;\n\t\tpublic BaseFeed from;\n\t}\n\t\t\n\tpublic static class Thumbnail {\n\t\tpublic String url = \"\";\n\t\tpublic String link = \"\";\n\t\tpublic int width = 0;\n\t\tpublic int height = 0;\n\t\tpublic String player = \"\";\n\t\tpublic int rotation = 0; // local\n\t\tpublic boolean landscape = true; // local\n\t\tpublic String videoId = null; // local\n\t\tpublic String videoUrl = null; // local\n\t\t\t\n\t\tpublic boolean isFFMediaPic() {\n\t\t\treturn link.indexOf(\"/m.friendfeed-media.com/\") > 0;\n\t\t}\n\t\t\t\n\t\tpublic boolean isSimplePic() {\n\t\t\treturn link.endsWith(\".jpg\") || link.endsWith(\".jpeg\") || link.endsWith(\".png\") || link.endsWith(\".gif\");\n\t\t}\n\t\t\t\n\t\tpublic boolean isYouTube() {\n\t\t\tif (TextUtils.isEmpty(player))\n\t\t\t\treturn false;\n\t\t\tif (!(TextUtils.isEmpty(videoId) || TextUtils.isEmpty(videoUrl)))\n\t\t\t\treturn true;\n\t\t\tDocument doc = Jsoup.parseBodyFragment(player);\n\t\t\tElements emb = doc.getElementsByTag(\"embed\");\n\t\t\tif (emb != null && emb.size() > 0 && emb.get(0).hasAttr(\"src\")) {\n\t\t\t\tString src = emb.get(0).attr(\"src\");\n\t\t\t\tif (Commons.YouTube.isVideoUrl(src)) {\n\t\t\t\t\tvideoId = Commons.YouTube.getId(src);\n\t\t\t\t\tvideoUrl = Commons.YouTube.getFriendlyUrl(src);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\t\n\t\tpublic String videoPreview() {\n\t\t\treturn isYouTube() ? Commons.YouTube.getPreview(videoUrl) : null;\n\t\t}\n\t}\n\t\t\n\tpublic static class Attachment {\n\t\tpublic String url;\n\t\tpublic String type;\n\t\tpublic String name;\n\t\tpublic String icon;\n\t\tpublic int size = 0;\n\t}\n\t\t\n\tpublic static class Coordinates {\n\t\tpublic String lat;\n\t\t\t\n\t\t@SerializedName(\"long\")\n\t\tpublic String lon;\n\t}\n}", "public static class Feed extends BaseFeed {\n\tpublic List<Entry> entries = new ArrayList<Entry>();\n\tpublic Realtime realtime;\n\t\t\n\tpublic static String lastDeletedEntry = \"\";\n\t\t\n\tpublic int indexOf(String eid) {\n\t\tfor (int i = 0; i < entries.size(); i++)\n\t\t\tif (entries.get(i).isIt(eid))\n\t\t\t\treturn i;\n\t\treturn -1;\n\t}\n\t\t\n\tpublic Entry find(String eid) {\n\t\tfor (Entry e : entries)\n\t\t\tif (e.id.equals(eid))\n\t\t\t\treturn e;\n\t\treturn null;\n\t}\n\t\t\n\tpublic int append(Feed feed) {\n\t\tint res = 0;\n\t\tfor (Entry e : feed.entries)\n\t\t\tif (find(e.id) == null) {\n\t\t\t\tentries.add(e);\n\t\t\t\te.checkLocalHide();\n\t\t\t\tres++;\n\t\t\t}\n\t\treturn res;\n\t}\n\t\t\n\tpublic int update(Feed feed, boolean sortLikeSite) {\n\t\trealtime = feed.realtime;\n\t\ttimestamp = feed.timestamp;\n\t\tint res = 0;\n\t\tfor (Entry e : feed.entries)\n\t\t\tif (e.created) {\n\t\t\t\tentries.add(0, e);\n\t\t\t\te.checkLocalHide();\n\t\t\t\tres++;\n\t\t\t} else\n\t\t\t\tfor (Entry old : entries)\n\t\t\t\t\tif (old.isIt(e.id)) {\n\t\t\t\t\t\told.update(e);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\tif (!TextUtils.isEmpty(lastDeletedEntry))\n\t\t\tfor (int n = 0; n < entries.size(); n++)\n\t\t\t\tif (entries.get(n).id.equals(lastDeletedEntry)) {\n\t\t\t\t\tentries.remove(n);\n\t\t\t\t\tlastDeletedEntry = \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\tif (sortLikeSite && res > 0) {\n\t\t\tCollections.sort(entries, new Comparator<BaseEntry>() {\n\t\t\t @Override\n\t\t\t public int compare(BaseEntry o1, BaseEntry o2) {\n\t\t\t return o1.date.compareTo(o2.date) * -1;\n\t\t\t }\n\t\t\t});\n\t\t}\n\t\treturn res;\n\t}\n\t\t\n\tpublic int update(Feed feed) {\n\t\treturn update(feed, false);\n\t}\n\t\t\n\tpublic void checkLocalHide() {\n\t\tfor (Entry e : entries)\n\t\t\te.checkLocalHide();\n\t}\n\t\t\n\tpublic static class Realtime {\n\t\tpublic String cursor;\n\t\tpublic final long timestamp = System.currentTimeMillis();\n\t}\n}", "public static class Realtime {\n\tpublic String cursor;\n\tpublic final long timestamp = System.currentTimeMillis();\n}" ]
import net.ggelardi.flucso.MainActivity; import net.ggelardi.flucso.R; import net.ggelardi.flucso.serv.Commons.PK; import net.ggelardi.flucso.serv.FFAPI.Comment; import net.ggelardi.flucso.serv.FFAPI.Entry; import net.ggelardi.flucso.serv.FFAPI.Feed; import net.ggelardi.flucso.serv.FFAPI.Feed.Realtime; import retrofit.RetrofitError; import android.annotation.TargetApi; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Build; import android.os.PowerManager; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.util.Log;
try { while (!terminated) { if (isLollipopPSorSO()) waitTime = 60000; else if (!session.hasAccount()) waitTime = 2000; else if (!checkProfile()) terminated = true; else { checkMessages(); checkFeedCache(); waitTime = 50000; } Thread.sleep(waitTime); } } catch (Exception e) { terminated = true; notifyError(e); } finally { stopSelf(); } } @Override public void onDestroy() { Log.v("FFService", "onDestroy()"); session.getPrefs().unregisterOnSharedPreferenceChangeListener(this); super.onDestroy(); } private void notifyError(Throwable error) { String text; try { text = error instanceof RetrofitError ? Commons.retrofitErrorText((RetrofitError) error) : error.getMessage(); } catch (Exception err) { text = "Unknown error"; } notifier.sendBroadcast(new Intent().setAction(SERVICE_ERROR).putExtra("message", text)); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean isLollipopPSorSO() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return false; PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); return pm.isPowerSaveMode() || !pm.isInteractive(); } private boolean checkProfile() { if (session.hasProfile() && session.getProfile().getAge() <= printv * 60000) return true; Log.v("FFService", "checkProfile()"); session.setProfile(FFAPI.client_profile(session).get_profile_sync("me")); session.setNavigation(FFAPI.client_profile(session).get_navigation_sync()); notifier.sendBroadcast(new Intent(PROFILE_READY)); return true; } private void checkMessages() { if (dmnotf == 0) return; long chk = dmlast != null ? dmlast.timestamp : session.getPrefs().getLong(PK.SERV_MSGS_TIME, 0); if (chk > 0 && System.currentTimeMillis() - chk <= dmintv * 60000) return; Log.v("FFService", "checkMessages()"); String cursor = dmlast != null ? dmlast.cursor : session.getPrefs().getString(PK.SERV_MSGS_CURS, ""); Feed data = FFAPI.client_msgs(session).get_feed_updates("filter/direct", 50, cursor, 0, 1); dmlast = data.realtime; // save the token SharedPreferences.Editor editor = session.getPrefs().edit(); editor.putString(PK.SERV_MSGS_CURS, dmlast.cursor); editor.putLong(PK.SERV_MSGS_TIME, System.currentTimeMillis()); editor.commit(); // check for updates boolean news = false; boolean upds = false; for (Entry e : data.entries) { if (news) break; if (e.from.isMe()) { if (!upds && replied(e)) upds = true; } else if (dmnotf == 2 || (e.to.length == 1 && e.to[0].isMe())) { if (e.created) news = true; else if (!upds && (e.updated || replied(e))) upds = true; } } if (news || upds) { PendingIntent rpi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class).setAction(DM_BASE_NOTIF), PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder ncb = new NotificationCompat.Builder(this).setSmallIcon( R.drawable.ic_launcher).setContentTitle(getResources().getString(R.string.app_name)).setContentText( getResources().getString(news ? R.string.notif_dm_new : R.string.notif_dm_upd)).setContentIntent(rpi); NotificationManager nmg = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nmg.notify(NOTIFICATION_ID, ncb.build()); } } private void checkFeedCache() { if (!Commons.isOnWIFI(this) || (session.cachedFeed != null && session.cachedFeed.getAge() < 10*60*1000)) return; Log.v("FFService", "checkFeedCache()"); String fid = session.cachedFeed != null ? session.cachedFeed.id : session.getPrefs().getString(PK.STARTUP, "home"); String cur = session.cachedFeed != null && session.cachedFeed.realtime != null ? session.cachedFeed.realtime.cursor : ""; if (cur == "") { session.cachedFeed = FFAPI.client_feed(session).get_feed_normal(fid, 0, 20); session.cachedFeed.realtime = FFAPI.client_feed(session).get_feed_updates(fid, 20, "", 0, 1).realtime; } else { session.cachedFeed.update(FFAPI.client_feed(session).get_feed_updates(fid, session.cachedFeed.entries.size(), session.cachedFeed.realtime.cursor, 0, 1), true); } } private static boolean replied(Entry e) {
for (Comment c: e.comments)
2
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/speakers/list/SpeakersListFragment.java
[ "@DebugLog\npublic class DroidconApp extends Application {\n\n private AppComponent component;\n\n public static DroidconApp get(Context context) {\n return (DroidconApp) context.getApplicationContext();\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n AndroidThreeTen.init(this);\n initGraph();\n initLogger();\n }\n\n public AppComponent component() {\n return component;\n }\n\n private void initGraph() {\n component = AppComponent.Initializer.init(this);\n }\n\n private void initLogger() {\n Timber.plant(new Timber.DebugTree());\n }\n}", "@Singleton\npublic class DataProvider {\n\n private final AppMapper appMapper;\n private final NetworkMapper networkMapper;\n private final DroidconService service;\n private final SpeakersDao speakersDao;\n private final SessionsDao sessionsDao;\n private final DataProviderCache cache;\n\n @Inject\n public DataProvider(AppMapper appMapper, NetworkMapper networkMapper, DroidconService service, SpeakersDao speakersDao, SessionsDao sessionsDao) {\n this.appMapper = appMapper;\n this.networkMapper = networkMapper;\n this.service = service;\n this.speakersDao = speakersDao;\n this.sessionsDao = sessionsDao;\n this.cache = new DataProviderCache();\n }\n\n public Observable<Schedule> getSchedule() {\n sessionsDao.initSelectedSessionsMemory();\n return getSessions().map(appMapper::toSchedule);\n }\n\n public Observable<List<Speaker>> getSpeakers() {\n return Observable.create(subscriber -> speakersDao.getSpeakers().subscribe(speakers -> {\n if (!speakers.isEmpty()) {\n subscriber.onNext(speakers);\n }\n\n if (!subscriber.isUnsubscribed()) {\n getSpeakersFromNetwork(subscriber);\n }\n subscriber.onCompleted();\n }, subscriber::onError));\n }\n\n private void getSpeakersFromNetwork(Subscriber<? super List<Speaker>> subscriber) {\n List<Speaker> fromCache = cache.getSpeakers();\n if (fromCache == null) {\n service.loadSpeakers()\n .map(networkMapper::toAppSpeakers)\n .subscribe(speakers -> {\n subscriber.onNext(speakers);\n speakersDao.saveSpeakers(speakers);\n cache.saveSpeakers(speakers);\n }, throwable -> Timber.e(throwable, \"Error getting speakers from network\"));\n } else {\n subscriber.onNext(fromCache);\n }\n }\n\n private Observable<List<Session>> getSessions() {\n return Observable.create(subscriber -> sessionsDao.getSessions().subscribe(sessions -> {\n if (!sessions.isEmpty()) {\n subscriber.onNext(sessions);\n }\n\n if (!subscriber.isUnsubscribed()) {\n getSessionsFromNetwork(subscriber);\n }\n subscriber.onCompleted();\n }, subscriber::onError));\n }\n\n private void getSessionsFromNetwork(Subscriber<? super List<Session>> subscriber) {\n List<Session> fromCache = cache.getSessions();\n if (fromCache == null) {\n Observable.zip(\n service.loadSessions(),\n getSpeakers().last().map(appMapper::speakersToMap),\n networkMapper::toAppSessions)\n .subscribe(sessions -> {\n subscriber.onNext(sessions);\n sessionsDao.saveSessions(sessions);\n cache.saveSessions(sessions);\n }, throwable -> Timber.e(throwable, \"Error getting sessions from network\"));\n } else {\n subscriber.onNext(fromCache);\n }\n }\n}", "@Value\npublic class Speaker implements Parcelable {\n\n public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() {\n public Speaker createFromParcel(Parcel source) {\n return new Speaker(source);\n }\n\n public Speaker[] newArray(int size) {\n return new Speaker[size];\n }\n };\n\n int id;\n String name;\n String title;\n String bio;\n String website;\n String twitter;\n String github;\n String photo;\n\n public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) {\n this.id = id;\n this.name = name;\n this.title = title;\n this.bio = bio;\n this.website = website;\n this.twitter = twitter;\n this.github = github;\n this.photo = photo;\n }\n\n protected Speaker(Parcel in) {\n id = in.readInt();\n name = in.readString();\n title = in.readString();\n bio = in.readString();\n website = in.readString();\n twitter = in.readString();\n github = in.readString();\n photo = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(id);\n dest.writeString(name);\n dest.writeString(title);\n dest.writeString(bio);\n dest.writeString(website);\n dest.writeString(twitter);\n dest.writeString(github);\n dest.writeString(photo);\n }\n}", "public abstract class BaseFragment<P extends BaseFragmentPresenter> extends Fragment {\n\n protected P presenter;\n private Unbinder unbinder;\n\n protected abstract P newPresenter();\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n FragmentArgs.inject(this);\n presenter = newPresenter();\n if (presenter != null) {\n presenter.onCreate(savedInstanceState);\n }\n }\n\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n unbinder = ButterKnife.bind(this, view);\n if (presenter != null) {\n presenter.onViewCreated(view, savedInstanceState);\n }\n }\n\n @Override\n public void onStart() {\n super.onStart();\n if (presenter != null) {\n presenter.onStart();\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (presenter != null) {\n presenter.onResume();\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n if (presenter != null) {\n presenter.onSaveInstanceState(outState);\n }\n }\n\n @Override\n public void onStop() {\n if (presenter != null) {\n presenter.onStop();\n }\n super.onStop();\n }\n\n @Override\n public void onDestroyView() {\n unbinder.unbind();\n super.onDestroyView();\n }\n}", "public class MarginDecoration extends RecyclerView.ItemDecoration {\n\n private final int margin;\n\n public MarginDecoration(Context context) {\n margin = context.getResources().getDimensionPixelSize(R.dimen.item_margin);\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n super.getItemOffsets(outRect, view, parent, state);\n outRect.set(margin, margin, margin, margin);\n }\n}", "public class SpeakerDetailsDialogFragment extends AppCompatDialogFragment {\n\n @Inject Picasso picasso;\n\n @BindView(R.id.speaker_details_name) TextView name;\n @BindView(R.id.speaker_details_title) TextView title;\n @BindView(R.id.speaker_details_bio) TextView bio;\n @BindView(R.id.speaker_details_photo) ImageView photo;\n @BindView(R.id.speaker_details_links_container) ViewGroup linksContainer;\n @BindView(R.id.speaker_details_twitter) ImageView twitter;\n @BindView(R.id.speaker_detail_github) ImageView github;\n @BindView(R.id.speaker_details_website) ImageView website;\n\n private Unbinder unbinder;\n\n private static final String EXTRA_SPEAKER = \"speaker\";\n\n public static void show(@NonNull Speaker speaker, @NonNull FragmentManager fm) {\n Bundle args = new Bundle();\n args.putParcelable(EXTRA_SPEAKER, speaker);\n SpeakerDetailsDialogFragment fragment = new SpeakerDetailsDialogFragment();\n fragment.setArguments(args);\n fragment.show(fm, SpeakerDetailsDialogFragment.class.getSimpleName());\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n DroidconApp.get(getContext()).component().inject(this);\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n @SuppressLint(\"InflateParams\")\n View view = LayoutInflater.from(getContext()).inflate(R.layout.speaker_details, null);\n unbinder = ButterKnife.bind(this, view);\n bindSpeaker(getArguments().getParcelable(EXTRA_SPEAKER));\n return new AlertDialog.Builder(getContext())\n .setView(view)\n .setPositiveButton(R.string.speaker_details_hide, (dialog, which) -> dismiss())\n .create();\n }\n\n @Override\n public void onDestroyView() {\n unbinder.unbind();\n super.onDestroyView();\n }\n\n private void bindSpeaker(Speaker speaker) {\n name.setText(speaker.getName());\n title.setText(speaker.getTitle());\n bio.setText(speaker.getBio());\n\n String photoUrl = speaker.getPhoto();\n if (!TextUtils.isEmpty(photoUrl)) {\n picasso.load(photoUrl).transform(new CircleTransformation()).into(photo);\n }\n\n bindLinks(speaker);\n }\n\n private void bindLinks(Speaker speaker) {\n boolean hasLink = false;\n\n if (!TextUtils.isEmpty(speaker.getTwitter())) {\n twitter.setVisibility(View.VISIBLE);\n twitter.setOnClickListener(v -> openLink(\"https://www.twitter.com/#!/\" + speaker.getTwitter()));\n hasLink = true;\n }\n\n if (!TextUtils.isEmpty(speaker.getGithub())) {\n github.setVisibility(View.VISIBLE);\n github.setOnClickListener(v -> openLink(\"https://www.github.com/\" + speaker.getGithub()));\n hasLink = true;\n }\n\n if (!TextUtils.isEmpty(speaker.getWebsite())) {\n website.setVisibility(View.VISIBLE);\n website.setOnClickListener(v -> openLink(speaker.getWebsite()));\n hasLink = true;\n }\n\n linksContainer.setVisibility(hasLink ? View.VISIBLE : View.GONE);\n }\n\n private void openLink(String url) {\n Intents.startExternalUrl(getActivity(), url);\n }\n}" ]
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.DataProvider; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.BaseFragment; import com.nilhcem.droidconde.ui.core.recyclerview.MarginDecoration; import com.nilhcem.droidconde.ui.speakers.details.SpeakerDetailsDialogFragment; import com.squareup.picasso.Picasso; import java.util.List; import javax.inject.Inject; import butterknife.BindView;
package com.nilhcem.droidconde.ui.speakers.list; public class SpeakersListFragment extends BaseFragment<SpeakersListPresenter> implements SpeakersListMvp.View { @Inject Picasso picasso; @Inject DataProvider dataProvider; @BindView(R.id.speakers_list_loading) ProgressBar loading; @BindView(R.id.speakers_list_recyclerview) RecyclerView recyclerView; private Snackbar errorSnackbar; private SpeakersListAdapter adapter; @Override protected SpeakersListPresenter newPresenter() { return new SpeakersListPresenter(this, dataProvider); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { DroidconApp.get(getContext()).component().inject(this); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.speakers_list, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); adapter = new SpeakersListAdapter(picasso, this);
recyclerView.addItemDecoration(new MarginDecoration(getContext()));
4
HarryPotterSpells/HarryPotterSpells
src/com/hpspells/core/spell/SpellManager.java
[ "public class HPS extends JavaPlugin {\n public static HPS instance;\n \n public ConfigurationManager ConfigurationManager;\n public PM PM;\n public SpellManager SpellManager;\n public WandManager WandManager;\n public SpellTargeter SpellTargeter;\n public Localisation Localisation;\n public ExtensionManager ExtensionManager;\n\n private static List<ItemStack> recipeResults = new ArrayList<ItemStack>();\n private static CommandMap commandMap;\n private static Collection<HelpTopic> helpTopics = new ArrayList<HelpTopic>();\n\n /**\n * State of the Localisation class, if it requires the plugin to disable \n * {@code state = false;} otherwise state will always be true\n */\n public boolean localeState = true;\n \n @Override\n public void onEnable() {\n instance = this;\n // Instance loading\n PM = new PM(this);\n ConfigurationManager = new ConfigurationManager(this);\n Localisation = new Localisation(this);\n if (localeState) {\n \tSpellTargeter = new SpellTargeter(this);\n SpellManager = new SpellManager(this);\n WandManager = new WandManager(this);\n ExtensionManager = new ExtensionManager(this);\n new APIHandler(this);\n \n // Configuration\n ConfigurationManager.loadConfig();\n\n PlayerSpellConfig PSC = (PlayerSpellConfig) ConfigurationManager.getConfig(ConfigurationType.PLAYER_SPELL);\n Double version = PSC.get().getDouble(\"VERSION_DO_NOT_EDIT\", -1d) == -1d ? null : PSC.get().getDouble(\"VERSION_DO_NOT_EDIT\", -1d);\n \n if (new File(getDataFolder(), \"PlayerSpellConfig.yml\").exists()) {\n \tif (version == null || version < PlayerSpellConfig.CURRENT_VERSION) {\n // STORE UPDATES HERE\n\n if (version == null) { // Updating from unformatted version to version 1.1\n PM.log(Level.INFO, Localisation.getTranslation(\"pscOutOfDate\"));\n\n Map<String, List<String>> newConfig = new HashMap<String, List<String>>(), lists = new HashMap<String, List<String>>();\n Set<String> css = new HashSet<String>();\n\n for (String s : PSC.get().getKeys(false)) // This seemingly stupid code is to avoid a ConcurrencyModificationException (google it)\n css.add(s);\n\n for (String s : css)\n lists.put(s, PSC.get().getStringList(s));\n\n for (String cs : css) {\n List<String> list = new ArrayList<String>();\n for (String spellString : PSC.get().getStringList(cs)) {\n if (spellString.equals(\"AlarteAscendare\")) {\n list.add(\"Alarte Ascendare\");\n } else if (spellString.equals(\"AvadaKedavra\")) {\n list.add(\"Avada Kedavra\");\n } else if (spellString.equals(\"FiniteIncantatem\")) {\n list.add(\"Finite Incantatem\");\n } else if (spellString.equals(\"MagnaTonitrus\")) {\n list.add(\"Magna Tonitrus\");\n } else if (spellString.equals(\"PetrificusTotalus\")) {\n list.add(\"Petrificus Totalus\");\n } else if (spellString.equals(\"TimeSpell\")) {\n list.add(\"Time\");\n } else if (spellString.equals(\"TreeSpell\")) {\n list.add(\"Tree\");\n } else if (spellString.equals(\"WingardiumLeviosa\")) {\n list.add(\"Wingardium Leviosa\");\n } else {\n list.add(spellString);\n }\n }\n\n newConfig.put(cs, list);\n }\n\n for (Entry<String, List<String>> ent : newConfig.entrySet())\n PSC.get().set(ent.getKey(), ent.getValue());\n\n PSC.get().set(\"VERSION_DO_NOT_EDIT\", 1.1d);\n PSC.save();\n\n PM.log(Level.INFO, Localisation.getTranslation(\"pscUpdated\", \"1.1\"));\n }\n }\n }\n\n // Listeners\n getServer().getPluginManager().registerEvents(new Listeners(this), this);\n getServer().getPluginManager().registerEvents(new MetricStatistics(), this);\n\n // Hacky command map stuff\n try {\n Class<?> craftServer = SVPBypass.getCurrentCBClass(\"CraftServer\");\n if (craftServer == null)\n throw new Throwable(\"Computer says no\");\n Field f = craftServer.getDeclaredField(\"commandMap\");\n f.setAccessible(true);\n commandMap = (CommandMap) f.get(getServer());\n } catch (Throwable e) {\n PM.log(Level.SEVERE, Localisation.getTranslation(\"errCommandMap\"));\n PM.debug(e);\n }\n\n // Reflections - Commands\n int commands = 0;\n try {\n for (Class<? extends HCommandExecutor> clazz : ReflectionsReplacement.getSubtypesOf(HCommandExecutor.class, \"com.hpspells.core.command\", getClassLoader(), HCommandExecutor.class)) {\n if (addHackyCommand(clazz))\n commands++;\n }\n } catch (Exception e) {\n PM.log(Level.WARNING, Localisation.getTranslation(\"errReflectionsReplacementCmd\"));\n PM.debug(e);\n }\n \n// HPSTabCompleter completer = new HPSTabCompleter();\n// getCommand(\"spellinfo\").setTabCompleter(completer);\n// getCommand(\"spellswitch\").setTabCompleter(completer);\n// getCommand(\"teach\").setTabCompleter(completer);\n// getCommand(\"unteach\").setTabCompleter(completer);\n \n PM.debug(Localisation.getTranslation(\"dbgRegisteredCoreCommands\", commands));\n\n Bukkit.getHelpMap().addTopic(new IndexHelpTopic(\"HarryPotterSpells\", Localisation.getTranslation(\"hlpDescription\"), \"\", helpTopics));\n PM.debug(Localisation.getTranslation(\"dbgHelpCommandsAdded\"));\n\n // Plugin Metrics\n setupCharts(new Metrics(this));\n\n // Crafting Changes\n PM.debug(Localisation.getTranslation(\"dbgCraftingStart\"));\n setupCrafting();\n PM.debug(Localisation.getTranslation(\"dbgCraftingEnd\"));\n\n // Extension manager setup\n PM.debug(Localisation.getTranslation(\"dbgExtensionStart\"));\n ExtensionManager.loadExtensions();\n ExtensionManager.enableExtensions();\n PM.debug(Localisation.getTranslation(\"dbgExtensionStop\"));\n\n PM.log(Level.INFO, Localisation.getTranslation(\"genPluginEnabled\"));\n }\n }\n\n @Override\n public void onDisable() {\n ExtensionManager.disableExtensions();\n \tif (localeState)\n \t\tPM.log(Level.INFO, Localisation.getTranslation(\"genPluginDisabled\"));\n \telse\n \t\tPM.log(Level.INFO, \"Plugin disabled.\");\n }\n \n public boolean onReload() {\n reloadConfig();\n ConfigurationManager.reloadConfigAll();\n Localisation.load();\n ExtensionManager.reloadExtensions();\n this.WandManager = new WandManager(this);\n if (!setupCrafting()) return false;\n return true;\n }\n \n private void setupCharts(Metrics metrics) {\n \ttry {\n \t\t// Total Amount of Spells Casted\n// metrics.addCustomChart(new Metrics.MultiLineChart(\"spells_casted_total\", () -> {\n// \tMap<String, Integer> spellsCastMap = new HashMap<>();\n//\t\t\t\tspellsCastMap.put(\"Total\", MetricStatistics.getSpellsCast());\n//\t\t\t\tspellsCastMap.put(\"Hits\", MetricStatistics.getSuccesses());\n//\t\t\t\tspellsCastMap.put(\"Misses\", MetricStatistics.getFailures());\n//\t\t\t\treturn spellsCastMap;\n// }));\n \t\t\n \t\tmetrics.addCustomChart(new Metrics.SingleLineChart(\"total_spells_casted\", () -> MetricStatistics.getSpellsCast()));\n \t\tmetrics.addCustomChart(new Metrics.SingleLineChart(\"total_spells_successes\", () -> MetricStatistics.getSuccesses()));\n \t\tmetrics.addCustomChart(new Metrics.SingleLineChart(\"total_spells_failures\", () -> MetricStatistics.getFailures()));\n \t\t\n // Amount of Spells Casted per Spell\n metrics.addCustomChart(new Metrics.SimpleBarChart(\"spells_casted_single\", () -> {\n \tMap<String, Integer> spellsCastMap = new HashMap<>();\n\t\t\t\tfor (Spell spell : SpellManager.getSpells()) {\n\t\t\t\t\tspellsCastMap.put(spell.getName(), MetricStatistics.getAmountOfTimesCast(spell));\n\t\t\t\t}\n\t\t\t\treturn spellsCastMap;\n } ));\n \n // Language used\n metrics.addCustomChart(new Metrics.SimplePie(\"Language\", () -> Language.getLanuage(getConfig().getString(\"language\")).toString()));\n } catch (Exception e) {\n PM.log(Level.WARNING, Localisation.getTranslation(\"errPluginMetrics\"));\n PM.debug(e);\n }\n }\n \n public boolean setupCrafting() {\n if (!recipeResults.isEmpty()) {\n \trecipeResults.clear();\n getServer().resetRecipes();\n }\n \t\n if (getConfig().getBoolean(\"wand.crafting.enabled\", true)) {\n try {\n ShapedRecipe wandRecipe = new ShapedRecipe(new NamespacedKey(this, \"wand\"), WandManager.getLorelessWand());\n List<String> list = getConfig().getStringList(\"wand.crafting.recipe\");\n Set<String> ingredients = getConfig().getConfigurationSection(\"wand.crafting.ingredients\").getKeys(false);\n\n wandRecipe.shape(list.get(0), list.get(1), list.get(2));\n for (String string : ingredients) {\n wandRecipe.setIngredient(string.toCharArray()[0], Material.matchMaterial(getConfig().getString(\"wand.crafting.ingredients.\" + string)));\n }\n\n recipeResults.add(wandRecipe.getResult());\n getServer().addRecipe(wandRecipe);\n return true;\n } catch (NullPointerException e) { // It's surrounded by a try/catch block because we can't let any stupid errors in config disable the plugin.\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (player.isOp()) {\n PM.tell(player, ChatColor.RED + \"Unable to load material from crafting config\");\n PM.tell(player, \"Please check that all values are correct\");\n }\n }\n PM.log(Level.INFO, Localisation.getTranslation(\"errCraftingChanges\"));\n PM.debug(e);\n return false;\n } catch (Exception e) {\n PM.log(Level.INFO, Localisation.getTranslation(\"errCraftingChanges\"));\n PM.debug(e);\n return false;\n }\n }\n\n if (getConfig().getBoolean(\"spells-craftable\", true)) {\n for (Spell s : SpellManager.getSpells()) {\n if (s instanceof Craftable) {\n SpellBookRecipeAddEvent e = new SpellBookRecipeAddEvent(((Craftable) s).getCraftingRecipe());\n getServer().getPluginManager().callEvent(e);\n if (!e.isCancelled()) {\n recipeResults.add(e.getRecipe().getResult());\n getServer().addRecipe(e.getRecipe());\n }\n }\n }\n }\n return true;\n }\n\n public ClassLoader getHPSClassLoader() {\n return getClassLoader();\n }\n \n public CustomConfiguration getConfig(ConfigurationType type) {\n \treturn ConfigurationManager.getConfig(type);\n }\n\n /**\n * Registers a {@link HackyCommand} to the plugin\n *\n * @param clazz a class that extends {@code CommandExecutor}\n * @return {@code true} if the command was added successfully\n */\n public boolean addHackyCommand(Class<? extends HCommandExecutor> clazz) {\n if (!clazz.isAnnotationPresent(CommandInfo.class)) {\n PM.log(Level.INFO, Localisation.getTranslation(\"errAddCommandMapAnnotation\", clazz.getSimpleName()));\n return false;\n }\n\n CommandInfo cmdInfo = clazz.getAnnotation(CommandInfo.class);\n String name = cmdInfo.name().equals(\"\") ? clazz.getSimpleName().toLowerCase() : cmdInfo.name();\n String permission = cmdInfo.permission().equals(\"\") ? \"harrypotterspells.\" + name : cmdInfo.permission();\n List<String> aliases = cmdInfo.aliases().equals(\"\") ? new ArrayList<String>() : Arrays.asList(cmdInfo.aliases().split(\",\"));\n Permission perm = new Permission(permission, PermissionDefault.getByName(cmdInfo.permissionDefault()));\n Bukkit.getServer().getPluginManager().addPermission(perm);\n HackyCommand hacky = new HackyCommand(this, name, Localisation.getTranslation(cmdInfo.description()), cmdInfo.usage(), aliases);\n hacky.setPermission(permission);\n hacky.setPermissionMessage(Localisation.getTranslation(cmdInfo.noPermissionMessage()));\n try {\n hacky.setExecutor(clazz.getConstructor(HPS.class).newInstance(this));\n } catch (Exception e) {\n PM.log(Level.WARNING, Localisation.getTranslation(\"errAddCommandMap\", clazz.getSimpleName()));\n PM.debug(e);\n return false;\n }\n commandMap.register(\"\", hacky);\n helpTopics.add(new GenericCommandHelpTopic(hacky));\n return true;\n }\n\n /**\n * A very hacky class used to register commands at plugin runtime\n */\n private static class HackyCommand extends Command {\n private CommandExecutor executor;\n private HPS HPS;\n\n public HackyCommand(HPS instance, String name, String description, String usageMessage, List<String> aliases) {\n super(name, description, usageMessage, aliases);\n this.HPS = instance;\n }\n\n @Override\n public boolean execute(CommandSender sender, String commandLabel, String[] args) {\n String s = sender instanceof Player ? \"/\" : \"\";\n if (executor == null)\n sender.sendMessage(HPS.Localisation.getTranslation(\"cmdUnknown\", s));\n else if (!sender.hasPermission(getPermission()))\n HPS.PM.dependantMessagingWarn(sender, getPermissionMessage());\n else {\n boolean success = executor.onCommand(sender, this, commandLabel, args);\n if (!success)\n HPS.PM.dependantMessagingTell(sender, ChatColor.RED + HPS.Localisation.getTranslation(\"cmdUsage\", s, getUsage().replace(\"<command>\", commandLabel)));\n }\n return true;\n }\n \n @Override\n public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {\n List<String> cmdList = new ArrayList<>(Arrays.asList(\"spellinfo\", \"teach\")); //All spells\n List<String> cmdList2 = new ArrayList<>(Arrays.asList(\"spellswitch\", \"unteach\")); //Player known spells\n if ((cmdList.contains(this.getName().toLowerCase()) || this.getAliases().stream().anyMatch(a -> this.getName().equalsIgnoreCase(a))) && args.length >= 1 && !HPS.SpellManager.isSpell(args[0])) {\n List<String> list = new ArrayList<String>();\n if (args[0] == null) {\n HPS.SpellManager.getSpells().forEach(spell -> {\n String spellName = spell.getName().replace(' ', '_');\n list.add(spellName);\n });\n } else {\n HPS.SpellManager.getSpells().stream()\n .filter(spell -> spell.getName().toLowerCase().startsWith(args[0].toLowerCase()))\n .forEach(spell -> {\n String spellName = spell.getName().replace(' ', '_');\n list.add(spellName);\n });\n }\n return list;\n } else if ((cmdList2.contains(this.getName().toLowerCase()) || this.getAliases().stream().anyMatch(a -> this.getName().equalsIgnoreCase(a))) && args.length >= 1 && !HPS.SpellManager.isSpell(args[0])) {\n List<String> list = new ArrayList<String>();\n if (args[0] == null) {\n HPS.SpellManager.getSpells().stream()\n .filter(spell -> spell.playerKnows((Player) sender))\n .forEach(spell -> {\n String spellName = spell.getName().replace(' ', '_');\n list.add(spellName);\n });\n } else {\n HPS.SpellManager.getSpells().stream()\n .filter(spell -> spell.getName().toLowerCase().startsWith(args[0].toLowerCase()) && spell.playerKnows((Player) sender))\n .forEach(spell -> {\n String spellName = spell.getName().replace(' ', '_');\n list.add(spellName);\n });\n }\n return list;\n }\n return super.tabComplete(sender, alias, args);\n }\n\n /**\n * Sets the executor to be used for this hacky command\n *\n * @param executor the executor\n */\n public void setExecutor(CommandExecutor executor) {\n this.executor = executor;\n }\n\n }\n\n}", "public class SpellEvent extends Event {\n private static final HandlerList handlers = new HandlerList();\n\n private Spell spell;\n private Player caster;\n\n public SpellEvent(Spell spell, Player caster) {\n this.spell = spell;\n this.caster = caster;\n }\n\n /**\n * Gets the HandlerList for this event\n *\n * @return the handler list\n */\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n /**\n * Gets the spell that is being cast\n *\n * @return the spell\n */\n public Spell getSpell() {\n return spell;\n }\n\n /**\n * Gets the caster of the spell\n *\n * @return the caster\n */\n public Player getCaster() {\n return caster;\n }\n\n /*\n * START STATIC METHODS\n */\n\n /**\n * Gets the HandlerList for this event\n *\n * @return the handler list\n */\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n}", "public class SpellPostCastEvent extends SpellEvent {\n private static final HandlerList handlers = new HandlerList();\n\n private final boolean successful;\n\n public SpellPostCastEvent(Spell spell, Player caster, boolean successful) {\n super(spell, caster);\n this.successful = successful;\n }\n\n /**\n * Gets the HandlerList for this event\n *\n * @return the handler list\n */\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n /**\n * Gets whether the spell was successfully cast or not\n *\n * @return {@code true} if the spell was successfully cast\n */\n public boolean wasSuccessful() {\n return successful;\n }\n\n /*\n * START STATIC METHODS\n */\n\n /**\n * Gets the HandlerList for this event\n *\n * @return the handler list\n */\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n}", "public class SpellPreCastEvent extends SpellEvent implements Cancellable {\n private static final HandlerList handlers = new HandlerList();\n\n private boolean cancelled = false;\n\n public SpellPreCastEvent(Spell spell, Player caster) {\n super(spell, caster);\n }\n\n /**\n * Gets the HandlerList for this event\n *\n * @return the handler list\n */\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n /**\n * Gets the cancelation status of this spell\n *\n * @return {@code true} if the spell has been cancelled\n */\n @Override\n public boolean isCancelled() {\n return cancelled;\n }\n\n /**\n * Sets the cancelation status of this spell\n *\n * @param cancel\n */\n @Override\n public void setCancelled(boolean cancel) {\n cancelled = cancel;\n }\n\n\t/*\n\t * START STATIC METHODS\n\t */\n\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n}", "public enum ConfigurationType {\n /**\n * Stores a list of the spells that every player knows\n */\n PLAYER_SPELL,\n /**\n * Stores a list of spell configurations\n */\n SPELL,\n /**\n * Stores a list of cooldowns for spells\n */\n COOLDOWN;\n}", "public class PlayerSpellConfig extends CustomConfiguration {\n\n /**\n * Constructs a new {@link PlayerSpellConfig} without copying any defaults\n *\n * @param instance an instance of {@link HPS}\n * @param file where to store the custom configuration\n */\n public PlayerSpellConfig(HPS instance, File file) {\n super(instance, file);\n }\n\n /**\n * Constructs a new {@link CustomConfiguration}, copying defaults from an {@link InputStream}\n *\n * @param instance an instance of {@link HPS}\n * @param file where to store the custom configuration\n * @param stream an input stream to copy default configuration from\n */\n public PlayerSpellConfig(HPS instance, File file, InputStream stream) {\n super(instance, file, stream, null);\n }\n\n /**\n * The current version specifying the format of the {@code PlayerSpellConfig.yml}\n */\n public static final double CURRENT_VERSION = 1.1d;\n\n /**\n * A utility function that is meant to be used instead of {@link FileConfiguration#getStringList(String)}. <br>\n * This is needed because the Bukkit version returns {@code null} when no String list is found.\n *\n * @param string the path to the String list\n * @return the string list at that location or an empty {@link ArrayList}\n */\n public List<String> getStringListOrEmpty(String string) {\n return get().getStringList(string) == null ? new ArrayList<String>() : get().getStringList(string);\n }\n\n}", "public class ReflectionsReplacement {\n\n /**\n * Gets a list containing the fully qualified names of the all classes in a package\n *\n * @param packageName the name of the package\n * @param classLoader the {@link ClassLoader} to find the package in\n * @return a list containing the names of all classes in a package\n * @throws IOException if an error occurred whilst getting the package information\n */\n public static List<String> getClassNamesFromPackage(String packageName, ClassLoader classLoader) throws IOException {\n URL packageURL;\n ArrayList<String> names = new ArrayList<String>();\n ;\n\n packageName = packageName.replace(\".\", \"/\");\n packageURL = classLoader.getResource(packageName);\n\n if (packageURL.getProtocol().equals(\"jar\")) { // Loop through all things in the jar\n String jarFileName;\n JarFile jf;\n Enumeration<JarEntry> jarEntries;\n String entryName;\n\n jarFileName = URLDecoder.decode(packageURL.getFile(), \"UTF-8\");\n jarFileName = jarFileName.substring(5, jarFileName.indexOf(\"!\"));\n jf = new JarFile(jarFileName);\n jarEntries = jf.entries();\n while (jarEntries.hasMoreElements()) { // Get the jar file and loop through everything in it\n entryName = jarEntries.nextElement().getName();\n if (entryName.startsWith(packageName) && entryName.endsWith(\".class\") && entryName.length() > packageName.length() + 5) {\n names.add(entryName.replace(\".class\", \"\").replace('/', '.')); // Put the stuff back again\n }\n }\n jf.close();\n } else { // Otherwise loop through all things in the classpath\n File folder = new File(packageURL.getFile());\n File[] contenuti = folder.listFiles();\n String entryName;\n for (File actual : contenuti) {\n entryName = actual.getName();\n names.add(entryName.replace(\".class\", \"\").replace('/', '.'));\n }\n }\n\n return names;\n }\n\n /**\n * Gets all subtypes of a specified class in a package\n *\n * @param clazz the class to find subtypes of\n * @param packagee the package to search in\n * @param classLoader the {@link ClassLoader} to find the package in\n * @param ignore classes to ignore\n * @return a list containing all subtypes of the specified class\n * @throws Exception if an error occurred during the lookup of these classes\n */\n public static <T> List<Class<? extends T>> getSubtypesOf(Class<T> clazz, String packagee, ClassLoader classLoader, Class<?>... ignore) throws Exception {\n List<Class<? extends T>> returnMe = Lists.newArrayList();\n List<Class<?>> ignores = Lists.newArrayList(ignore);\n for (String str : getClassNamesFromPackage(packagee, classLoader)) {\n Class<?> indi = Class.forName(str.replace(\".class\", \"\"));\n if (clazz.isAssignableFrom(indi) && !ignores.contains(indi)) {\n @SuppressWarnings(\"unchecked\") Class<? extends T> extended = (Class<? extends T>) indi;\n returnMe.add(extended);\n }\n }\n return returnMe;\n }\n\n /**\n * Adds a file to a classpath\n *\n * @param classPath the classpath\n * @param file the file\n * @throws Exception if an error occurred while adding the class to the classpath\n */\n public static void addFileToClasspath(ClassLoader classPath, File file) throws Exception {\n Method method = URLClassLoader.class.getDeclaredMethod(\"addURL\", new Class[]{URL.class});\n method.setAccessible(true);\n method.invoke(classPath, new Object[]{file.toURI().toURL()});\n }\n\n /**\n * Adds a file to the system's classpath\n *\n * @param file the file\n * @throws Exception if an error occurred while adding the class to the classpath\n */\n public static void addFileToClasspath(File file) throws Exception {\n addFileToClasspath(ClassLoader.getSystemClassLoader(), file);\n }\n\n}" ]
import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import javax.annotation.Nullable; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import com.google.common.collect.Iterables; import com.hpspells.core.HPS; import com.hpspells.core.api.event.SpellEvent; import com.hpspells.core.api.event.SpellPostCastEvent; import com.hpspells.core.api.event.SpellPreCastEvent; import com.hpspells.core.configuration.ConfigurationManager.ConfigurationType; import com.hpspells.core.configuration.PlayerSpellConfig; import com.hpspells.core.spell.Spell.SpellInfo; import com.hpspells.core.util.ReflectionsReplacement;
package com.hpspells.core.spell; /** * A class that manages spells and holds lots of spell related utilities */ public class SpellManager { private HashMap<String, HashMap<Spell, Long>> cooldowns = new HashMap<String, HashMap<Spell, Long>>(); private Comparator<Spell> spellComparator = new Comparator<Spell>() { @Override public int compare(Spell o1, Spell o2) { return o1.getName().compareTo(o2.getName()); } }; private SortedSet<Spell> spellList = new TreeSet<Spell>(spellComparator); private Map<String, Integer> currentSpell = new HashMap<String, Integer>();
private HPS HPS;
0
komamj/KomaMusic
app/src/main/java/com/koma/music/helper/ArtworkDataFetcher.java
[ "public class MusicApplication extends Application {\n private static final String TAG = MusicApplication.class.getSimpleName();\n\n private static Context sContext;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n LogUtils.i(TAG, \"onCreate\");\n\n enableStrictMode();\n\n sContext = getApplicationContext();\n\n ImageLoaderConfiguration localImageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this).build();\n ImageLoader.getInstance().init(localImageLoaderConfiguration);\n\n if (LeakCanary.isInAnalyzerProcess(this)) {\n // This process is dedicated to LeakCanary for heap analysis.\n // You should not init your app in this process.\n return;\n }\n LeakCanary.install(this);\n }\n\n public synchronized static Context getContext() {\n return sContext;\n }\n\n @Override\n public void onLowMemory() {\n LogUtils.e(TAG, \"onLowMemory\");\n\n //clear cache\n Glide.get(sContext).clearMemory();\n\n super.onLowMemory();\n }\n\n private void enableStrictMode() {\n final StrictMode.ThreadPolicy.Builder threadPolicyBuilder = new StrictMode.ThreadPolicy.Builder()\n .detectAll().penaltyLog();\n final StrictMode.VmPolicy.Builder vmPolicyBuilder = new StrictMode.VmPolicy.Builder()\n .detectAll().penaltyLog();\n\n threadPolicyBuilder.penaltyFlashScreen();\n StrictMode.setThreadPolicy(threadPolicyBuilder.build());\n StrictMode.setVmPolicy(vmPolicyBuilder.build());\n }\n}", "public class AlbumsPresenter implements AlbumsConstract.Presenter {\n private static String TAG = AlbumsPresenter.class.getSimpleName();\n @NonNull\n private AlbumsConstract.View mView;\n\n private MusicRepository mRepository;\n\n private CompositeDisposable mDisposables;\n\n public AlbumsPresenter(@NonNull AlbumsConstract.View view, MusicRepository repository) {\n mView = view;\n mView.setPresenter(this);\n\n mRepository = repository;\n\n mDisposables = new CompositeDisposable();\n }\n\n @Override\n public void subscribe() {\n LogUtils.i(TAG, \"subscribe\");\n\n loadAlbums();\n }\n\n @Override\n public void unSubscribe() {\n LogUtils.i(TAG, \"unSubcribe\");\n\n if (mDisposables != null) {\n mDisposables.clear();\n }\n }\n\n @Override\n public void loadAlbums() {\n LogUtils.i(TAG, \"loadAlbums\");\n\n mDisposables.clear();\n\n Disposable disposable = mRepository.getAllAlbums().subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribeWith(new DisposableSubscriber<List<Album>>() {\n @Override\n public void onError(Throwable throwable) {\n LogUtils.e(TAG, \"loadAlbums onError : \" + throwable.toString());\n }\n\n @Override\n public void onComplete() {\n\n }\n\n @Override\n public void onNext(List<Album> albumList) {\n onLoadSongsFinished(albumList);\n }\n });\n\n mDisposables.add(disposable);\n }\n\n @Override\n public void onLoadSongsFinished(List<Album> albums) {\n LogUtils.i(TAG, \"onLoadSongsFinished\");\n\n if (mView.isActive()) {\n mView.hideLoadingView();\n\n if (albums.size() == 0) {\n mView.showEmptyView();\n } else {\n mView.showAlbums(albums);\n }\n }\n }\n\n public static List<Album> getAllAlbums() {\n return getAlbums(makeAlbucursor(null), false);\n }\n\n public static List<Album> getArtistAlbums(long artistId) {\n return getAlbums(makeAlbucursor(artistId), false);\n }\n\n private static List<Album> getAlbums(Cursor cursor, boolean isSingle) {\n List<Album> albumList = new ArrayList<>();\n\n // Gather the data\n if (cursor != null && cursor.moveToFirst()) {\n do {\n // Copy the album id\n final long id = cursor.getLong(0);\n\n // Copy the album name\n final String albumName = cursor.getString(1);\n\n // Copy the artist name\n final String artist = cursor.getString(2);\n\n // Copy the number of songs\n final int songCount = cursor.getInt(3);\n\n // Copy the release year\n final String year = cursor.getString(4);\n\n // as per designer's request, don't show unknown albums\n if (MediaStore.UNKNOWN_STRING.equals(albumName)) {\n continue;\n }\n\n // Create a new album\n final Album album = new Album(id, albumName, artist, songCount, year);\n // Add everything up\n albumList.add(album);\n } while (cursor.moveToNext() && !isSingle);\n }\n // Close the cursor\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n\n return albumList;\n }\n\n /**\n * Creates the {@link Cursor} used to run the query.\n *\n * @param artistId The artistId we want to find albums for or null if we want all albums\n * @return The {@link Cursor} used to run the album query.\n */\n private static final Cursor makeAlbucursor(final Long artistId) {\n // requested album ordering\n Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;\n\n if (artistId != null) {\n uri = MediaStore.Audio.Artists.Albums.getContentUri(\"external\", artistId);\n }\n\n Cursor cursor = MusicApplication.getContext().getContentResolver().query(uri,\n new String[]{\n /* 0 */\n BaseColumns._ID,\n /* 1 */\n MediaStore.Audio.AlbumColumns.ALBUM,\n /* 2 */\n MediaStore.Audio.AlbumColumns.ARTIST,\n /* 3 */\n MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,\n /* 4 */\n MediaStore.Audio.AlbumColumns.FIRST_YEAR\n }, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);\n\n return cursor;\n }\n}", "public class MyFavoritePresenter implements MyFavoriteContract.Presenter {\n private static final String TAG = MyFavoritePresenter.class.getSimpleName();\n\n @NonNull\n private MyFavoriteContract.View mView;\n\n private MusicRepository mRepository;\n\n private CompositeDisposable mDisposables;\n\n public MyFavoritePresenter(MyFavoriteContract.View view, MusicRepository repository) {\n mRepository = repository;\n\n mView = view;\n mView.setPresenter(this);\n\n mDisposables = new CompositeDisposable();\n }\n\n @Override\n public void subscribe() {\n LogUtils.i(TAG, \"subscribe\");\n\n loadMyFavoriteSongs();\n }\n\n @Override\n public void unSubscribe() {\n LogUtils.i(TAG, \"unSubscribe\");\n\n if (mDisposables != null) {\n mDisposables.clear();\n }\n }\n\n @Override\n public void loadMyFavoriteSongs() {\n if (mDisposables != null) {\n mDisposables.clear();\n }\n\n Disposable disposable = mRepository.getMyFavoriteSongs().subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribeWith(new DisposableSubscriber<List<Song>>() {\n @Override\n public void onError(Throwable e) {\n LogUtils.e(TAG, \"loadMyFavoriteSongs error : \" + e.toString());\n }\n\n @Override\n public void onComplete() {\n\n }\n\n @Override\n public void onNext(List<Song> songs) {\n onLoadFinished(songs);\n }\n });\n\n mDisposables.add(disposable);\n }\n\n @Override\n public void onLoadFinished(List<Song> songs) {\n LogUtils.i(TAG, \"onLoadSongsFinished count : \" + songs.size());\n\n if (mView != null) {\n if (mView.isActive()) {\n mView.hideLoadingView();\n\n if (songs.size() == 0) {\n Glide.with(mView.getContext())\n .asBitmap()\n .load(R.drawable.ic_album)\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {\n if (mView != null) {\n mView.showArtwork(resource);\n }\n }\n });\n\n mView.showEmptyView();\n } else {\n Glide.with(mView.getContext())\n .asBitmap()\n .load(Utils.getAlbumArtUri(songs.get(0).mAlbumId))\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {\n if (mView != null) {\n mView.showArtwork(resource);\n }\n }\n\n @Override\n public void onLoadFailed(Drawable errorDrawable) {\n super.onLoadFailed(errorDrawable);\n if (mView != null) {\n mView.showArtwork(errorDrawable);\n }\n }\n });\n\n mView.showFavoriteSongs(songs);\n }\n }\n }\n }\n\n public static final List<Song> getFavoriteSongs() {\n return SongsPresenter.getSongsForCursor(getFavoriteSongCursor(), false);\n }\n\n public static Cursor getFavoriteSongCursor() {\n Cursor cursor = FavoriteSong.getInstance(MusicApplication.getContext()).getFavoriteSong();\n SortedCursor sortedCursor = SongsPresenter.makeSortedCursor(MusicApplication.getContext(),\n cursor, 0);\n return sortedCursor;\n }\n}", "public class RecentlyAddedPresenter implements RecentlyAddedContract.Presenter {\n private static final String TAG = RecentlyAddedPresenter.class.getSimpleName();\n\n private MusicRepository mRepository;\n\n private CompositeDisposable mDisposables;\n\n @NonNull\n private RecentlyAddedContract.View mView;\n\n public RecentlyAddedPresenter(RecentlyAddedContract.View view, MusicRepository repository) {\n mView = view;\n mView.setPresenter(this);\n\n mRepository = repository;\n\n mDisposables = new CompositeDisposable();\n }\n\n @Override\n public void subscribe() {\n LogUtils.i(TAG, \"subscribe\");\n\n loadRecentlyAddedSongs();\n }\n\n @Override\n public void loadRecentlyAddedSongs() {\n if (mDisposables != null) {\n mDisposables.clear();\n }\n\n Disposable disposable = mRepository.getRecentlyAddedSongs().subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribeWith(new DisposableSubscriber<List<Song>>() {\n @Override\n public void onError(Throwable e) {\n LogUtils.e(TAG, \"loadRecentlyAddedSongs onError : \" + e.toString());\n }\n\n @Override\n public void onComplete() {\n\n }\n\n @Override\n public void onNext(List<Song> songs) {\n onLoadSongsFinished(songs);\n }\n });\n\n mDisposables.add(disposable);\n }\n\n @Override\n public void onLoadSongsFinished(List<Song> songs) {\n LogUtils.i(TAG, \"onLoadSongsFinished\");\n\n if (mView != null) {\n if (mView.isActive()) {\n mView.hideLoadingView();\n\n if (songs.size() == 0) {\n Glide.with(mView.getContext()).asBitmap().load(R.drawable.ic_album)\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {\n if (mView != null) {\n mView.showArtwork(resource);\n }\n }\n });\n\n mView.showEmptyView();\n } else {\n Glide.with(mView.getContext()).asBitmap()\n .load(Utils.getAlbumArtUri(songs.get(0).mAlbumId))\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {\n if (mView != null) {\n mView.showArtwork(resource);\n }\n }\n\n @Override\n public void onLoadFailed(Drawable errorDrawable) {\n super.onLoadFailed(errorDrawable);\n if (mView != null) {\n mView.showArtwork(errorDrawable);\n }\n }\n });\n\n mView.showSongs(songs);\n }\n }\n }\n }\n\n @Override\n public void unSubscribe() {\n LogUtils.i(TAG, \"unSubscribe\");\n\n if (mDisposables != null) {\n mDisposables.clear();\n }\n }\n\n public static List<Song> getRecentlyAddedSongs() {\n return SongsPresenter.getSongsForCursor(makeLastAddedCursor(), false);\n }\n\n /**\n * @return The {@link Cursor} used to run the song query.\n */\n public static final Cursor makeLastAddedCursor() {\n // timestamp of four weeks ago\n long fourWeeksAgo = (System.currentTimeMillis() / 1000) - (4 * 3600 * 24 * 7);\n // possible saved timestamp caused by user \"clearing\" the last added playlist\n long cutoff = PreferenceUtils.getInstance(MusicApplication.getContext())\n .getLastAddedCutoff() / 1000;\n // use the most recent of the two timestamps\n if (cutoff < fourWeeksAgo) {\n cutoff = fourWeeksAgo;\n }\n\n String selection = (MediaStore.Audio.AudioColumns.IS_MUSIC + \"=1\") +\n \" AND \" + MediaStore.Audio.AudioColumns.TITLE + \" != ''\" +\n \" AND \" + MediaStore.Audio.Media.DATE_ADDED + \">\" +\n cutoff;\n\n return MusicApplication.getContext().getContentResolver().query(Constants.SONG_URI,\n new String[]{\n /* 0 */\n BaseColumns._ID,\n /* 1 */\n MediaStore.Audio.AudioColumns.TITLE,\n /* 2 */\n MediaStore.Audio.AudioColumns.ARTIST,\n /* 3 */\n MediaStore.Audio.AudioColumns.ALBUM_ID,\n /* 4 */\n MediaStore.Audio.AudioColumns.ALBUM,\n /* 5 */\n MediaStore.Audio.AudioColumns.DURATION,\n }, selection, null, MediaStore.Audio.Media.DATE_ADDED + \" DESC\");\n }\n}", "public class RecentlyPlayPresenter implements RecentlyPlayContract.Presenter {\n private static final String TAG = RecentlyPlayPresenter.class.getSimpleName();\n\n @NonNull\n private RecentlyPlayContract.View mView;\n\n private CompositeDisposable mDisposables;\n\n private MusicRepository mRepository;\n\n public RecentlyPlayPresenter(@NonNull RecentlyPlayContract.View view, MusicRepository repository) {\n mDisposables = new CompositeDisposable();\n\n mView = view;\n mView.setPresenter(this);\n\n mRepository = repository;\n }\n\n @Override\n public void subscribe() {\n LogUtils.i(TAG, \"subscribe\");\n\n loadRecentlyPlayedSongs();\n }\n\n @Override\n public void unSubscribe() {\n LogUtils.i(TAG, \"unSubscribe\");\n\n if (mDisposables != null) {\n mDisposables.clear();\n }\n }\n\n @Override\n public void loadRecentlyPlayedSongs() {\n if (mDisposables != null) {\n mDisposables.clear();\n }\n\n Disposable disposable = mRepository.getRecentlyPlayedSongs().subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribeWith(new DisposableSubscriber<List<Song>>() {\n @Override\n public void onError(Throwable e) {\n LogUtils.e(TAG, \"loadRecentlyPlayedSongs error : \" + e.toString());\n }\n\n @Override\n public void onComplete() {\n\n }\n\n @Override\n public void onNext(List<Song> songs) {\n onLoadPlayedSongsFinished(songs);\n }\n });\n\n mDisposables.add(disposable);\n }\n\n @Override\n public void onLoadPlayedSongsFinished(List<Song> songs) {\n LogUtils.i(TAG, \"onLoadSongsFinished count : \" + songs.size());\n\n if (mView != null) {\n if (mView.isActive()) {\n mView.hideLoadingView();\n\n if (songs.size() == 0) {\n Glide.with(mView.getContext()).asBitmap().load(R.drawable.ic_album)\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {\n if (mView != null) {\n mView.showArtwork(resource);\n }\n }\n });\n\n mView.showEmptyView();\n } else {\n Glide.with(mView.getContext()).asBitmap().load(Utils.getAlbumArtUri(songs.get(0).mAlbumId))\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {\n if (mView != null) {\n mView.showArtwork(resource);\n }\n }\n\n @Override\n public void onLoadFailed(Drawable errorDrawable) {\n super.onLoadFailed(errorDrawable);\n\n LogUtils.e(TAG, \"onLoadfailed\");\n\n if (mView != null) {\n mView.showArtwork(errorDrawable);\n }\n }\n });\n\n mView.showPlayedSongs(songs);\n }\n }\n }\n }\n\n public static List<Song> getRecentlyPlaySongs() {\n return SongsPresenter.getSongsForCursor(makeRecentPlayCursor(), false);\n }\n\n /**\n * 获取最近播放歌曲的cursor\n *\n * @return\n */\n public static SortedCursor makeRecentPlayCursor() {\n\n Cursor songs = RecentlyPlay.getInstance(MusicApplication.getContext()).queryRecentIds(null);\n\n try {\n return SongsPresenter.makeSortedCursor(MusicApplication.getContext(), songs,\n songs.getColumnIndex(SongPlayCount.SongPlayCountColumns.ID));\n } finally {\n if (songs != null) {\n songs.close();\n }\n }\n }\n}", "public class SongsPresenter implements SongsContract.Presenter {\n private static final String TAG = SongsPresenter.class.getSimpleName();\n private static final String[] AUDIO_PROJECTION = new String[]{\n /* 0 */\n MediaStore.Audio.Media._ID,\n /* 1 */\n MediaStore.Audio.Media.TITLE,\n /* 2 */\n MediaStore.Audio.Media.ARTIST,\n /* 3 */\n MediaStore.Audio.Media.ALBUM_ID,\n /* 4 */\n MediaStore.Audio.Media.ALBUM,\n /* 5 */\n MediaStore.Audio.Media.DURATION\n };\n @NonNull\n private SongsContract.View mView;\n\n private CompositeDisposable mDisposables;\n\n private MusicRepository mRepository;\n\n public SongsPresenter(@NonNull SongsContract.View view, MusicRepository repository) {\n mDisposables = new CompositeDisposable();\n mRepository = repository;\n mView = view;\n mView.setPresenter(this);\n }\n\n @Override\n public void subscribe() {\n LogUtils.i(TAG, \"subscribe\");\n loadSongs();\n }\n\n @Override\n public void unSubscribe() {\n LogUtils.i(TAG, \"unSubscribe\");\n mDisposables.clear();\n }\n\n @Override\n public void loadSongs() {\n mDisposables.clear();\n\n Disposable disposable = mRepository.getAllSongs().subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribeWith(new DisposableSubscriber<List<Song>>() {\n @Override\n public void onError(Throwable throwable) {\n LogUtils.e(TAG, \"onError :\" + throwable.toString());\n }\n\n @Override\n public void onComplete() {\n LogUtils.i(TAG, \"onCompleted\");\n }\n\n @Override\n public void onNext(List<Song> songs) {\n onLoadSongsFinished(songs);\n }\n });\n\n mDisposables.add(disposable);\n }\n\n @Override\n public void onLoadSongsFinished(List<Song> songs) {\n if (mView == null) {\n return;\n }\n\n if (mView.isActive()) {\n mView.hideLoadingView();\n\n if (songs.size() == 0) {\n mView.showEmptyView();\n } else {\n mView.showSongs(songs);\n }\n }\n }\n\n public static List<Song> getAllSongs() {\n LogUtils.i(TAG, \"getAllSongs\");\n\n return getSongsForCursor(makeSongCursor(), false);\n }\n\n public static List<Song> getSongsForCursor(Cursor cursor, boolean isSingle) {\n List<Song> songs = new ArrayList<>();\n // Gather the data\n if (cursor != null && cursor.moveToFirst()) {\n do {\n // Copy the song Id\n final long id = cursor.getLong(0);\n\n // Copy the song name\n final String songName = cursor.getString(1);\n\n // Copy the artist name\n final String artist = cursor.getString(2);\n\n // Copy the album id\n final long albumId = cursor.getLong(3);\n\n // Copy the album name\n final String album = cursor.getString(4);\n\n // Copy the duration\n final long duration = cursor.getLong(5);\n\n // Convert the duration into seconds\n final int durationInSecs = (int) duration / 1000;\n\n // Create a new song\n final Song song = new Song(id, songName, artist, album, albumId,\n durationInSecs);\n\n songs.add(song);\n } while (cursor.moveToNext() && !isSingle);\n }\n // Close the cursor\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n return songs;\n }\n\n public static final Cursor makeSongCursor() {\n Cursor cursor = MusicApplication.getContext().getContentResolver().query(Constants.SONG_URI,\n AUDIO_PROJECTION, Constants.MUSIC_ONLY_SELECTION, null,\n MediaStore.Audio.Media.DEFAULT_SORT_ORDER);\n return cursor;\n }\n\n public static Cursor makeSongCursor(Context context, String selection, String[] paramArrayOfString) {\n //final String songSortOrder = PreferenceUtils.getInstance(context).getSongSortOrder();\n return makeSongCursor(context, selection, paramArrayOfString,\n MediaStore.Audio.Media.DEFAULT_SORT_ORDER);\n }\n\n private static Cursor makeSongCursor(Context context, String selection, String[] paramArrayOfString, String sortOrder) {\n if (!TextUtils.isEmpty(selection)) {\n selection = Constants.MUSIC_ONLY_SELECTION + \" AND \" + selection;\n }\n return context.getContentResolver().query(Constants.SONG_URI,\n AUDIO_PROJECTION, selection, paramArrayOfString, sortOrder);\n\n }\n\n /**\n * 根据包含song id的cursor,获取排序好的song cursor\n *\n * @param context\n * @param cursor\n * @param idColumn\n * @return\n */\n public static SortedCursor makeSortedCursor(final Context context, final Cursor cursor,\n final int idColumn) {\n if (cursor != null && cursor.moveToFirst()) {\n\n StringBuilder selection = new StringBuilder();\n selection.append(BaseColumns._ID);\n selection.append(\" IN (\");\n\n long[] order = new long[cursor.getCount()];\n\n long id = cursor.getLong(idColumn);\n selection.append(id);\n order[cursor.getPosition()] = id;\n\n while (cursor.moveToNext()) {\n selection.append(\",\");\n\n id = cursor.getLong(idColumn);\n order[cursor.getPosition()] = id;\n selection.append(String.valueOf(id));\n }\n\n selection.append(\")\");\n\n Cursor songCursor = makeSongCursor(context, selection.toString(), null);\n if (songCursor != null) {\n return new SortedCursor(songCursor, order, BaseColumns._ID, null);\n }\n }\n\n if (cursor != null) {\n cursor.close();\n }\n\n return null;\n }\n}", "public class Constants {\n /* Name of database file */\n public static final String DATABASENAME = \"komamusic.db\";\n\n public static final String MUSIC_PACKAGE_NAME = \"com.koma.music\";\n public static final String DETAIL_PACKAGE_NAME = \"com.koma.music.detail.DetailsActivity\";\n\n public static Uri PLAYLIST_URI = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;\n public static Uri SONG_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;\n public static Uri ARTIST_URI = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;\n public static Uri ALBUM_URI = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;\n public static Uri GENRES_URI = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;\n\n public static final Uri ARTWORK_URI = Uri.parse(\"content://media/external/audio/albumart\");\n\n public static int REFRESH_TIME = 500;\n\n public static final String MUSIC_ONLY_SELECTION = MediaStore.Audio.AudioColumns.IS_MUSIC + \"=1\"\n + \" AND \" + MediaStore.Audio.AudioColumns.TITLE + \" != ''\";\n\n //Detail\n public static final String WHICH_DETAIL_PAGE = \"which_detail_page\";\n public static final int RECENTLY_ADDED = 0x00;\n public static final int RECENTLY_PLAYED = RECENTLY_ADDED + 1;\n public static final int MY_FAVORITE = RECENTLY_PLAYED + 1;\n public static final int ALBUM_DETAIL = MY_FAVORITE + 1;\n public static final int ARTIST_DETAIL = ALBUM_DETAIL + 1;\n\n //AlbumDetail\n public static final String TRANSITION_NAME = \"transition_name\";\n public static final String ALBUM_ID = \"album_id\";\n public static final String ALBUM_NAME = \"album_name\";\n\n //ArtistDetail\n public static final String ARTIST_ID = \"artist_id\";\n public static final String ARTIST_NAME = \"artist_name\";\n\n //Category artwork\n public static final String CATEGORY_RECENTLY_ADDED = \"category_recently_added\";\n public static final String CATEGORY_RECENTLY_PLAYED = \"category_recently_played\";\n public static final String CATEGORY_MY_FAVORITE = \"category_my_favorite\";\n public static final String CATEGORY_ARTIST = \"category_artist\";\n\n //MyFavorite\n public static final String SONG_ID = \"song_id\";\n}", "public class LogUtils {\n private static final boolean IS_DEBUG = true;\n private static final String TAG = \"KomaMusic\";\n\n public static void d(String tag, String msg) {\n if (IS_DEBUG) {\n Log.d(TAG, buildString(tag, msg));\n }\n }\n\n public static void i(String tag, String msg) {\n if (IS_DEBUG) {\n Log.i(TAG, buildString(tag, msg));\n }\n }\n\n public static void e(String tag, String msg) {\n if (IS_DEBUG) {\n Log.e(TAG, buildString(tag, msg));\n }\n }\n\n private static String buildString(String tag, String msg) {\n StringBuilder sb = new StringBuilder(tag);\n sb.append(\"----\");\n sb.append(msg);\n return sb.toString();\n }\n}", "public class Utils {\n /**\n * 阅读习惯是否是从右到左\n *\n * @return true:从右到左 false:从左到右\n */\n public static boolean isRTL() {\n final Locale locale = Locale.getDefault();\n return TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL;\n }\n\n public static Uri getAlbumArtUri(long paramInt) {\n return ContentUris.withAppendedId(Uri.parse(\"content://media/external/audio/albumart\"), paramInt);\n }\n\n /**\n * Used to make number of labels for the number of artists, albums, songs,\n * genres, and playlists.\n *\n * @param context The {@link Context} to use.\n * @param pluralInt The ID of the plural string to use.\n * @param number The number of artists, albums, songs, genres, or playlists.\n * @return A {@link String} used as a label for the number of artists,\n * albums, songs, genres, and playlists.\n */\n public static final String makeLabel(final Context context, final int pluralInt,\n final int number) {\n return context.getResources().getQuantityString(pluralInt, number, number);\n }\n}" ]
import java.io.InputStream; import android.content.ContentResolver; import android.net.Uri; import com.bumptech.glide.Priority; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.data.DataFetcher; import com.koma.music.MusicApplication; import com.koma.music.album.AlbumsPresenter; import com.koma.music.playlist.myfavorite.MyFavoritePresenter; import com.koma.music.playlist.recentlyadd.RecentlyAddedPresenter; import com.koma.music.playlist.recentlyplay.RecentlyPlayPresenter; import com.koma.music.song.SongsPresenter; import com.koma.music.util.Constants; import com.koma.music.util.LogUtils; import com.koma.music.util.Utils; import java.io.FileNotFoundException; import java.io.IOException;
/* * Copyright (C) 2017 Koma MJ * * 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.koma.music.helper; /** * Created by koma on 5/11/17. */ public class ArtworkDataFetcher implements DataFetcher<InputStream> { private static final String TAG = ArtworkDataFetcher.class.getSimpleName(); private InputStream mInputStream; private String mCategory; public ArtworkDataFetcher(String category) { mCategory = category; } @Override public void loadData(Priority priority, DataCallback<? super InputStream> callback) { try { mInputStream = openThumbInputStream(); } catch (FileNotFoundException e) { LogUtils.d(TAG, "Failed to find thumbnail file," + e.toString()); callback.onLoadFailed(e); return; } callback.onDataReady(mInputStream); } private InputStream openThumbInputStream() throws FileNotFoundException { ContentResolver contentResolver = MusicApplication.getContext().getContentResolver(); Uri thumbnailUri; switch (mCategory) { case Constants.CATEGORY_RECENTLY_ADDED:
thumbnailUri = Utils.getAlbumArtUri(SongsPresenter.getSongsForCursor(
5
ragnraok/JParserUtil
src/main/java/com/ragnarok/jparseutil/memberparser/TypeParser.java
[ "public class SourceInfo {\n \n public static final String TAG = \"JParserUtil.SourceInfo\";\n \n private String fileName;\n private List<String> importClassNames = new ArrayList<>();\n private String packageName = null;\n \n private List<String> asteriskImports = new ArrayList<>();\n \n private Map<String, AnnotationInfo> annotationInfos = new TreeMap<>();\n \n /**\n * all class informations\n */\n private Map<String, ClassInfo> classInfos = new TreeMap<>();\n \n public void setFilename(String filename) {\n this.fileName = filename;\n }\n \n public String getFilename() {\n return this.fileName;\n }\n \n public void addImports(String importClass) {\n this.importClassNames.add(importClass);\n if (importClass.endsWith(\".*\")) {\n this.asteriskImports.add(importClass);\n }\n }\n \n public List<String> getImports() {\n return this.importClassNames;\n }\n \n public List<String> getAsteriskImports() {\n return this.asteriskImports;\n }\n \n public void setPackageName(String packageName) {\n this.packageName = packageName;\n }\n \n public String getPackageName() {\n return this.packageName;\n }\n \n public void addClassInfo(ClassInfo clazz) {\n if (clazz != null) {\n// Log.d(TAG, \"addClassInfo, name: %s, size: %d\", clazz.getSimpleName(), this.classInfos.size());\n this.classInfos.put(clazz.getQualifiedName(), clazz);\n }\n }\n \n public boolean isContainClass(String simpleClassName) {\n for (ClassInfo clazz : classInfos.values()) {\n if (clazz.getSimpleName().equals(simpleClassName)) {\n return true;\n }\n }\n return false;\n }\n \n public ClassInfo getClassInfoByQualifiedName(String qualifiedName) {\n return classInfos.get(qualifiedName);\n }\n \n public ClassInfo getClassInfoBySimpleName(String simpleName) {\n for (ClassInfo clazz : classInfos.values()) {\n if (clazz.getSimpleName().equals(simpleName)) {\n return clazz;\n }\n }\n return null;\n }\n \n public ClassInfo getClassInfoBySuffixName(String suffixName) {\n for (ClassInfo clazz : classInfos.values()) {\n if (clazz.getQualifiedName().endsWith(\".\" + suffixName)) {\n return clazz;\n }\n }\n return null;\n }\n \n public void updateClassInfoByQualifiedName(String qualifiedName, ClassInfo newClazz) {\n if (classInfos.containsKey(qualifiedName)) {\n classInfos.put(qualifiedName, newClazz);\n }\n }\n \n public List<ClassInfo> getAllClass() {\n List<ClassInfo> result = new ArrayList<>(this.classInfos.size());\n result.addAll(classInfos.values());\n return result;\n }\n \n public String dumpClazz() {\n String result = \"\";\n for (ClassInfo clazz : classInfos.values()) {\n result += clazz.getSimpleName() + \", \";\n }\n return result; \n }\n \n public void putAnnotaiotn(AnnotationInfo annotationInfo) {\n this.annotationInfos.put(annotationInfo.getQualifiedName(), annotationInfo);\n }\n \n public List<AnnotationInfo> getAllAnnotations() {\n List<AnnotationInfo> result = new ArrayList<>(this.annotationInfos.size());\n result.addAll(annotationInfos.values());\n return result;\n }\n \n public AnnotationInfo getAnnotationInfoByQualifiedName(String qualifiedName) {\n return annotationInfos.get(qualifiedName);\n }\n \n public void updateAnnotationByQualifiedName(String qualifiedName, AnnotationInfo annotationInfo) {\n if (annotationInfos.containsKey(qualifiedName)) {\n annotationInfos.put(qualifiedName, annotationInfo);\n }\n }\n\n @Override\n public String toString() {\n StringBuilder result = new StringBuilder();\n result.append(String.format(\"{SourceInfo, filename: %s, packageName: %s\", fileName, packageName));\n result.append(\"\\n\");\n if (importClassNames.size() > 0) {\n for (String className : importClassNames) {\n result.append(String.format(\"importClass: %s, \", className));\n }\n }\n result.append(\"\\n\");\n if (annotationInfos.size() > 0) {\n for (AnnotationInfo annotationInfo : annotationInfos.values()) {\n result.append(annotationInfo.toString());\n result.append(\"\\n\");\n }\n }\n if (classInfos.size() > 0) {\n for (ClassInfo classInfo : classInfos.values()) {\n result.append(classInfo.toString());\n result.append(\"\\n\");\n }\n }\n result.append(\"}\");\n return result.toString();\n }\n}", "public class Type {\n \n public static final String TAG = \"JParserUtil.Type\";\n \n private String typeName; // fully qualified\n private boolean isPrimitive = false;\n private boolean isArray = false;\n private Type arrayElementType = null; // not null if isArray is true\n \n private boolean isUpdatedToQualifiedTypeName = false;\n \n private SourceInfo containedSourceInfo;\n \n public void setTypeName(String typeName) {\n this.typeName = typeName;\n }\n \n public String getTypeName() {\n if (CodeInfo.isParseFinish() && \n !isUpdatedToQualifiedTypeName && !Util.isPrimitive(typeName) && !Util.isVoidType(typeName) && !isArray) {\n if (this.typeName != null) {\n typeName = Util.parseTypeFromSourceInfo(containedSourceInfo, typeName);\n if (typeName != null && typeName.contains(\".\")) {\n isUpdatedToQualifiedTypeName = true;\n } else {\n if (!isUpdatedToQualifiedTypeName) { // not in import, sample package of this containedSourceInfo\n typeName = containedSourceInfo.getPackageName() + \".\" + typeName;\n isUpdatedToQualifiedTypeName = true;\n }\n }\n }\n }\n return this.typeName;\n }\n \n public void setPrimitive(boolean isPrimitive) {\n this.isPrimitive = isPrimitive;\n }\n \n public boolean isPrimitive() {\n return this.isPrimitive;\n }\n \n public void setArray(boolean isArray) {\n this.isArray = isArray;\n }\n \n public boolean isArray() {\n return this.isArray;\n }\n \n public void setArrayElementType(Type elemType) {\n this.arrayElementType = elemType;\n }\n \n public Type getArrayElementType() {\n return this.arrayElementType;\n }\n \n public void setContainedSourceInfo(SourceInfo sourceInfo) {\n this.containedSourceInfo = sourceInfo;\n }\n\n @Override\n public String toString() {\n if (!isArray) {\n return String.format(\"{type: %s, isPrimitive: %b, isArray: %b}\", getTypeName(), isPrimitive(), isArray());\n } else {\n return String.format(\"{type: %s, isPrimitive: %b, isArray: %b, arrayElemType: %s}\", getTypeName(), isPrimitive(), isArray(), arrayElementType);\n }\n }\n \n \n}", "public class Log {\n\n /**\n * log level definitions\n */\n public static final int VERBOSE = 1;\n public static final int DEBUG = 2;\n public static final int INFO = 3;\n public static final int WARNING = 4;\n public static final int ERROR = 5;\n \n private static final String VERBOSE_COLOR = \"\\u001B[37m\";\n private static final String DEBUG_COLOR = \"\\u001B[34m\";\n private static final String INFO_COLOR = \"\\u001B[32m\";\n private static final String WARNING_COLOR = \"\\u001B[36m\";\n private static final String ERROR_COLOR = \"\\u001B[31m\";\n private static final String[] LOG_TEXT_COLOR = new String[] {VERBOSE_COLOR, DEBUG_COLOR, INFO_COLOR, WARNING_COLOR, ERROR_COLOR};\n private static final String ANSI_RESET = \"\\u001B[0m\";\n \n private static final String LOG_FORMAT = \"[%s/%s:%s] %s\"; // time/level: TAG content\n \n public static int MAX_SHOW_LOG_LEVEL = DEBUG;\n \n public static Set<String> SHOW_LOG_TAG = new HashSet<>();\n \n static {\n SHOW_LOG_TAG.add(SimpleJavaFileScanner.TAG);\n }\n \n public static void setMaxLogLevel(int maxLogLevel) {\n MAX_SHOW_LOG_LEVEL = maxLogLevel;\n }\n \n public static void addShowLogTAG(String TAG) {\n SHOW_LOG_TAG.add(TAG);\n }\n \n public static void v(String TAG, String format, Object... args) {\n println(VERBOSE, TAG, String.format(format, args));\n }\n \n public static void d(String TAG, String format, Object... args) {\n println(DEBUG, TAG, String.format(format, args));\n }\n \n public static void i(String TAG, String format, Object... args) {\n println(INFO, TAG, String.format(format, args));\n }\n \n public static void w(String TAG, String format, Object... args) {\n println(WARNING, TAG, String.format(format, args));\n }\n \n public static void e(String TAG, String format, Object... args) {\n println(ERROR, TAG, String.format(format, args));\n } \n \n private static String getCurrentLogTime() {\n return new SimpleDateFormat(\"K:mm:ss:SSS\").format(new Date());\n }\n \n private static String logLevelToString(int level) {\n switch (level) {\n case VERBOSE:\n return \"V\";\n case DEBUG:\n return \"D\";\n case INFO:\n return \"I\";\n case WARNING:\n return \"W\";\n case ERROR:\n return \"E\";\n }\n return \"\";\n }\n \n private static void println(int level, String tag, String content) {\n if (level >= MAX_SHOW_LOG_LEVEL && SHOW_LOG_TAG.contains(tag)) {\n System.out.println(String.format(LOG_TEXT_COLOR[level - 1] + LOG_FORMAT + ANSI_RESET, getCurrentLogTime(), logLevelToString(level), tag, content));\n }\n }\n}", "public class Primitive {\n public static String INT_TYPE = \"int\";\n public static String INTEGER_TYPE = \"Integer\";\n public static String STRING_TYPE = \"String\";\n public static String FLOAT_TYPE = \"float\";\n public static String FLOAT_PKG_TYPE = \"Float\";\n public static String DOUBLE_TYPE = \"double\";\n public static String DOUBLE_PKG_TYPE = \"Double\";\n public static String CHAR_TYPE = \"char\";\n public static String CHARACTER_TYPE = \"Character\";\n public static String LONG_TYPE = \"long\";\n public static String LONG_PKG_TYPE = \"Long\";\n public static String BOOLEAN_TYPE = \"boolean\";\n public static String BOOLEAN_PKG_TYPE = \"Boolean\";\n public static String NUMBER_TYPE = \"Number\";\n\n public static String[] PrimitiveTypes = new String[] {INT_TYPE, INTEGER_TYPE, STRING_TYPE,\n FLOAT_TYPE, FLOAT_PKG_TYPE, DOUBLE_TYPE, DOUBLE_PKG_TYPE, CHAR_TYPE, CHARACTER_TYPE,\n LONG_TYPE, LONG_PKG_TYPE, BOOLEAN_TYPE, BOOLEAN_PKG_TYPE, NUMBER_TYPE};\n \n public static String VOID_TYPE = \"void\";\n}", "public class Util {\n \n public static final String JAVA_FILE_SUFFIX = \".java\";\n \n public static boolean isPrimitive(String variableTypeName) {\n if (variableTypeName == null) {\n return false;\n }\n for (String type : Primitive.PrimitiveTypes) {\n if (type.equals(variableTypeName)) {\n return true;\n }\n }\n return false;\n }\n \n public static boolean isVoidType(String type) {\n if (type == null) {\n return false;\n }\n return type.equalsIgnoreCase(Primitive.VOID_TYPE);\n }\n\n // parse type from source imports\n public static String parseTypeFromSourceInfo(SourceInfo sourceInfo, String type) {\n if (isPrimitive(type)) {\n return type;\n }\n \n\n for (String className : sourceInfo.getImports()) {\n// String simpleClassName = className.substring(className.lastIndexOf(\".\") + 1);\n// if (simpleClassName.equals(type)) {\n// return className;\n// }\n if (!className.endsWith(\"*\")) {\n String simpleClassName = className.substring(className.lastIndexOf(\".\") + 1);\n if (simpleClassName.equals(type)) {\n return className;\n }\n } else {\n // import *\n String fullQualifiedClassName = ReferenceSourceMap.getInstance().searchClassNameByPrefixAndSimpleClassName(className, type);\n if (fullQualifiedClassName != null) {\n return fullQualifiedClassName;\n }\n }\n }\n \n // parse for annotation type\n for (AnnotationInfo annotationInfo : sourceInfo.getAllAnnotations()) {\n String name = annotationInfo.getQualifiedName();\n if (name != null && name.endsWith(type)) {\n return name;\n }\n }\n\n // for inner class variable, currently may not add in sourceInfo, so we will\n // update type later\n ClassInfo classInfo = sourceInfo.getClassInfoBySuffixName(type);\n if (classInfo != null) {\n return classInfo.getQualifiedName();\n }\n\n return type; // is import from java.lang\n }\n \n public static Object getValueFromLiteral(LiteralExpr literal) {\n if (literal instanceof BooleanLiteralExpr) {\n return ((BooleanLiteralExpr) literal).getValue();\n } else if (literal instanceof IntegerLiteralExpr) {\n return ((IntegerLiteralExpr) literal).getValue();\n } else if (literal instanceof LongLiteralExpr) {\n return ((LongLiteralExpr) literal).getValue();\n } else if (literal instanceof DoubleLiteralExpr) {\n return ((DoubleLiteralExpr) literal).getValue();\n } else if (literal instanceof CharLiteralExpr) {\n return ((CharLiteralExpr) literal).getValue();\n } else if (literal instanceof NullLiteralExpr) {\n return null;\n } else if (literal instanceof StringLiteralExpr) {\n return ((StringLiteralExpr) literal).getValue();\n } else {\n return literal.toString();\n }\n }\n \n public static String buildClassName(String prefix, String simpleName) {\n simpleName = simpleName.replace(\".\", \"\");\n if (prefix.endsWith(\".\")) {\n return prefix + simpleName;\n } else {\n return prefix + \".\" + simpleName;\n }\n }\n \n public static boolean isStringInFile(String filename, List<String> stringList) {\n String content = getFileContent(filename);\n if (content == null) {\n return false;\n }\n for (String str : stringList) {\n if (content.contains(str)) {\n return true;\n }\n }\n return false;\n }\n \n public static String getFileContent(String filename) {\n File file;\n FileChannel channel;\n MappedByteBuffer buffer;\n\n file = new File(filename);\n FileInputStream fin = null;\n try {\n fin = new FileInputStream(file);\n channel = fin.getChannel();\n buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());\n byte[] contentBytes = new byte[buffer.remaining()];\n buffer.get(contentBytes);\n String content = new String(contentBytes);\n return content;\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if (fin != null) {\n try {\n fin.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n return null;\n }\n}" ]
import com.github.javaparser.ast.type.ReferenceType; import com.ragnarok.jparseutil.dataobject.SourceInfo; import com.ragnarok.jparseutil.dataobject.Type; import com.ragnarok.jparseutil.util.Log; import com.ragnarok.jparseutil.util.Primitive; import com.ragnarok.jparseutil.util.Util; import com.sun.source.tree.Tree; import com.sun.tools.javac.tree.JCTree;
package com.ragnarok.jparseutil.memberparser; /** * Created by ragnarok on 15/6/28. * parser for the variable type */ public class TypeParser { public static final String TAG = "JParserUtil.TypeParser"; public static Type parseType(SourceInfo sourceInfo, com.github.javaparser.ast.type.Type typeElement, String typeName) { if (typeElement != null) { // Log.d(TAG, "parseTypeFromSourceInfo, typeElement class: %s", typeElement.getClass().getSimpleName()); } boolean isArray = typeElement != null && typeElement instanceof ReferenceType && ((ReferenceType)typeElement).getArrayCount() > 0; Type result = new Type(); result.setContainedSourceInfo(sourceInfo);
if (Util.isPrimitive(typeName)) {
4
ailab-uniud/distiller-CORE
src/main/java/it/uniud/ailab/dcore/annotation/annotators/StatisticalAnnotator.java
[ "public interface Annotator extends Stage {\r\n \r\n /**\r\n * The abstract annotation method. All classes that perform some kind of \r\n * annotation (splitting, PoS tagging, entity linking...) must inherit from\r\n * Annotator. They annotate the blackboard given as first parameter or a \r\n * component of the blackboard, given as second parameter. \r\n * \r\n * @param blackboard blackboard to annotate\r\n * @param component component to annotate.\r\n */\r\n public void annotate(Blackboard blackboard, DocumentComponent component);\r\n \r\n \r\n @Override\r\n default void run(Blackboard b) {\r\n this.annotate(b, b.getStructure());\r\n } \r\n \r\n}\r", "public class Blackboard {\r\n\r\n /**\r\n * The default document identifier.\r\n */\r\n private static final String DEFAULT_DOCUMENT_ID = \"DocumentRoot\";\r\n\r\n /**\r\n * The full raw text of the document.\r\n */\r\n private String rawText;\r\n\r\n /**\r\n * The root block of the document.\r\n */\r\n private DocumentComponent document;\r\n\r\n /**\r\n * Container for the n-grams of the document. Every n-gram is part of a\r\n * specific list identifying the type of n-gram. The types of n-grams are\r\n * the key for searching in the main n-gram list.\r\n */\r\n private Map<String, Map<String, Gram>> generalNGramsContainer;\r\n\r\n /**\r\n * Document-wide annotations. This space can be used to add annotations that\r\n * belong to the whole document, as for example extracted concepts, or\r\n * tagset used by a POS-tagger, or the overall sentiment.\r\n */\r\n private List<Annotation> annotations;\r\n\r\n /**\r\n * Instantiates an empty blackboard.\r\n */\r\n public Blackboard() {\r\n createDocument(\"\");\r\n }\r\n\r\n /**\r\n * Initializes the blackboard with a new document. This will destroy any\r\n * information previously held by the blackboard.\r\n *\r\n * @param rawText the text of the new document.\r\n * @param documentId the output-friendly identifier of the document\r\n */\r\n public final void createDocument(String rawText, String documentId) {\r\n this.rawText = rawText;\r\n this.document = new DocumentComposite(rawText, documentId);\r\n this.generalNGramsContainer = new HashMap<>();\r\n this.annotations = new ArrayList<>();\r\n }\r\n\r\n /**\r\n * Initializes the blackboard with a new document. This will destroy any\r\n * information previously held by the blackboard.\r\n *\r\n * @param rawText the text of the new document.\r\n */\r\n public final void createDocument(String rawText) {\r\n this.rawText = rawText;\r\n this.document = new DocumentComposite(rawText, DEFAULT_DOCUMENT_ID);\r\n this.generalNGramsContainer = new HashMap<>();\r\n this.annotations = new ArrayList<>();\r\n }\r\n\r\n /**\r\n * Gets the root of the document.\r\n *\r\n * @return the {@link it.uniud.ailab.dcore.persistence.DocumentComponent}\r\n * root object.\r\n */\r\n @JsonIgnore\r\n public DocumentComponent getStructure() {\r\n return document;\r\n }\r\n\r\n /**\r\n * Gets the raw text (i.e. unprocessed) of the document.\r\n *\r\n * @return the original document string.\r\n */\r\n public String getText() {\r\n return rawText;\r\n }\r\n\r\n /**\r\n * Adds a Gram in the Gram Container, merging grams with the same\r\n * identifier. If the gram is already present, the method updates it adding\r\n * the new occurrence. Annotations of the new gram are <b>not</b> merged\r\n * into the old gram. This is because it's good practice to annotate grams\r\n * only when they've <b>all</b> been added into the blackboard.\r\n *\r\n * @param unit the concept unit where the gram appears\r\n * @param newGram the gram to add\r\n */\r\n public void addGram(DocumentComponent unit, Gram newGram) {\r\n\r\n Map<String, Gram> grams = generalNGramsContainer.get(newGram.getType());\r\n if (grams == null) {\r\n grams = new HashMap<>();\r\n }\r\n Gram gram = grams.get(newGram.getIdentifier());\r\n\r\n // Deep clone the object instead of referencing the found one.\r\n // this way, we're free to modify it by adding annotations without\r\n // modifying the old object.\r\n if (gram == null) {\r\n Gram cloned = (new Cloner()).deepClone(newGram);\r\n grams.put(cloned.getIdentifier(), cloned);\r\n gram = cloned;\r\n } else {\r\n // add the surface of the new gram\r\n gram.addSurfaces(newGram.getSurfaces(), newGram.getTokenLists());\r\n }\r\n\r\n gram.addAppaerance(unit);\r\n unit.addGram(gram);\r\n generalNGramsContainer.put(newGram.getType(), grams);\r\n }\r\n\r\n public void addGram(Gram newGram) {\r\n\r\n Map<String, Gram> grams = generalNGramsContainer.get(newGram.getType());\r\n if (grams == null) {\r\n grams = new HashMap<>();\r\n }\r\n Gram gram = grams.get(newGram.getIdentifier());\r\n\r\n // Deep clone the object instead of referencing the found one.\r\n // this way, we're free to modify it by adding annotations without\r\n // modifying the old object.\r\n if (gram == null) {\r\n Gram cloned = (new Cloner()).deepClone(newGram);\r\n grams.put(cloned.getIdentifier(), cloned);\r\n } else {\r\n // add the surface of the new gram\r\n gram.addSurfaces(newGram.getSurfaces(), newGram.getTokenLists());\r\n }\r\n\r\n generalNGramsContainer.put(newGram.getType(), grams);\r\n }\r\n \r\n /**\r\n * Get the all the different kind of grams found in the document. This\r\n * grams are divided by type, stored in a Map using their identifier as \r\n * key.\r\n * \r\n * @return all the maps found in the document.\r\n */\r\n public Map<String,Map<String,Gram>> getGrams() {\r\n return generalNGramsContainer;\r\n }\r\n\r\n /**\r\n * Get all the grams of a given type found in the blackboard.\r\n * \r\n * @param <T> the type of the grams to achieve\r\n * @param gramType the identifier of the gram type\r\n * @return a collection with all the grams with match type and identifier,\r\n * null if there is no match.\r\n */\r\n public <T> Collection<T> getGramsByType(String gramType) { \r\n return \r\n generalNGramsContainer.containsKey(gramType) ?\r\n (Collection<T>)generalNGramsContainer.get(gramType).values() :\r\n null;\r\n }\r\n\r\n /**\r\n * Retrieves the keyphrases found in the document.\r\n *\r\n * @return a collection of\r\n * {@link it.uniud.ailab.dcore.persistence.Keyphrase}s.\r\n */\r\n @Deprecated\r\n @JsonIgnore\r\n public List<Gram> getKeyphrases() {\r\n\r\n Map<String, Gram> kps = generalNGramsContainer.get(Keyphrase.KEYPHRASE);\r\n return kps != null ? new ArrayList(kps.values()) : new ArrayList();\r\n }\r\n\r\n /**\r\n * Removes a keyphrase from the document because it's no more relevant, or\r\n * useful, or for whatever reason an annotator thinks so.\r\n *\r\n * @param g the gram to remove.\r\n */\r\n @Deprecated\r\n public void removeKeyphrase(Keyphrase g) {\r\n removeGram(Keyphrase.KEYPHRASE,g);\r\n }\r\n \r\n /**\r\n * Removes a gram from the document because it's no more relevant, or\r\n * useful, or for whatever reason an annotator thinks so.\r\n *\r\n * @param type the type of the gram to remove\r\n * @param g the gram to remove.\r\n */\r\n public void removeGram(String type,Gram g) {\r\n generalNGramsContainer.get(type)\r\n .remove(g.getIdentifier());\r\n\r\n for (Sentence s : DocumentUtils.getSentences(document)) {\r\n s.removeGram(g);\r\n }\r\n }\r\n\r\n /**\r\n * Adds an annotation in the blackboard.\r\n *\r\n * @param a the annotation to add\r\n */\r\n public void addAnnotation(Annotation a) {\r\n annotations.add(a);\r\n }\r\n\r\n /**\r\n * Get all the annotations.\r\n *\r\n * @return the annotations stored in the blackboard\r\n */\r\n public List<Annotation> getAnnotations() {\r\n return annotations;\r\n }\r\n\r\n /**\r\n * Gets the annotations produced by a specific annotator.\r\n *\r\n * @param annotator the annotator identifier\r\n * @return the annotations produced by the specified annotator\r\n */\r\n public List<Annotation> getAnnotations(String annotator) {\r\n return annotations.stream().filter((a)\r\n -> (a.getAnnotator().equals(annotator))).\r\n collect(Collectors.toList());\r\n }\r\n\r\n /**\r\n * Remove an annotation from the blackboard.\r\n * \r\n * @param ann the annotation to remove.\r\n */\r\n public void removeAnnotation(Annotation ann) {\r\n annotations.remove(ann);\r\n }\r\n \r\n /**\r\n * Get the language of the document root.\r\n * \r\n * @return the language of the document root.\r\n */\r\n public String getDocumentLanguage() {\r\n return getStructure().getLanguage().getLanguage();\r\n }\r\n\r\n}\r", "public class DefaultAnnotations {\n \n public static final String SENTENCE_INDEX = \"SentenceIndex\";\n \n public static final String SENTENCE_COUNT = \"SentenceCount\";\n \n public static final String CHAR_COUNT = \"CharCount\";\n \n public static final String WORD_COUNT = \"WordCount\";\n \n public static final String PHRASES_COUNT = \"PhrasesCount\";\n \n public static final String IS_NER = \"IsANer\";\n \n}", "public class FeatureAnnotation \n extends Annotation\n implements ScoredAnnotation {\n \n /**\n * A feature.\n * \n * @param annotator the annotator that generated the feature.\n * @param score the value of the feature.\n */\n public FeatureAnnotation(String annotator,double score) {\n super(annotator);\n \n super.addNumber(score);\n }\n \n /**\n * Get the value of the feature.\n * \n * @return the value of the feature\n */\n @Override\n public double getScore() {\n return super.getNumberAt(0).doubleValue();\n }\n}", "public abstract class DocumentComponent extends Annotable {\n\n private final String text;\n private Locale language;\n\n /**\n * Creates a document component.\n *\n * @param text the text of the component\n * @param language the language of the component\n * @param identifier the unique identifier for the component\n */\n public DocumentComponent(String text, Locale language, String identifier) {\n super(identifier);\n this.text = text;\n this.language = language;\n }\n\n // <editor-fold desc=\"getters and setters\">\n /**\n * Returns the text of the component\n *\n * @return the text of the component.\n */\n public String getText() {\n return text;\n }\n\n /**\n * Sets the language of the component.\n *\n * @param language the language of the component\n */\n public void setLanguage(Locale language) {\n this.language = language;\n if (hasComponents()) {\n for (DocumentComponent c : getComponents()) {\n c.setLanguage(language);\n }\n }\n }\n\n /**\n * Returns the language of the component.\n *\n * @return the language of the component.\n * @see <a href=\"http://tools.ietf.org/html/rfc5646\">RFC5646</a>\n * specification to know about language tags used by Java.\n */\n public Locale getLanguage() {\n return this.language;\n }\n\n /**\n * Check if the component is a leaf ( so it can be a\n * {@link it.uniud.ailab.dcore.persistence.Sentence}), or if it has\n * children, so it's surely a\n * {@link it.uniud.ailab.dcore.persistence.DocumentComposite}.\n *\n * @return true if the component has children; otherwise false.\n */\n public boolean hasComponents() {\n List<DocumentComponent> comps = getComponents();\n return !(comps == null);\n }\n\n // </editor-fold>\n // <editor-fold desc=\"abstract methods\">\n /**\n * Returns the children of the document component, or null if the current\n * concept unit has no children (a sentence, the leaf of the tree).\n *\n * @return the children of the document component, or null if the current\n * concept unit has no children.\n */\n public abstract List<DocumentComponent> getComponents();\n \n /**\n * Adds a gram to the component.\n *\n * @param g the gram to add\n */\n public abstract void addGram(Gram g);\n\n /**\n * Returns the gram associated with the component.\n *\n * @return the gram associated with the component.\n */\n public abstract List<Gram> getGrams();\n \n /**\n * Remote a gram from the component.\n * \n * @param g the gram tor remove\n */\n public abstract void removeGram(Gram g);\n\n // </editor-fold>\n\n /**\n * Get the string representation of the component.\n *\n * @return the string that represent the component (which has been set in\n * the constructor).\n */\n @Override\n public String toString() {\n return text;\n }\n\n}", "public abstract class Gram extends Annotable {\n \n /**\n * The type of n-gram:it can be a concept, a keyphrase, a mention...\n */\n private final String type;\n \n /**\n * The different list of words forming the surface of the gram.\n */\n private List<List<Token>> tokenLists;\n \n /**\n * The different string representation of the gram.\n */\n private final List<String> surfaces;\n \n /**\n * The concept Units in which the gram appears.\n */\n private List<DocumentComponent> appareances;\n \n /**\n * The identifier for a GRAM object.\n */\n public static final String GRAM = \"GRAM\";\n \n /**\n * Instantiates an n-gram. Usually, the surface should be simply the the \n * concatenation of the text of the tokens. The signature can be used for \n * comparison, so be sure to generate different signatures for n-grams\n * that are different in your domain. For example, you can use the sequence \n * of the stems of the tokens, so that n-grams with the same stemmed form \n * are considered equal.\n * \n *\n * @param sequence the tokens that form the gram\n * @param identifier unique identifier of the gram.\n * @param surface the pretty-printed string representation of the gram\n * @param type the type of gram that will be generated.\n */\n public Gram(String identifier, List<Token> sequence, String surface, \n String type) {\n \n super(identifier);\n \n this.type = type;\n \n tokenLists = new ArrayList<>();\n tokenLists.add(sequence);\n \n surfaces = new ArrayList<>();\n surfaces.add(surface);\n }\n \n /**\n * Adds a surface to the n-gram. Duplicates are permitted.\n * \n * @param surface the surface to add\n * @param tokens the tokens that form the surface\n */\n public void addSurface(String surface,List<Token> tokens) {\n surfaces.add(surface);\n tokenLists.add(tokens);\n }\n \n /**\n * Adds a group of surfaces to the n-gram. Duplicates are permitted.\n * \n * @param surfaces the surface to add\n * @param tokenLists the tokens that form the surface\n */\n public void addSurfaces(List<String> surfaces,List<List<Token>> tokenLists) {\n \n if (surfaces.size() != tokenLists.size())\n throw new IllegalArgumentException(\n \"Mismatching size of surfaces and token lists.\");\n \n this.surfaces.addAll(surfaces);\n \n // note: do not use addAll. The references are lost if you don't copy\n for (List<Token> t : tokenLists) {\n this.tokenLists.add(new ArrayList<Token>(t));\n }\n }\n \n /**\n * Get the type of the Gram that depends on the type of Gram implementation.\n * \n * @return the type of gram. \n */\n public String getType(){\n return type;\n }\n\n /**\n * The tokens that form the most common surface of the gram.\n *\n * @return the tokens of the surface of the gram.\n */\n public List<Token> getTokens() {\n return tokenLists.get(surfaces.indexOf(ListUtils.mostCommon(surfaces)));\n }\n \n /**\n * Returns all the possible lists of tokens that form the gram.\n * \n * @return all the possible lists of tokens that form the gram.\n */\n @JsonIgnore\n public List<List<Token>> getTokenLists() {\n return tokenLists;\n }\n\n /**\n * The human-readable form of the gram. This is the most common surface\n * between all the surfaces associated with the gram; if there are more than\n * one, the first one that has been added to the gram is selected.\n *\n * @return the human-readable form of the gram.\n */\n public String getSurface() {\n return ListUtils.mostCommon(surfaces);\n }\n \n /**\n * Returns all the surfaces of the gram. Note: may contain \n * duplicates.\n * \n * @return all the surfaces of the gram.\n */\n @JsonIgnore\n public List<String> getSurfaces() {\n return surfaces;\n }\n \n /**\n * Adds an appearance of the gram; in other words, adds the component in\n * which the gram appears to the list of the appearances.\n *\n * @param component the component in which the gram appears\n */\n public void addAppaerance(DocumentComponent component) {\n appareances.add(component);\n }\n\n /**\n * Gets all the components in which the gram appears.\n *\n * @return all the components in which the gram appears.\n */\n @JsonIgnore\n public List<DocumentComponent> getAppaerances() {\n return appareances;\n }\n \n \n /**\n * The identifier of the gram. Please note that it is possible that two\n * grams with different surface or tokens may have the same identifier, \n * based on the policy of the class that generated the gram.\n * \n * For example, \"italian\" and \"Italy\" may have the same identifier, because\n * the identifier has been generated using the same stem \"ital\". Otherwise,\n * the identifier may be the same link on an external ontology: in this \n * case, both words may have been associated with the entity \"Italy\".\n * \n *\n * @return the signature of the gram.\n */\n @Override\n public String getIdentifier() {\n return super.getIdentifier();\n }\n \n}", "public class Keyphrase extends Gram {\n\n /**\n * The different list of words forming the surface of the gram.\n */\n private List<List<Token>> tokenLists;\n /**\n * The different string representation of the gram.\n */\n private final List<String> surfaces;\n /**\n * The concept Units in which the gram appears.\n */\n private List<DocumentComponent> appareances;\n \n /**\n * The identifier for a Keyphrase object.\n */\n public static final String KEYPHRASE = \"Keyphrase\"; \n\n /**\n * Instantiated an n-gram. Usually, the surface should be simply the the \n * concatenation of the text of the tokens. The signature can be used for \n * comparison, so be sure to generate different signatures for n-grams\n * that are different in your domain. For example, you can use the sequence \n * of the stems of the tokens, so that n-grams with the same stemmed form \n * are considered equal.\n * \n *\n * @param sequence the tokens that form the gram\n * @param identifier unique identifier of the gram.\n * @param surface the pretty-printed string representation of the gram\n */\n public Keyphrase(String identifier, List<Token> sequence, String surface) {\n \n super(identifier, sequence, surface,KEYPHRASE);\n \n tokenLists = new ArrayList<>();\n tokenLists.add(sequence);\n \n surfaces = new ArrayList<>();\n surfaces.add(surface);\n appareances = new ArrayList<>();\n }\n \n /**\n * Adds a surface to the n-gram. Duplicates are permitted.\n * \n * @param surface the surface to add\n * @param tokens the tokens that form the surface\n */\n @Override\n public void addSurface(String surface,List<Token> tokens) {\n surfaces.add(surface);\n tokenLists.add(tokens);\n }\n \n /**\n * Adds a group of surfaces to the n-gram. Duplicates are permitted.\n * \n * @param surfaces the surface to add\n * @param tokenLists the tokens that form the surface\n */\n @Override\n public void addSurfaces(List<String> surfaces,List<List<Token>> tokenLists) {\n \n if (surfaces.size() != tokenLists.size())\n throw new IllegalArgumentException(\n \"Mismatching size of surfaces and token lists.\");\n \n this.surfaces.addAll(surfaces);\n \n // note: do not use addAll. The references are lost if you don't copy\n for (List<Token> t : tokenLists) {\n this.tokenLists.add(new ArrayList<Token>(t));\n }\n }\n\n /**\n * The tokens that form the most common surface of the gram.\n *\n * @return the tokens of the surface of the gram.\n */\n @Override\n public List<Token> getTokens() {\n return tokenLists.get(surfaces.indexOf(ListUtils.mostCommon(surfaces)));\n }\n \n /**\n * Returns all the possible lists of tokens that form the gram.\n * \n * @return all the possible lists of tokens that form the gram.\n */\n @Override\n @JsonIgnore\n public List<List<Token>> getTokenLists() {\n return tokenLists;\n }\n\n /**\n * The human-readable form of the gram. This is the most common surface\n * between all the surfaces associated with the gram; if there are more than\n * one, the first one that has been added to the gram is selected.\n *\n * @return the human-readable form of the gram.\n */\n @Override\n public String getSurface() {\n return ListUtils.mostCommon(surfaces);\n }\n \n /**\n * Returns all the surfaces of the gram. Note: may contain \n * duplicates.\n * \n * @return all the surfaces of the gram.\n */\n @Override\n @JsonIgnore\n public List<String> getSurfaces() {\n return surfaces;\n }\n\n /**\n * The identifier of the gram. Please note that it is possible that two\n * grams with different surface or tokens may have the same identifier, \n * based on the policy of the class that generated the gram.\n * \n * For example, \"italian\" and \"Italy\" may have the same identifier, because\n * the identifier has been generated using the same stem \"ital\". Otherwise,\n * the identifier may be the same link on an external ontology: in this \n * case, both words may have been associated with the entity \"Italy\".\n * \n *\n * @return the signature of the gram.\n */\n @Override\n public String getIdentifier() {\n return super.getIdentifier();\n }\n\n // <editor-fold desc=\"Feature and annotation Management\">\n\n /**\n * Adds a feature to the gram.\n *\n * @param feature the identifier of the feature\n * @param value the value of the feature\n */\n public void putFeature(String feature, double value) { \n addAnnotation(new FeatureAnnotation(feature,value));\n \n }\n\n /**\n * Adds a feature to the gram,\n *\n * @param f the feature to add.\n */\n public void putFeature(FeatureAnnotation f) {\n addAnnotation(f);\n }\n\n /**\n * Check if the gram has been annotated by the annotator specified via input\n * string.\n *\n * @param featureName the name of the feature to search\n * @return true if the gram has the feature; false otherwise\n */\n public boolean hasFeature(String featureName) {\n return this.hasAnnotation(featureName);\n }\n\n /**\n * Gets the feature generated by the annotator specified via input string.\n *\n * Please note that this method makes no difference between a feature that\n * has been assigned with value 0 and a feature that has not been assigned\n * to the gram, since in both cases the value 0 will be returned.\n *\n * @param featureName the name of the feature to search\n * @return the value of the feature. Returns 0 if the feature is not in the\n * gram.\n */\n public double getFeature(String featureName) {\n // null check; if the feature is not specified, we assume it's 0.\n if (!this.hasAnnotation(featureName)) {\n return 0;\n }\n return ((FeatureAnnotation) getAnnotation(featureName))\n .getScore();\n }\n\n /**\n * Returns all the features associated with the gram.\n *\n * @return all the features associated with the gram.\n */\n @JsonIgnore\n public FeatureAnnotation[] getFeatures() {\n \n List<FeatureAnnotation> features = new ArrayList<>();\n \n for (Annotation ann : getAnnotations()) {\n if (ann instanceof FeatureAnnotation)\n features.add((FeatureAnnotation)ann);\n }\n \n return features.toArray(new FeatureAnnotation[features.size()]); \n }\n\n /**\n * Sets the features of the gram, deleting the previous ones (if any).\n *\n * @param features the new features of the gram.\n */\n public void setFeatures(FeatureAnnotation[] features) {\n for (FeatureAnnotation f : features)\n this.addAnnotation(f);\n }\n // </editor-fold> \n\n // <editor-fold desc=\"Location Management\"> \n /**\n * Adds an appearance of the gram; in other words, adds the component in\n * which the gram appears to the list of the appearances.\n *\n * @param component the component in which the gram appears\n */\n @Override\n public void addAppaerance(DocumentComponent component) {\n appareances.add(component);\n }\n\n /**\n * Gets all the components in which the gram appears.\n *\n * @return all the components in which the gram appears.\n */\n @Override\n public List<DocumentComponent> getAppaerances() {\n return appareances;\n }\n // </editor-fold>\n}", "public class Sentence extends DocumentComponent {\r\n \r\n // <editor-fold desc=\"Private fields\">\r\n\r\n /**\r\n * The {@link it.uniud.ailab.dcore.persistence.Token}s that form the sentence.\r\n */\r\n private List<Token> tokenizedSentence;\r\n\r\n /**\r\n * The {@link it.uniud.ailab.dcore.persistence.Keyphrase}s that have been detected \r\n * in the sentence.\r\n */\r\n private List<Gram> grams;\r\n \r\n // </editor-fold>\r\n \r\n /**\r\n * Creates a sentence with the specified text and language.\r\n * \r\n * @param text the text of the sentence\r\n * @param language the language of the sentence\r\n * @param identifier the output friendly identifier of the sentence\r\n */ \r\n public Sentence(String text,Locale language,String identifier) {\r\n super(text,language,identifier);\r\n tokenizedSentence = new ArrayList<>();\r\n grams = new ArrayList<>(); \r\n }\r\n \r\n /**\r\n * Creates a sentence with the specified text. This requires\r\n * a call to setLanguage before many of the annotators can actually work.\r\n * \r\n * @param text the text of the sentence\r\n * @param identifier the output friendly identifier of the sentence\r\n */\r\n public Sentence(String text,String identifier) {\r\n this(text,null,identifier);\r\n }\r\n \r\n /**\r\n * Sets the tokens of the sentence.\r\n * \r\n * @param tokenzedSentence the tokens of the sentence.\r\n */\r\n public void setTokens(List<Token> tokenzedSentence) {\r\n this.tokenizedSentence = tokenzedSentence;\r\n }\r\n \r\n /**\r\n * Appends a tokens at the end of the token list of the sentence.\r\n * \r\n * @param t the token to add\r\n */\r\n public void addToken(Token t) {\r\n this.tokenizedSentence.add(t);\r\n }\r\n \r\n /**\r\n * Returns the tokens of the sentence.\r\n * \r\n * @return the tokens of the sentence.\r\n */\r\n public List<Token> getTokens() {\r\n return tokenizedSentence;\r\n } \r\n \r\n /**\r\n * Returns an array containing the POS tags of the tokens of the sentence.\r\n * \r\n * @return an array containing the POS tags of the sentence.\r\n */\r\n public String[] getPosTaggedSentence() {\r\n String[] output = new String[tokenizedSentence.size()];\r\n for (int i = 0; i < tokenizedSentence.size(); i++) {\r\n output[i] = tokenizedSentence.get(i).getPoS();\r\n }\r\n return output;\r\n } \r\n // </editor-fold>\r\n \r\n /**\r\n * Get the text of the sentence.\r\n * \r\n * @return the text of the sentence.\r\n */\r\n @Override\r\n public String toString() {\r\n return getText();\r\n }\r\n\r\n /**\r\n * A sentence has no sub-components in the document model, so a null value\r\n * is returned.\r\n * \r\n * @return null, because the sentence has no children.\r\n */\r\n @Override\r\n public List<DocumentComponent> getComponents() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Add a n-gram to the sentence.\r\n * \r\n * @param g the gram to add. \r\n */\r\n @Override\r\n public void addGram(Gram g) {\r\n grams.add(g);\r\n }\r\n \r\n /**\r\n * Get all the grams of a sentence.\r\n * \r\n * @return the grams that have been found in the sentence.\r\n */\r\n @Override\r\n public List<Gram> getGrams() {\r\n return grams;\r\n }\r\n\r\n /**\r\n * Removes a gram from the sentence.\r\n * \r\n * @param gramToRemove the gram to remove\r\n */\r\n @Override\r\n public void removeGram(Gram gramToRemove) {\r\n\r\n for (Iterator<Gram> gramIterator = grams.iterator(); \r\n gramIterator.hasNext();)\r\n {\r\n Gram gram = gramIterator.next();\r\n \r\n if (gram.getIdentifier().equals(gramToRemove.getIdentifier())) {\r\n gramIterator.remove();\r\n }\r\n \r\n }\r\n }\r\n}\r", "public class DocumentUtils {\n\n /**\n * Gets all the sentences of a document component.\n *\n * @param component the component of which you want the sentences\n * @return the sentences of the component\n */\n public static List<Sentence> getSentences(DocumentComponent component) {\n List<Sentence> ret = new ArrayList<>();\n\n for (DocumentComponent c : component.getComponents()) {\n if (c.getComponents() == null) {\n ret.add((Sentence) c);\n } else {\n ret.addAll(getSentences(c));\n }\n }\n\n return ret;\n }\n\n /**\n * Get the total number of phrases from which the document id composed. \n * \n * @param component\n * @return the total # of simple phrases in the document\n */\n public static double getNumberOfPhrasesInDocument(DocumentComponent component) {\n double numberOfPhrases = 0;\n \n //get the sentences in the document\n List<Sentence> sentences = getSentences(component);\n \n for (Sentence sentence : sentences) {\n \n //get the annotation for phrase count in the single sentence\n FeatureAnnotation annotation = (FeatureAnnotation)sentence\n .getAnnotation(DefaultAnnotations.PHRASES_COUNT);\n \n //update the total number of phrases with the one of the current \n //sentence\n numberOfPhrases += annotation.getScore();\n }\n \n assert(numberOfPhrases >= 1):\"total number of phrases must be positive\";\n \n return numberOfPhrases;\n }\n}" ]
import java.util.List; import it.uniud.ailab.dcore.annotation.Annotator; import it.uniud.ailab.dcore.Blackboard; import it.uniud.ailab.dcore.annotation.DefaultAnnotations; import it.uniud.ailab.dcore.annotation.annotations.FeatureAnnotation; import it.uniud.ailab.dcore.persistence.DocumentComponent; import it.uniud.ailab.dcore.persistence.Gram; import it.uniud.ailab.dcore.persistence.Keyphrase; import it.uniud.ailab.dcore.persistence.Sentence; import it.uniud.ailab.dcore.utils.DocumentUtils; import java.util.ArrayList;
/* * Copyright (C) 2015 Artificial Intelligence * Laboratory @ University of Udine. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package it.uniud.ailab.dcore.annotation.annotators; /** * Annotates grams with statistical information such as their frequency, their * width and their depth in the * {@link it.uniud.ailab.dcore.persistence.DocumentComponent} passed as input. * * Document depth is defined as : ( index of sentence of last occurrence / total * # of sentences ) Document height is defined as : ( index of sentence of first * occurrence / total # of sentences ) Frequency is defined as : total # of * occurrences / total # of sentences Life span is defined as : ( index of * sentence of last occurrence - index of sentence of first occurrence) / total * # of sentences. * * * @author Marco Basaldella */ public class StatisticalAnnotator implements Annotator { // We use final fields to avoid spelling errors in feature naming. // Plus, is more handy to refer to a feature by ClassName.FeatureName, // so that the code is much more readable. /** * Document depth of a gram, defined as ( index of sentence of last * occurrence / total # of sentences ). */ public static final String DEPTH = "Depth"; /** * Document depth of a gram, defined as ( index of sentence of first * occurrence / total # of sentences ). */ public static final String HEIGHT = "Height"; /** * Document frequency, defined as the total count of occurrences of the gram * in text normalized by the number of sentences. Note: if a gram appears * twice in a sentence, is counted once. */ public static final String FREQUENCY_SENTENCE = "Freq_Sentence"; /** * Document frequency, defined as the total count of occurrences of the gram * in text. */ public static final String FREQUENCY = "Freq_Absolute"; /** * Life span of a gram, defined as ( index of sentence of last occurrence - * index of sentence of first occurrence) / total # of sentences. * * This can be expressed as (depth - (1 - height)) or equally as depth + * height - 1. */ public static final String LIFESPAN = "LifeSpan"; /** * Annotates grams and sentences with statistical information. * <p> * Grams are annotated with information such as their frequency, their width * and their depth in the * {@link it.uniud.ailab.dcore.persistence.DocumentComponent} passed as * input. * <p> * Sentences are annotated with their length, expressed both in number of * words and number of characters (including whitespaces). * * * @param component the component to analyze. */ @Override public void annotate(Blackboard blackboard, DocumentComponent component) {
List<Sentence> sentences = DocumentUtils.getSentences(component);
8
tang-jie/AvatarMQ
src/com/newlandframework/avatarmq/broker/strategy/BrokerUnsubscribeStrategy.java
[ "public interface ConsumerMessageListener {\n\n void hookConsumerMessage(SubscribeMessage msg, RemoteChannelData channel);\n}", "public interface ProducerMessageListener {\n\n void hookProducerMessage(Message msg, String requestId, Channel channel);\n}", "public class ConsumerContext {\n\n private static final CopyOnWriteArrayList<ClustersRelation> relationArray = new CopyOnWriteArrayList<ClustersRelation>();\n private static final CopyOnWriteArrayList<ClustersState> stateArray = new CopyOnWriteArrayList<ClustersState>();\n\n public static void setClustersStat(String clusters, int stat) {\n stateArray.add(new ClustersState(clusters, stat));\n }\n\n public static int getClustersStat(String clusters) {\n\n Predicate predicate = new Predicate() {\n public boolean evaluate(Object object) {\n String clustersId = ((ClustersState) object).getClusters();\n return clustersId.compareTo(clusters) == 0;\n }\n };\n\n Iterator iterator = new FilterIterator(stateArray.iterator(), predicate);\n\n ClustersState state = null;\n while (iterator.hasNext()) {\n state = (ClustersState) iterator.next();\n break;\n\n }\n return (state != null) ? state.getState() : 0;\n }\n\n public static ConsumerClusters selectByClusters(String clusters) {\n Predicate predicate = new Predicate() {\n public boolean evaluate(Object object) {\n String id = ((ClustersRelation) object).getId();\n return id.compareTo(clusters) == 0;\n }\n };\n\n Iterator iterator = new FilterIterator(relationArray.iterator(), predicate);\n\n ClustersRelation relation = null;\n while (iterator.hasNext()) {\n relation = (ClustersRelation) iterator.next();\n break;\n }\n\n return (relation != null) ? relation.getClusters() : null;\n }\n\n public static List<ConsumerClusters> selectByTopic(String topic) {\n\n List<ConsumerClusters> clusters = new ArrayList<ConsumerClusters>();\n\n for (int i = 0; i < relationArray.size(); i++) {\n ConcurrentHashMap<String, SubscriptionData> subscriptionTable = relationArray.get(i).getClusters().getSubMap();\n if (subscriptionTable.containsKey(topic)) {\n clusters.add(relationArray.get(i).getClusters());\n }\n }\n\n return clusters;\n }\n\n public static void addClusters(String clusters, RemoteChannelData channelinfo) {\n ConsumerClusters manage = selectByClusters(clusters);\n if (manage == null) {\n ConsumerClusters newClusters = new ConsumerClusters(clusters);\n newClusters.attachRemoteChannelData(channelinfo.getClientId(), channelinfo);\n relationArray.add(new ClustersRelation(clusters, newClusters));\n } else if (manage.findRemoteChannelData(channelinfo.getClientId()) != null) {\n manage.detachRemoteChannelData(channelinfo.getClientId());\n manage.attachRemoteChannelData(channelinfo.getClientId(), channelinfo);\n } else {\n String topic = channelinfo.getSubcript().getTopic();\n boolean touchChannel = manage.getSubMap().containsKey(topic);\n if (touchChannel) {\n manage.attachRemoteChannelData(channelinfo.getClientId(), channelinfo);\n } else {\n manage.getSubMap().clear();\n manage.getChannelMap().clear();\n manage.attachRemoteChannelData(channelinfo.getClientId(), channelinfo);\n }\n }\n }\n\n public static void unLoad(String clientId) {\n\n for (int i = 0; i < relationArray.size(); i++) {\n String id = relationArray.get(i).getId();\n ConsumerClusters manage = relationArray.get(i).getClusters();\n\n if (manage.findRemoteChannelData(clientId) != null) {\n manage.detachRemoteChannelData(clientId);\n }\n\n if (manage.getChannelMap().size() == 0) {\n ClustersRelation relation = new ClustersRelation();\n relation.setId(id);\n relationArray.remove(id);\n }\n }\n }\n}", "public class RequestMessage extends BusinessMessage {\n\n public RequestMessage() {\n super();\n }\n}", "public class ResponseMessage extends BusinessMessage {\n\n public ResponseMessage() {\n super();\n }\n}", "public class UnSubscribeMessage extends BaseMessage implements Serializable {\n\n private String consumerId;\n\n public UnSubscribeMessage(String consumerId) {\n this.consumerId = consumerId;\n }\n\n public String getConsumerId() {\n return consumerId;\n }\n\n public void setConsumerId(String consumerId) {\n this.consumerId = consumerId;\n }\n}" ]
import com.newlandframework.avatarmq.broker.ConsumerMessageListener; import com.newlandframework.avatarmq.broker.ProducerMessageListener; import com.newlandframework.avatarmq.consumer.ConsumerContext; import com.newlandframework.avatarmq.model.RequestMessage; import com.newlandframework.avatarmq.model.ResponseMessage; import com.newlandframework.avatarmq.msg.UnSubscribeMessage; import io.netty.channel.ChannelHandlerContext;
/** * Copyright (C) 2016 Newland Group Holding Limited * * 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.newlandframework.avatarmq.broker.strategy; /** * @filename:BrokerUnsubscribeStrategy.java * @description:BrokerUnsubscribeStrategy功能模块 * @author tangjie<https://github.com/tang-jie> * @blog http://www.cnblogs.com/jietang/ * @since 2016-8-11 */ public class BrokerUnsubscribeStrategy implements BrokerStrategy { public BrokerUnsubscribeStrategy() { } public void messageDispatch(RequestMessage request, ResponseMessage response) { UnSubscribeMessage msgUnSubscribe = (UnSubscribeMessage) request.getMsgParams(); ConsumerContext.unLoad(msgUnSubscribe.getConsumerId()); } public void setHookProducer(ProducerMessageListener hookProducer) { }
public void setHookConsumer(ConsumerMessageListener hookConsumer) {
0
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/user/UserPacksQuery.java
[ "public enum HTTPRequestMethod {\n\n\t/** HTTP GET. */\n\tGET,\n\n\t/** HTTP POST. */\n\tPOST,\n\n\t/** HTTP PUT. */\n\tPUT,\n\n\t/** HTTP DELETE. */\n\tDELETE,\n\n\t/** HTTP PATCH. */\n\tPATCH,\n\n\t/** HTTP HEAD. */\n\tHEAD,\n\n\t/** HTTP OPTIONS. */\n\tOPTIONS;\n}", "public abstract class PagingQuery<Q extends PagingQuery<Q, I>, I extends Object>\n\t\t\textends JSONResponseQuery<List<I>> {\n\n\t/** The default page size if none is specified. */\n\tpublic static final int DEFAULT_PAGE_SIZE = 15;\n\n\t/** The maximum size of a single page. 150 is the specified maximum in the API documentation. */\n\tpublic static final int MAXIMUM_PAGE_SIZE = 150;\n\n\t/** The page that will be requested in the query. */\n\tprivate int page;\n\n\t/** The number of results to return per page. */\n\tprivate int pageSize;\n\n\t/**\n\t * @param httpRequestMethod HTTP method to use for query\n\t * @param path The URI path to the API endpoint\n\t * @param resultsMapper {@link PagingResponseMapper} to convert results\n\t */\n\tprotected PagingQuery(\n\t\t\tfinal HTTPRequestMethod httpRequestMethod, final String path, final PagingResponseMapper<I> resultsMapper) {\n\t\tthis(httpRequestMethod, path, resultsMapper, DEFAULT_PAGE_SIZE);\n\t}\n\n\t/**\n\t * @param httpRequestMethod HTTP method to use for query\n\t * @param path The URI path to the API endpoint\n\t * @param resultsMapper {@link PagingResponseMapper} to convert results\n\t * @param pageSize The number of results per page\n\t */\n\tprotected PagingQuery(\n\t\t\tfinal HTTPRequestMethod httpRequestMethod,\n\t\t\tfinal String path,\n\t\t\tfinal PagingResponseMapper<I> resultsMapper,\n\t\t\tfinal int pageSize) {\n\t\tthis(httpRequestMethod, path, resultsMapper, pageSize, 1);\n\t}\n\n\t/**\n\t * @param httpRequestMethod HTTP method to use for query\n\t * @param path The URI path to the API endpoint\n\t * @param resultsMapper {@link PagingResponseMapper} to convert results\n\t * @param pageSize The number of results per page\n\t * @param startPage The page to start at\n\t */\n\tprotected PagingQuery(\n\t\t\tfinal HTTPRequestMethod httpRequestMethod,\n\t\t\tfinal String path,\n\t\t\tfinal PagingResponseMapper<I> resultsMapper,\n\t\t\tfinal int pageSize,\n\t\t\tfinal int startPage) {\n\t\tsuper(httpRequestMethod, path, resultsMapper);\n\t\tsetPageSize(pageSize);\n\t\tsetPage(startPage);\n\t}\n\n\t@Override\n\tpublic PagingResponse<I> processResponse(\n\t\t\tfinal int httpResponseCode, final String httpResponseStatusString, final JSONObject freesoundResponse) {\n\t\tfinal PagingResponse<I> response = new PagingResponse<>(httpResponseCode, httpResponseStatusString);\n\n\t\tif (response.isErrorResponse()) {\n\t\t\tresponse.setErrorDetails(extractErrorMessage(freesoundResponse));\n\t\t} else {\n\t\t\tfinal PagingResponseMapper<I> resultsMapper = (PagingResponseMapper<I>) getResultsMapper();\n\n\t\t\tresponse.setCount(resultsMapper.extractCount(freesoundResponse));\n\t\t\tresponse.setNextPageURI(resultsMapper.extractNextPageURI(freesoundResponse));\n\t\t\tresponse.setPreviousPageURI(resultsMapper.extractPreviousPageURI(freesoundResponse));\n\n\t\t\tresponse.setResults(resultsMapper.map(freesoundResponse));\n\t\t}\n\n\t\treturn response;\n\t}\n\n\t/**\n\t * Set the page of results to retrieve in the query, using a Fluent API style.\n\t *\n\t * @param pageNumber The page number to retrieve\n\t * @return The current query\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Q page(final int pageNumber) {\n\t\tsetPage(pageNumber);\n\t\treturn (Q) this;\n\t}\n\n\t/**\n\t * Set the number of results to return per page, using a Fluent API style.\n\t *\n\t * @param pageSize The number of results per page\n\t * @return The current query\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Q pageSize(final int pageSize) {\n\t\tsetPageSize(pageSize);\n\t\treturn (Q) this;\n\t}\n\n\t@Override\n\tpublic Map<String, Object> getQueryParameters() {\n\t\tfinal Map<String, Object> queryParams = new HashMap<>();\n\t\tqueryParams.put(\"page\", Integer.valueOf(page));\n\t\tqueryParams.put(\"page_size\", Integer.valueOf(pageSize));\n\n\t\treturn queryParams;\n\t}\n\n\t/**\n\t * @return the page\n\t */\n\tpublic int getPage() {\n\t\treturn page;\n\t}\n\n\t/**\n\t * @param page the page to set\n\t */\n\tpublic void setPage(final int page) {\n\t\tif (page < 1) {\n\t\t\tthrow new IllegalArgumentException(\"Must specifiy a page number greater than 0\");\n\t\t}\n\n\t\tthis.page = page;\n\t}\n\n\t/**\n\t * @return the pageSize\n\t */\n\tpublic int getPageSize() {\n\t\treturn pageSize;\n\t}\n\n\t/**\n\t * @param pageSize the pageSize to set\n\t */\n\tpublic void setPageSize(final int pageSize) {\n\t\tif (pageSize < 1) {\n\t\t\tthrow new IllegalArgumentException(\"Must specifiy a page size greater than 0\");\n\t\t} else if (pageSize > MAXIMUM_PAGE_SIZE) {\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\tString.format(\"Cannot specify a page size greater than %s\", MAXIMUM_PAGE_SIZE));\n\t\t}\n\n\t\tthis.pageSize = pageSize;\n\t}\n\n}", "public class Pack {\n\n\t/** The unique identifier of this pack. */\n\tprivate int id;\n\n\t/** The URI for this pack on the Freesound website. */\n\tprivate String url;\n\n\t/** The description the user gave to the pack (if any). */\n\tprivate String description;\n\n\t/** The date when the pack was created. */\n\tprivate Date created;\n\n\t/** The name user gave to the pack. */\n\tprivate String name;\n\n\t/** Username of the creator of the pack. */\n\tprivate String username;\n\n\t/** The number of sounds in the pack. */\n\tprivate int numberOfSounds;\n\n\t/** The URI for a list of sounds in the pack. */\n\tprivate String soundsURI;\n\n\t/** The number of times this pack has been downloaded. */\n\tprivate int numberOfDownloads;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(final int id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the url\n\t */\n\tpublic String getUrl() {\n\t\treturn url;\n\t}\n\n\t/**\n\t * @param url the url to set\n\t */\n\tpublic void setUrl(final String url) {\n\t\tthis.url = url;\n\t}\n\n\t/**\n\t * @return the description\n\t */\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\t/**\n\t * @param description the description to set\n\t */\n\tpublic void setDescription(final String description) {\n\t\tthis.description = description;\n\t}\n\n\t/**\n\t * @return the created\n\t */\n\tpublic Date getCreated() {\n\t\treturn created;\n\t}\n\n\t/**\n\t * @param created the created to set\n\t */\n\tpublic void setCreated(final Date created) {\n\t\tthis.created = created;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name the name to set\n\t */\n\tpublic void setName(final String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * @return the username\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * @param username the username to set\n\t */\n\tpublic void setUsername(final String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * @return the numberOfSounds\n\t */\n\tpublic int getNumberOfSounds() {\n\t\treturn numberOfSounds;\n\t}\n\n\t/**\n\t * @param numberOfSounds the numberOfSounds to set\n\t */\n\tpublic void setNumberOfSounds(final int numberOfSounds) {\n\t\tthis.numberOfSounds = numberOfSounds;\n\t}\n\n\t/**\n\t * @return the numberOfDownloads\n\t */\n\tpublic int getNumberOfDownloads() {\n\t\treturn numberOfDownloads;\n\t}\n\n\t/**\n\t * @param numberOfDownloads the numberOfDownloads to set\n\t */\n\tpublic void setNumberOfDownloads(final int numberOfDownloads) {\n\t\tthis.numberOfDownloads = numberOfDownloads;\n\t}\n\n\t/**\n\t * @return the soundsURI\n\t */\n\tpublic String getSoundsURI() {\n\t\treturn soundsURI;\n\t}\n\n\t/**\n\t * @param soundsURI the soundsURI to set\n\t */\n\tpublic void setSoundsURI(final String soundsURI) {\n\t\tthis.soundsURI = soundsURI;\n\t}\n\n}", "public class PackMapper extends Mapper<JSONObject, Pack> {\n\n\t@Override\n\tpublic Pack map(final JSONObject source) {\n\t\tfinal Pack pack = new Pack();\n\n\t\tpack.setId(extractFieldValue(source, \"id\", Integer.class));\n\t\tpack.setUrl(extractFieldValue(source, \"url\", String.class));\n\t\tpack.setDescription(extractFieldValue(source, \"description\", String.class));\n\t\tpack.setCreated(parseDate(extractFieldValue(source, \"created\", String.class)));\n\t\tpack.setName(extractFieldValue(source, \"name\", String.class));\n\t\tpack.setUsername(extractFieldValue(source, \"username\", String.class));\n\t\tpack.setNumberOfSounds(extractFieldValue(source, \"num_sounds\", Integer.class));\n\t\tpack.setSoundsURI(extractFieldValue(source, \"sounds\", String.class));\n\t\tpack.setNumberOfDownloads(extractFieldValue(source, \"num_downloads\", Integer.class));\n\n\t\treturn pack;\n\t}\n\n}", "public class PagingResponseMapper<I extends Object> extends Mapper<JSONObject, List<I>> {\n\n\t/** {@link Mapper} used to process the individual items in the list. */\n\tprivate final Mapper<JSONObject, I> itemMapper;\n\n\t/**\n\t * @param itemMapper {@link Mapper} used to process the individual items\n\t */\n\tpublic PagingResponseMapper(final Mapper<JSONObject, I> itemMapper) {\n\t\tthis.itemMapper = itemMapper;\n\t}\n\n\t@Override\n\tpublic List<I> map(final JSONObject source) {\n\t\tfinal List<I> items = new LinkedList<>();\n\t\tfinal JSONArray resultsArray = extractFieldValue(source, \"results\", JSONArray.class);\n\n\t\tif (resultsArray != null) {\n\t\t\tfor (int i = 0; i < resultsArray.length(); i++) {\n\t\t\t\tif (!resultsArray.isNull(i)) {\n\t\t\t\t\tfinal JSONObject jsonObject = resultsArray.getJSONObject(i);\n\t\t\t\t\tif ((jsonObject != null)) {\n\t\t\t\t\t\tfinal I item = itemMapper.map(jsonObject);\n\t\t\t\t\t\titems.add(item);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Retrieve the total number of results for the query from the JSON message.\n\t *\n\t * @param source JSON response from freesound\n\t * @return Total number of results\n\t */\n\tpublic Integer extractCount(final JSONObject source) {\n\t\treturn extractFieldValue(source, \"count\", Integer.class);\n\t}\n\n\t/**\n\t * Retrieve the URI of the next page of results (if any) for the query from the JSON message.\n\t *\n\t * @param source JSON response from freesound\n\t * @return Next page URI\n\t */\n\tpublic String extractNextPageURI(final JSONObject source) {\n\t\treturn extractFieldValue(source, \"next\", String.class);\n\t}\n\n\t/**\n\t * Retrieve the URI of the previous page of results (if any) for the query from the JSON message.\n\t *\n\t * @param source JSON response from freesound\n\t * @return Previous page URI\n\t */\n\tpublic String extractPreviousPageURI(final JSONObject source) {\n\t\treturn extractFieldValue(source, \"previous\", String.class);\n\t}\n}" ]
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.PagingQuery; import com.sonoport.freesound.response.Pack; import com.sonoport.freesound.response.mapping.PackMapper; import com.sonoport.freesound.response.mapping.PagingResponseMapper;
/* * Copyright 2014 Sonoport (Asia) Pte Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sonoport.freesound.query.user; /** * Query used to retrieve all {@link Pack}s belonging to a given user. */ public class UserPacksQuery extends PagingQuery<UserPacksQuery, Pack> { /** Parameter to replace on path with username of pack owner. */ protected static final String USERNAME_ROUTE_PARAM = "username"; /** Path to API endpoint. */ protected static final String PATH = String.format("/users/{%s}/packs/", USERNAME_ROUTE_PARAM); /** The username of the user to retrieve packs for. */ private final String username; /** * @param username Username of the user to retrieve packs for */ public UserPacksQuery(final String username) {
super(HTTPRequestMethod.GET, PATH, new PagingResponseMapper<>(new PackMapper()));
3
maruohon/worldutils
src/main/java/fi/dy/masa/worldutils/event/PlayerEventHandler.java
[ "public class ItemChunkWand extends ItemWorldUtils implements IKeyBound\n{\n public static final String WRAPPER_TAG_NAME = \"ChunkWand\";\n public static final String TAG_NAME_MODE = \"Mode\";\n public static final String TAG_NAME_CONFIGS = \"Configs\";\n public static final String TAG_NAME_CONFIG_PRE = \"Mode_\";\n public static final String TAG_NAME_SELECTION = \"Sel\";\n\n protected Map<UUID, Long> lastLeftClick = new HashMap<UUID, Long>();\n\n public ItemChunkWand(String name)\n {\n super(name);\n\n this.setMaxStackSize(1);\n this.setMaxDamage(0);\n }\n\n @Override\n public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand)\n {\n if (world.isRemote == false)\n {\n this.setPosition(player.getHeldItem(hand), PositionUtils.getLookedAtChunk(world, player, 256), Corner.END);\n }\n\n return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, player.getHeldItem(hand));\n }\n\n @Override\n public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)\n {\n if (world.isRemote == false)\n {\n this.setPosition(player.getHeldItem(hand), PositionUtils.getChunkPosFromBlockPos(pos), Corner.END);\n }\n\n return EnumActionResult.SUCCESS;\n }\n\n public void onItemLeftClick(ItemStack stack, World world, EntityPlayer player)\n {\n this.setPosition(stack, PositionUtils.getLookedAtChunk(world, player, 256), Corner.START);\n }\n\n public void onLeftClickBlock(EntityPlayer player, World world, ItemStack stack, BlockPos pos, int dimension, EnumFacing side)\n {\n if (world.isRemote == true)\n {\n return;\n }\n\n // Hack to work around the fact that when the NBT changes, the left click event will fire again the next tick,\n // so it would easily result in the state toggling multiple times per left click\n Long last = this.lastLeftClick.get(player.getUniqueID());\n\n if (last == null || (world.getTotalWorldTime() - last) >= 4)\n {\n this.setPosition(stack, PositionUtils.getChunkPosFromBlockPos(pos), Corner.START);\n }\n\n this.lastLeftClick.put(player.getUniqueID(), world.getTotalWorldTime());\n }\n\n @Override\n public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack stack)\n {\n return true;\n }\n\n @Override\n public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged)\n {\n return slotChanged || oldStack.equals(newStack) == false;\n }\n\n public ChunkPos getPosition(ItemStack stack, Corner corner)\n {\n return this.getPosition(stack, Mode.getMode(stack), corner);\n }\n\n public ChunkPos getPosition(ItemStack stack, Mode mode, Corner corner)\n {\n NBTTagCompound tag = NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true);\n String tagName = corner == Corner.START ? \"Pos1\" : \"Pos2\";\n\n if (tag.hasKey(tagName, Constants.NBT.TAG_COMPOUND))\n {\n tag = tag.getCompoundTag(tagName);\n return new ChunkPos(tag.getInteger(\"chunkX\"), tag.getInteger(\"chunkZ\"));\n }\n\n return null;\n }\n\n private void setPosition(ItemStack stack, ChunkPos pos, Corner corner)\n {\n this.setPosition(stack, Mode.getMode(stack), pos, corner);\n }\n\n private void setPosition(ItemStack stack, Mode mode, ChunkPos pos, Corner corner)\n {\n NBTTagCompound tag = NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true);\n String tagName = corner == Corner.START ? \"Pos1\" : \"Pos2\";\n\n if (pos == null || pos.equals(this.getPosition(stack, mode, corner)))\n {\n tag.removeTag(tagName);\n }\n else\n {\n NBTTagCompound posTag = new NBTTagCompound();\n posTag.setInteger(\"chunkX\", pos.x);\n posTag.setInteger(\"chunkZ\", pos.z);\n tag.setTag(tagName, posTag);\n }\n }\n\n private void movePosition(ItemStack stack, EnumFacing direction, boolean reverse, Corner corner)\n {\n ChunkPos pos = this.getPosition(stack, corner);\n\n if (pos != null)\n {\n int amount = reverse ? 1 : -1;\n pos = new ChunkPos(pos.x + direction.getXOffset() * amount, pos.z + direction.getZOffset() * amount);\n this.setPosition(stack, pos, corner);\n }\n }\n\n public Collection<ChunkPos> getCurrentAndStoredSelections(ItemStack stack)\n {\n Collection<ChunkPos> chunks = this.getCurrentSelection(stack);\n chunks.addAll(this.getStoredSelection(stack));\n return chunks;\n }\n\n public Collection<ChunkPos> getCurrentSelection(ItemStack stack)\n {\n List<ChunkPos> list = new ArrayList<ChunkPos>();\n ChunkPos start = this.getPosition(stack, Corner.START);\n ChunkPos end = this.getPosition(stack, Corner.END);\n\n if (start != null && end != null)\n {\n int minX = Math.min(start.x, end.x);\n int minZ = Math.min(start.z, end.z);\n int maxX = Math.max(start.x, end.x);\n int maxZ = Math.max(start.z, end.z);\n\n for (int z = minZ; z <= maxZ; z++)\n {\n for (int x = minX; x <= maxX; x++)\n {\n list.add(new ChunkPos(x, z));\n }\n }\n }\n else if (start != null)\n {\n list.add(start);\n }\n else if (end != null)\n {\n list.add(end);\n }\n\n return list;\n }\n\n public Collection<ChunkPos> getStoredSelection(ItemStack stack)\n {\n Set<ChunkPos> stored = new HashSet<ChunkPos>();\n NBTTagCompound tag = NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true);\n NBTTagList list = tag.getTagList(\"Chunks\", Constants.NBT.TAG_LONG);\n\n for (int i = 0; i < list.tagCount(); i++)\n {\n NBTBase nbt = list.get(i);\n\n if (nbt.getId() == Constants.NBT.TAG_LONG)\n {\n long val = ((NBTTagLong) nbt).getLong();\n stored.add(new ChunkPos((int)(val & 0xFFFFFFFF), (int)(val >>> 32) & 0xFFFFFFFF));\n }\n }\n\n return stored;\n }\n\n private void setStoredChunks(ItemStack stack, Collection<ChunkPos> chunks)\n {\n NBTTagCompound tag = NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true);\n NBTTagList list = new NBTTagList();\n\n for (ChunkPos pos : chunks)\n {\n list.appendTag(new NBTTagLong(ChunkPos.asLong(pos.x, pos.z)));\n }\n\n tag.setTag(\"Chunks\", list);\n }\n\n private void addCurrentSelectionToStoredSet(ItemStack stack)\n {\n Collection<ChunkPos> current = this.getCurrentSelection(stack);\n Collection<ChunkPos> stored = this.getStoredSelection(stack);\n stored.addAll(current);\n this.setStoredChunks(stack, stored);\n }\n\n private void removeCurrentSelectionFromStoredSet(ItemStack stack)\n {\n Collection<ChunkPos> current = this.getCurrentSelection(stack);\n Collection<ChunkPos> stored = this.getStoredSelection(stack);\n stored.removeAll(current);\n this.setStoredChunks(stack, stored);\n }\n\n public int getNumTargets(ItemStack stack)\n {\n return NBTUtils.getByte(stack, WRAPPER_TAG_NAME, \"NumTargets\");\n }\n\n private void setNumTargets(ItemStack stack, World world)\n {\n int num = ChunkUtils.getNumberOfAlternateWorlds();\n NBTUtils.setByte(stack, WRAPPER_TAG_NAME, \"NumTargets\", (byte) num);\n }\n\n public int getTargetSelection(ItemStack stack)\n {\n return NBTUtils.getByte(stack, WRAPPER_TAG_NAME, TAG_NAME_SELECTION);\n }\n\n private void changeTargetSelection(ItemStack stack, World world, boolean reverse)\n {\n NBTTagCompound tag = NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true);\n\n int max = this.getNumTargets(stack);\n NBTUtils.cycleByteValue(tag, TAG_NAME_SELECTION, 0, max - 1, reverse);\n tag.setString(\"WorldName\", ChunkUtils.getWorldName(tag.getByte(TAG_NAME_SELECTION)));\n }\n\n public String getWorldName(ItemStack stack)\n {\n return NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true).getString(\"WorldName\");\n }\n\n public String getBiomeName(ItemStack stack)\n {\n return NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true).getString(\"BiomeName\");\n }\n\n public int getBiomeIndex(ItemStack stack)\n {\n return NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true).getByte(\"BiomeIndex\");\n }\n\n private EnumActionResult useWand(ItemStack stack, World world, EntityPlayer player)\n {\n Mode mode = Mode.getMode(stack);\n\n if (mode == Mode.CHUNK_SWAP)\n {\n return this.useWandChunkSwap(stack, world, player);\n }\n else if (mode == Mode.BIOME_IMPORT)\n {\n return this.useWandBiomeImport(stack, world, player);\n }\n else if (mode == Mode.BIOME_SET)\n {\n return this.useWandBiomeSet(stack, world, player);\n }\n\n return EnumActionResult.PASS;\n }\n\n private EnumActionResult useWandChunkSwap(ItemStack stack, World world, EntityPlayer player)\n {\n Collection<ChunkPos> locations = this.getCurrentAndStoredSelections(stack);\n String worldName = this.getWorldName(stack);\n\n for (ChunkPos pos : locations)\n {\n ChunkUtils.instance().loadChunkFromAlternateWorld(world, pos, worldName, player.getName());\n }\n\n PacketHandler.INSTANCE.sendTo(new MessageChunkChanges(ChangeType.CHUNK_CHANGE, locations, worldName), (EntityPlayerMP) player);\n\n return EnumActionResult.SUCCESS;\n }\n\n private EnumActionResult useWandBiomeImport(ItemStack stack, World world, EntityPlayer player)\n {\n Collection<ChunkPos> locations = this.getCurrentAndStoredSelections(stack);\n String worldName = this.getWorldName(stack);\n\n for (ChunkPos pos : locations)\n {\n ChunkUtils.instance().loadBiomesFromAlternateWorld(world, pos, worldName, player.getName());\n }\n\n PacketHandler.INSTANCE.sendTo(new MessageChunkChanges(ChangeType.BIOME_IMPORT, locations, worldName), (EntityPlayerMP) player);\n\n return EnumActionResult.SUCCESS;\n }\n\n private EnumActionResult useWandBiomeSet(ItemStack stack, World world, EntityPlayer player)\n {\n Collection<ChunkPos> locations = this.getCurrentAndStoredSelections(stack);\n Biome biome = ForgeRegistries.BIOMES.getValue(new ResourceLocation(this.getBiomeName(stack)));\n\n for (ChunkPos pos : locations)\n {\n ChunkUtils.instance().setBiome(world, pos, biome, player.getName());\n }\n\n PacketHandler.INSTANCE.sendTo(new MessageChunkChanges(ChangeType.BIOME_SET, locations, \"\"), (EntityPlayerMP) player);\n\n return EnumActionResult.SUCCESS;\n }\n\n private void changeSelectedBiome(ItemStack stack, boolean reverse)\n {\n ResourceLocation selected = new ResourceLocation(this.getBiomeName(stack));\n List<ResourceLocation> biomes = new ArrayList<ResourceLocation>();\n List<Integer> biomeIds = new ArrayList<Integer>();\n\n for (Map.Entry<ResourceLocation, Biome> entry : ForgeRegistries.BIOMES.getEntries())\n {\n biomeIds.add(Biome.getIdForBiome(ForgeRegistries.BIOMES.getValue(entry.getKey())));\n }\n\n Collections.sort(biomeIds);\n int index = -1;\n int i = 0;\n\n for (Integer id : biomeIds)\n {\n ResourceLocation rl = ForgeRegistries.BIOMES.getKey(Biome.getBiome(id));\n biomes.add(rl);\n\n if (rl.equals(selected))\n {\n index = i;\n }\n\n i++;\n }\n\n if (index == -1)\n {\n index = 0;\n }\n else\n {\n index += reverse ? -1 : 1;\n\n if (index < 0)\n {\n index = biomes.size() - 1;\n }\n else if (index >= biomes.size())\n {\n index = 0;\n }\n }\n\n NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true).setString(\"BiomeName\", biomes.get(index).toString());\n NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true).setByte(\"BiomeId\", (byte) biomeIds.get(index).intValue());\n NBTUtils.getCompoundTag(stack, WRAPPER_TAG_NAME, true).setByte(\"BiomeIndex\", (byte) index);\n }\n\n @Override\n public void doKeyBindingAction(EntityPlayer player, ItemStack stack, int key)\n {\n if (key == HotKeys.KEYCODE_CUSTOM_1)\n {\n this.onItemLeftClick(stack, player.getEntityWorld(), player);\n return;\n }\n\n Mode mode = Mode.getMode(stack);\n\n // Alt + Shift + Scroll: Move the start position\n if (EnumKey.SCROLL.matches(key, HotKeys.MOD_SHIFT_ALT))\n {\n this.movePosition(stack, EntityUtils.getHorizontalLookingDirection(player), EnumKey.keypressActionIsReversed(key), Corner.START);\n }\n // Shift + Scroll: Move the end position\n else if (EnumKey.SCROLL.matches(key, HotKeys.MOD_SHIFT))\n {\n this.movePosition(stack, EntityUtils.getHorizontalLookingDirection(player), EnumKey.keypressActionIsReversed(key), Corner.END);\n }\n // Alt + Scroll: Change world selection\n else if (EnumKey.SCROLL.matches(key, HotKeys.MOD_ALT))\n {\n if (mode == Mode.BIOME_SET)\n {\n this.changeSelectedBiome(stack, EnumKey.keypressActionIsReversed(key));\n }\n else\n {\n this.setNumTargets(stack, player.getEntityWorld());\n this.changeTargetSelection(stack, player.getEntityWorld(), EnumKey.keypressActionIsReversed(key));\n }\n }\n // Ctrl + Scroll: Cycle the mode\n else if (EnumKey.SCROLL.matches(key, HotKeys.MOD_CTRL))\n {\n Mode.cycleMode(stack, EnumKey.keypressActionIsReversed(key) || EnumKey.keypressContainsShift(key), player);\n }\n // Ctrl + Alt + Toggle key: Clear stored chunk selection\n else if (EnumKey.TOGGLE.matches(key, HotKeys.MOD_CTRL_ALT))\n {\n this.setStoredChunks(stack, new ArrayList<ChunkPos>());\n }\n // Shift + Toggle key: Remove current area from stored area\n else if (EnumKey.TOGGLE.matches(key, HotKeys.MOD_SHIFT))\n {\n this.removeCurrentSelectionFromStoredSet(stack);\n }\n // Alt + Toggle key: Add current area to stored area\n else if (EnumKey.TOGGLE.matches(key, HotKeys.MOD_ALT))\n {\n this.addCurrentSelectionToStoredSet(stack);\n }\n // Ctrl + Shift + Alt + Toggle key: Clear chunk change tracker\n else if (EnumKey.TOGGLE.matches(key, HotKeys.MOD_SHIFT_CTRL_ALT))\n {\n ChunkUtils.instance().clearChangedChunksForUser(player.getEntityWorld(), player.getName());\n player.sendMessage(new TextComponentTranslation(\"worldutils.chat.message.chunkwand.clearedchangedchunks\"));\n }\n // Just Toggle key: Execute the chunk operation\n else if (EnumKey.TOGGLE.matches(key, HotKeys.MOD_NONE))\n {\n if (this.useWand(stack, player.getEntityWorld(), player) == EnumActionResult.SUCCESS)\n {\n player.getEntityWorld().playSound(null, player.getPosition(), SoundEvents.ENTITY_ENDERMEN_TELEPORT, SoundCategory.MASTER, 0.4f, 0.7f);\n }\n }\n }\n\n public static enum Mode\n {\n CHUNK_SWAP (\"chunk_swap\", \"worldutils.tooltip.item.chunkwand.chunkswap\", true),\n BIOME_IMPORT (\"biome_import\", \"worldutils.tooltip.item.chunkwand.biomeimport\", true),\n BIOME_SET (\"biome_set\", \"worldutils.tooltip.item.chunkwand.biomeset\", true);\n\n private final String name;\n private final String unlocName;\n private final boolean hasUseDelay;\n\n private Mode (String name, String unlocName, boolean useDelay)\n {\n this.name = name;\n this.unlocName = unlocName;\n this.hasUseDelay = useDelay;\n }\n\n public String getName()\n {\n return this.name;\n }\n\n public String getDisplayName()\n {\n return I18n.format(this.unlocName);\n }\n\n public boolean hasUseDelay()\n {\n return this.hasUseDelay;\n }\n\n public static Mode getMode(ItemStack stack)\n {\n return values()[getModeOrdinal(stack)];\n }\n\n public static void cycleMode(ItemStack stack, boolean reverse, EntityPlayer player)\n {\n NBTUtils.cycleByteValue(stack, WRAPPER_TAG_NAME, TAG_NAME_MODE, values().length - 1, reverse);\n }\n\n public static int getModeOrdinal(ItemStack stack)\n {\n int id = NBTUtils.getByte(stack, WRAPPER_TAG_NAME, TAG_NAME_MODE);\n return (id >= 0 && id < values().length) ? id : 0;\n }\n\n public static int getModeCount(EntityPlayer player)\n {\n return values().length;\n }\n }\n\n public static enum Corner\n {\n START,\n END;\n }\n}", "public class MessageChunkChanges implements IMessage\n{\n private byte type;\n private int numChunks;\n private String worldName;\n private Collection<ChunkPos> chunks;\n private NBTTagCompound nbt;\n\n public MessageChunkChanges()\n {\n }\n\n public MessageChunkChanges(ChangeType type, Collection<ChunkPos> chunks, String worldName)\n {\n this.type = (byte) type.ordinal();\n this.numChunks = chunks.size();\n this.worldName = worldName;\n this.chunks = chunks;\n }\n\n public MessageChunkChanges(NBTTagCompound nbt)\n {\n this.type = (byte) 0xFF;\n this.nbt = nbt;\n }\n\n @Override\n public void fromBytes(ByteBuf buf)\n {\n this.type = buf.readByte();\n\n // Full change set in NBT form\n if (this.type == (byte) 0xFF)\n {\n this.nbt = ByteBufUtils.readTag(buf);\n }\n else\n {\n this.worldName = ByteBufUtils.readUTF8String(buf);\n this.numChunks = buf.readInt();\n this.chunks = new ArrayList<ChunkPos>();\n\n for (int i = 0; i < this.numChunks; i++)\n {\n this.chunks.add(new ChunkPos(buf.readInt(), buf.readInt()));\n }\n }\n }\n\n @Override\n public void toBytes(ByteBuf buf)\n {\n buf.writeByte(this.type);\n\n // Full change set in NBT form\n if (this.type == (byte) 0xFF)\n {\n ByteBufUtils.writeTag(buf, this.nbt);\n }\n else\n {\n ByteBufUtils.writeUTF8String(buf, this.worldName);\n buf.writeInt(this.numChunks);\n\n for (ChunkPos pos : this.chunks)\n {\n buf.writeInt(pos.x);\n buf.writeInt(pos.z);\n }\n }\n }\n\n public static class Handler implements IMessageHandler<MessageChunkChanges, IMessage>\n {\n @Override\n public IMessage onMessage(final MessageChunkChanges message, MessageContext ctx)\n {\n if (ctx.side != Side.CLIENT)\n {\n WorldUtils.logger.error(\"Wrong side in MessageChunkChanges: \" + ctx.side);\n return null;\n }\n\n Minecraft mc = FMLClientHandler.instance().getClient();\n final EntityPlayer player = WorldUtils.proxy.getPlayerFromMessageContext(ctx);\n if (mc == null || player == null)\n {\n WorldUtils.logger.error(\"Minecraft or player was null in MessageSyncSlot\");\n return null;\n }\n\n mc.addScheduledTask(new Runnable()\n {\n public void run()\n {\n processMessage(message, player);\n }\n });\n\n return null;\n }\n\n protected void processMessage(final MessageChunkChanges message, EntityPlayer player)\n {\n if (message.type == (byte) 0xFF)\n {\n //WorldUtils.logger.info(\"Message to load ALL chunks\");\n ChunkChangeTracker.instance().readAllChangesFromNBT(message.nbt);\n }\n else\n {\n //WorldUtils.logger.info(\"Message to load incremental chunks\");\n ChunkChangeTracker.instance().addIncrementalChanges(ChangeType.fromId(message.type), message.chunks, message.worldName);\n }\n }\n }\n}", "public class MessageKeyPressed implements IMessage\n{\n private int keyPressed;\n\n public MessageKeyPressed()\n {\n }\n\n public MessageKeyPressed(int key)\n {\n this.keyPressed = key;\n }\n\n @Override\n public void fromBytes(ByteBuf buf)\n {\n this.keyPressed = buf.readInt();\n }\n\n @Override\n public void toBytes(ByteBuf buf)\n {\n buf.writeInt(this.keyPressed);\n }\n\n public static class Handler implements IMessageHandler<MessageKeyPressed, IMessage>\n {\n @Override\n public IMessage onMessage(final MessageKeyPressed message, MessageContext ctx)\n {\n if (ctx.side != Side.SERVER)\n {\n WorldUtils.logger.error(\"Wrong side in MessageKeyPressed: \" + ctx.side);\n return null;\n }\n\n final EntityPlayerMP sendingPlayer = ctx.getServerHandler().player;\n if (sendingPlayer == null)\n {\n WorldUtils.logger.error(\"Sending player was null in MessageKeyPressed\");\n return null;\n }\n\n final WorldServer playerWorldServer = sendingPlayer.getServerWorld();\n if (playerWorldServer == null)\n {\n WorldUtils.logger.error(\"World was null in MessageKeyPressed\");\n return null;\n }\n\n playerWorldServer.addScheduledTask(new Runnable()\n {\n public void run()\n {\n processMessage(message, sendingPlayer);\n }\n });\n\n return null;\n }\n\n protected void processMessage(final MessageKeyPressed message, EntityPlayer player)\n {\n ItemStack stack = EntityUtils.getHeldItemOfType(player, IKeyBound.class);\n\n if (stack.isEmpty() == false)\n {\n ((IKeyBound) stack.getItem()).doKeyBindingAction(player, stack, message.keyPressed);\n }\n }\n }\n}", "public class PacketHandler\n{\n public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID.toLowerCase());\n\n public static void init()\n {\n INSTANCE.registerMessage(MessageKeyPressed.Handler.class, MessageKeyPressed.class, 0, Side.SERVER);\n INSTANCE.registerMessage(MessageChunkChanges.Handler.class, MessageChunkChanges.class, 1, Side.CLIENT);\n }\n}", "public class HotKeys\n{\n public static final String KEYBIND_CATEGORY_WORLD_UTILS = \"category.\" + Reference.MOD_ID;\n\n public static final String KEYBIND_NAME_TOGGLE_MODE = Reference.MOD_ID + \".key.togglemode\";\n\n public static final int DEFAULT_KEYBIND_TOGGLE_MODE = Keyboard.KEY_R;\n\n // These are used to identify the pressed key on the server side. They have nothing to do with actual key codes.\n public static final int BASE_KEY_MASK = 0x0000FFFF;\n public static final int KEYBIND_ID_TOGGLE_MODE = 0x00000001;\n public static final int KEYCODE_SCROLL = 0x00001000;\n\n public static final int MODIFIER_MASK = 0x000F0000;\n public static final int KEYBIND_MODIFIER_SHIFT = 0x00010000;\n public static final int KEYBIND_MODIFIER_CONTROL = 0x00020000;\n public static final int KEYBIND_MODIFIER_ALT = 0x00040000;\n public static final int SCROLL_MODIFIER_REVERSE = 0x00100000;\n\n public static final int KEYCODE_SNEAK = 0x01000000;\n public static final int KEYCODE_JUMP = 0x02000000;\n public static final int KEYCODE_CUSTOM_1 = 0x10000000;\n\n public static final int MOD_NONE = 0x00000000;\n public static final int MOD_SHIFT = KEYBIND_MODIFIER_SHIFT;\n public static final int MOD_CTRL = KEYBIND_MODIFIER_CONTROL;\n public static final int MOD_ALT = KEYBIND_MODIFIER_ALT;\n public static final int MOD_SHIFT_CTRL = KEYBIND_MODIFIER_SHIFT | KEYBIND_MODIFIER_CONTROL;\n public static final int MOD_SHIFT_ALT = KEYBIND_MODIFIER_SHIFT | KEYBIND_MODIFIER_ALT;\n public static final int MOD_SHIFT_CTRL_ALT = KEYBIND_MODIFIER_SHIFT | KEYBIND_MODIFIER_CONTROL | KEYBIND_MODIFIER_ALT;\n public static final int MOD_CTRL_ALT = KEYBIND_MODIFIER_CONTROL | KEYBIND_MODIFIER_ALT;\n\n public enum EnumKey\n {\n TOGGLE (0x00000001),\n SCROLL (0x00001000),\n SNEAK (0x01000000),\n JUMP (0x02000000),\n CUSTOM_1 (0x10000000);\n\n private final int keyCode;\n\n private EnumKey(int keyCode)\n {\n this.keyCode = keyCode;\n }\n\n public static int getBaseKey(int value)\n {\n return (value & BASE_KEY_MASK);\n }\n\n public static int getModifier(int value)\n {\n return (value & MODIFIER_MASK);\n }\n\n public static boolean matches(int value, EnumKey key, int modifier)\n {\n return getBaseKey(value) == key.keyCode && getModifier(value) == modifier;\n }\n\n public boolean matches(int value, int modifier)\n {\n return this.matches(value, modifier, 0);\n }\n\n public boolean matches(int value, int modRequire, int modIgnore)\n {\n return getBaseKey(value) == this.keyCode && (getModifier(value) & ~modIgnore) == modRequire;\n }\n\n public static boolean keypressContainsShift(int value)\n {\n return (value & KEYBIND_MODIFIER_SHIFT) != 0;\n }\n\n public static boolean keypressContainsControl(int value)\n {\n return (value & KEYBIND_MODIFIER_CONTROL) != 0;\n }\n\n public static boolean keypressContainsAlt(int value)\n {\n return (value & KEYBIND_MODIFIER_ALT) != 0;\n }\n\n public static boolean keypressActionIsReversed(int value)\n {\n return (value & SCROLL_MODIFIER_REVERSE) != 0;\n }\n }\n}", "@Mod.EventBusSubscriber(modid = Reference.MOD_ID)\npublic class WorldUtilsItems\n{\n @GameRegistry.ObjectHolder(Reference.MOD_ID + \":\" + ReferenceNames.NAME_ITEM_CHUNK_WAND)\n public static final ItemWorldUtils CHUNK_WAND = null;\n\n @SubscribeEvent\n public static void registerItems(RegistryEvent.Register<Item> event)\n {\n IForgeRegistry<Item> registry = event.getRegistry();\n\n registerItem(registry, new ItemChunkWand(ReferenceNames.NAME_ITEM_CHUNK_WAND), Configs.disableChunkWand);\n }\n\n private static void registerItem(IForgeRegistry<Item> registry, ItemWorldUtils item, boolean isDisabled)\n {\n if (isDisabled == false)\n {\n item.setRegistryName(Reference.MOD_ID + \":\" + item.getItemNameWorldUtils());\n registry.register(item);\n }\n }\n}", "public class ChunkUtils\n{\n public static final String TAG_CHANGED_CHUNKS = \"chunks_changed\";\n public static final String TAG_BIOMES_IMPORTED = \"biomes_imported\";\n public static final String TAG_BIOMES_SET = \"biomes_set\";\n private static final ChunkUtils INSTANCE = new ChunkUtils();\n private static MethodHandle methodHandle_ChunkProviderServer_saveChunkData;\n private static MethodHandle methodHandle_ChunkProviderServer_saveChunkExtraData;\n private static Field field_World_tileEntitiesToBeRemoved;\n private static Field field_World_unloadedEntityList;\n private static Field field_PlayerChunkMapEntry_chunk;\n private final Map<File, AnvilChunkLoader> chunkLoaders = new HashMap<File, AnvilChunkLoader>();\n private final Int2ObjectOpenHashMap<Map<String, Map<Long, String>>> changedChunks = new Int2ObjectOpenHashMap<>();\n private final Int2ObjectOpenHashMap<Map<String, Map<Long, String>>> importedBiomes = new Int2ObjectOpenHashMap<>();\n private final Int2ObjectOpenHashMap<Map<String, Map<Long, String>>> setBiomes = new Int2ObjectOpenHashMap<>();\n private boolean dirty;\n\n static\n {\n methodHandle_ChunkProviderServer_saveChunkData =\n MethodHandleUtils.getMethodHandleVirtual(ChunkProviderServer.class, new String[] { \"func_73242_b\", \"saveChunkData\"}, Chunk.class);\n methodHandle_ChunkProviderServer_saveChunkExtraData =\n MethodHandleUtils.getMethodHandleVirtual(ChunkProviderServer.class, new String[] { \"func_73243_a\", \"saveChunkExtraData\" }, Chunk.class);\n\n field_World_tileEntitiesToBeRemoved = ObfuscationReflectionHelper.findField(World.class, \"field_147483_b\"); // tileEntitiesToBeRemoved\n field_World_unloadedEntityList = ObfuscationReflectionHelper.findField(World.class, \"field_72997_g\"); // unloadedEntityList\n field_PlayerChunkMapEntry_chunk = ObfuscationReflectionHelper.findField(PlayerChunkMapEntry.class, \"field_187286_f\"); // chunk\n }\n\n public static class ChunkChanges\n {\n public final ChangeType type;\n public final String worldName;\n\n public ChunkChanges(ChangeType type, String worldName)\n {\n this.type = type;\n this.worldName = worldName;\n }\n\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((type == null) ? 0 : type.hashCode());\n result = prime * result + ((worldName == null) ? 0 : worldName.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n ChunkChanges other = (ChunkChanges) obj;\n if (type != other.type)\n return false;\n if (worldName == null)\n {\n if (other.worldName != null)\n return false;\n }\n else if (!worldName.equals(other.worldName))\n return false;\n return true;\n }\n }\n\n public static enum ChangeType\n {\n CHUNK_CHANGE,\n BIOME_IMPORT,\n BIOME_SET;\n\n public static ChangeType fromId(int id)\n {\n return values()[id % values().length];\n }\n }\n\n private ChunkUtils()\n {\n }\n\n public static ChunkUtils instance()\n {\n return INSTANCE;\n }\n\n private static File getBaseWorldSaveLocation()\n {\n return DimensionManager.getCurrentSaveRootDirectory();\n }\n\n private static File getWorldSaveLocation(World world)\n {\n File dir = getBaseWorldSaveLocation();\n\n if (world.provider.getSaveFolder() != null)\n {\n dir = new File(dir, world.provider.getSaveFolder());\n }\n\n return dir;\n }\n\n private static File getAlternateWorldsBaseDirectory()\n {\n return new File(getBaseWorldSaveLocation(), \"alternate_worlds\");\n }\n\n private static File getAlternateWorldSaveLocation(World world, String worldName)\n {\n File baseDir = getAlternateWorldsBaseDirectory();\n\n if (world.provider.getSaveFolder() != null)\n {\n baseDir = new File(baseDir, world.provider.getSaveFolder());\n }\n\n return new File(baseDir, worldName);\n }\n\n public static int getNumberOfAlternateWorlds()\n {\n File dir = getAlternateWorldsBaseDirectory();\n String[] names = dir.list();\n int num = 0;\n\n if (names != null)\n {\n for (String name : names)\n {\n File tmp1 = new File(dir, name);\n File tmp2 = new File(tmp1, \"region\");\n\n if (tmp1.isDirectory() && tmp2.isDirectory())\n {\n num++;\n }\n }\n\n return num;\n }\n\n return 0;\n }\n\n public static String getWorldName(int index)\n {\n File dir = getAlternateWorldsBaseDirectory();\n String[] names = dir.list();\n\n if (names != null)\n {\n List<String> namesList = new ArrayList<String>();\n\n for (String name : names)\n {\n File tmp1 = new File(dir, name);\n File tmp2 = new File(tmp1, \"region\");\n\n if (tmp1.isDirectory() && tmp2.isDirectory())\n {\n namesList.add(name);\n }\n }\n\n Collections.sort(namesList);\n\n return index < namesList.size() ? namesList.get(index) : \"\";\n }\n\n return \"\";\n }\n\n public AnvilChunkLoader getChunkLoader(File worldDir)\n {\n AnvilChunkLoader loader = this.chunkLoaders.get(worldDir);\n\n if (loader == null)\n {\n loader = new AnvilChunkLoader(worldDir, FMLCommonHandler.instance().getMinecraftServerInstance().getDataFixer());\n this.chunkLoaders.put(worldDir, loader);\n }\n\n return loader;\n }\n\n public AnvilChunkLoader getChunkLoaderForWorld(World world)\n {\n File worldDir = getWorldSaveLocation(world);\n\n if (worldDir.exists() && worldDir.isDirectory())\n {\n return this.getChunkLoader(worldDir);\n }\n\n return null;\n }\n\n public AnvilChunkLoader getChunkLoaderForAlternateWorld(World world, String alternateWorldName)\n {\n File worldDir = getAlternateWorldSaveLocation(world, alternateWorldName);\n\n if (worldDir.exists() && worldDir.isDirectory())\n {\n return this.getChunkLoader(worldDir);\n }\n\n return null;\n }\n\n private void unloadChunk(WorldServer world, ChunkPos pos)\n {\n int chunkX = pos.x;\n int chunkZ = pos.z;\n Chunk chunk = world.getChunk(chunkX, chunkZ);\n\n chunk.onUnload();\n\n try\n {\n ChunkProviderServer provider = world.getChunkProvider();\n methodHandle_ChunkProviderServer_saveChunkData.invokeExact(provider, chunk);\n methodHandle_ChunkProviderServer_saveChunkExtraData.invokeExact(provider, chunk);\n }\n catch (Throwable t)\n {\n WorldUtils.logger.warn(\"Exception while trying to unload chunk ({}, {})\", chunk.x, chunk.z, t);\n }\n\n List<Entity> unloadEntities = new ArrayList<Entity>();\n\n for (ClassInheritanceMultiMap<Entity> map : chunk.getEntityLists())\n {\n unloadEntities.addAll(map);\n }\n\n for (int i = 0; i < unloadEntities.size(); i++)\n {\n Entity entity = unloadEntities.get(i);\n\n if ((entity instanceof EntityPlayer) == false)\n {\n world.loadedEntityList.remove(entity);\n world.onEntityRemoved(entity);\n }\n }\n\n Collection<TileEntity> unloadTileEntities = chunk.getTileEntityMap().values();\n world.tickableTileEntities.removeAll(unloadTileEntities);\n world.loadedTileEntityList.removeAll(unloadTileEntities);\n\n try\n {\n @SuppressWarnings(\"unchecked\")\n List<TileEntity> toRemove = (List<TileEntity>) field_World_tileEntitiesToBeRemoved.get(world);\n toRemove.removeAll(unloadTileEntities);\n\n @SuppressWarnings(\"unchecked\")\n List<Entity> toRemoveEnt = (List<Entity>) field_World_unloadedEntityList.get(world);\n toRemoveEnt.removeAll(unloadEntities);\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"Exception while trying to unload chunk ({}, {})\", chunk.x, chunk.z, e);\n }\n\n // For some reason getPendingBlockUpdates() checks for \"x >= minX && x < maxX\" and not x <= maxX...\n StructureBoundingBox bb = new StructureBoundingBox(chunkX << 4, 0, chunkZ << 4, (chunkX << 4) + 17, 255, (chunkZ << 4) + 17);\n world.getPendingBlockUpdates(bb, true); // Remove pending block updates from the unloaded chunk area\n\n world.getChunkProvider().loadedChunks.remove(ChunkPos.asLong(chunk.x, chunk.z));\n }\n\n private Chunk loadChunk(WorldServer world, ChunkPos pos, String worldName)\n {\n AnvilChunkLoader loader = this.getChunkLoaderForAlternateWorld(world, worldName);\n\n if (loader != null)\n {\n try\n {\n Object[] data = loader.loadChunk__Async(world, pos.x, pos.z);\n\n if (data != null)\n {\n this.unloadChunk(world, pos);\n\n final Chunk chunk = (Chunk) data[0];\n NBTTagCompound nbt = (NBTTagCompound) data[1];\n loader.loadEntities(world, nbt.getCompoundTag(\"Level\"), chunk);\n\n chunk.setLastSaveTime(world.getTotalWorldTime());\n world.getChunkProvider().loadedChunks.put(ChunkPos.asLong(pos.x, pos.z), chunk);\n this.updatePlayerChunkMap(world, pos, chunk);\n\n List<Entity> unloadEntities = new ArrayList<Entity>();\n\n for (ClassInheritanceMultiMap<Entity> map : chunk.getEntityLists())\n {\n unloadEntities.addAll(map);\n }\n\n // Remove any entities from the world that have the same UUID\n // as entities in the new chunk that will get loaded.\n for (Entity entity : unloadEntities)\n {\n Entity match = world.getEntityFromUuid(entity.getUniqueID());\n\n if (match != null)\n {\n world.removeEntityDangerously(match);\n }\n }\n\n chunk.onLoad();\n chunk.markDirty();\n // don't call chunk.populateChunk() because it would probably mess with structures in this kind of usage\n\n // Add any player entities into the new chunk that are inside the chunk's area\n for (EntityPlayerMP player : world.getPlayers(EntityPlayerMP.class, new Predicate<EntityPlayerMP>() {\n @Override\n public boolean apply(EntityPlayerMP playerIn)\n {\n double x = chunk.x << 4;\n double z = chunk.z << 4;\n return playerIn.posX >= x && playerIn.posX < x + 16 && playerIn.posZ >= z && playerIn.posZ < z + 16;\n }\n }))\n {\n chunk.addEntity(player);\n }\n\n return chunk;\n }\n }\n catch (IOException e)\n {\n WorldUtils.logger.warn(\"Exception while trying to load chunk ({}, {}) - IOException\", pos.x, pos.z);\n }\n }\n\n return null;\n }\n\n private void updatePlayerChunkMap(WorldServer world, ChunkPos pos, Chunk chunk)\n {\n PlayerChunkMap map = world.getPlayerChunkMap();\n PlayerChunkMapEntry entry = map.getEntry(pos.x, pos.z);\n\n if (entry != null)\n {\n try\n {\n field_PlayerChunkMapEntry_chunk.set(entry, chunk);\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"Failed to update PlayerChunkMapEntry for chunk ({}, {})\", pos.x, pos.z, e);\n }\n }\n }\n\n private void sendChunkToWatchers(final WorldServer world, final Chunk chunk)\n {\n for (EntityPlayerMP player : world.getPlayers(EntityPlayerMP.class, new Predicate<EntityPlayerMP>() {\n @Override\n public boolean apply(EntityPlayerMP playerIn)\n {\n return world.getPlayerChunkMap().isPlayerWatchingChunk(playerIn, chunk.x, chunk.z);\n }\n }))\n {\n player.connection.sendPacket(new SPacketUnloadChunk(chunk.x, chunk.z));\n Packet<?> packet = new SPacketChunkData(chunk, 65535);\n player.connection.sendPacket(packet);\n world.getEntityTracker().sendLeashedEntitiesInChunk(player, chunk);\n }\n }\n\n private Map<String, Map<Long, String>> getChangeMap(Int2ObjectOpenHashMap<Map<String, Map<Long, String>>> mainMap, World world)\n {\n int dim = world.provider.getDimension();\n Map<String, Map<Long, String>> map = mainMap.get(dim);\n\n if (map == null)\n {\n map = new HashMap<String, Map<Long, String>>();\n mainMap.put(dim, map);\n }\n\n return map;\n }\n\n private void addChangedChunkLocation(World world, ChunkPos pos, ChangeType type, String worldName, String user)\n {\n Map<String, Map<Long, String>> mainMap = null;\n\n if (type == ChangeType.CHUNK_CHANGE)\n {\n mainMap = this.getChangeMap(this.changedChunks, world);\n }\n else if (type == ChangeType.BIOME_IMPORT)\n {\n mainMap = this.getChangeMap(this.importedBiomes, world);\n }\n else\n {\n mainMap = this.getChangeMap(this.setBiomes, world);\n }\n\n Map<Long, String> map = mainMap.get(user);\n\n if (map == null)\n {\n map = new HashMap<Long, String>();\n mainMap.put(user, map);\n }\n\n Long posLong = ChunkPos.asLong(pos.x, pos.z);\n map.put(posLong, worldName);\n\n // A chunk change also removes an earlier biome import for that chunk\n if (type == ChangeType.CHUNK_CHANGE)\n {\n map = this.getChangeMap(this.importedBiomes, world).get(user);\n\n if (map != null)\n {\n map.remove(posLong);\n }\n\n map = this.getChangeMap(this.setBiomes, world).get(user);\n\n if (map != null)\n {\n map.remove(posLong);\n }\n }\n\n this.dirty = true;\n }\n\n public void readFromDisk(World world)\n {\n if ((world instanceof WorldServer) == false)\n {\n return;\n }\n\n try\n {\n File saveDir = getAlternateWorldsBaseDirectory();\n\n if (saveDir == null || saveDir.isDirectory() == false)\n {\n return;\n }\n\n final int dim = world.provider.getDimension();\n\n String[] files = saveDir.list(new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name)\n {\n return name.startsWith(\"dim\" + dim + \"_\") && name.endsWith(\"_changed_chunks.nbt\");\n }\n \n });\n\n for (String fileName : files)\n {\n File file = new File(saveDir, fileName);\n\n if (file.exists() && file.isFile())\n {\n NBTTagCompound nbt = CompressedStreamTools.readCompressed(new FileInputStream(file));\n this.readFromNBT(this.getChangeMap(this.changedChunks, world), nbt, TAG_CHANGED_CHUNKS);\n this.readFromNBT(this.getChangeMap(this.importedBiomes, world), nbt, TAG_BIOMES_IMPORTED);\n this.readFromNBT(this.getChangeMap(this.setBiomes, world), nbt, TAG_BIOMES_SET);\n }\n }\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"Failed to read exported changed chunks data from file!\");\n }\n }\n\n public void writeToDisk(World world)\n {\n if (this.dirty == false || (world instanceof WorldServer) == false)\n {\n return;\n }\n\n try\n {\n File saveDir = getAlternateWorldsBaseDirectory();\n\n if (saveDir == null || (saveDir.exists() == false && saveDir.mkdirs() == false))\n {\n WorldUtils.logger.warn(\"Failed to create the directory '\" + saveDir + \"'\");\n return;\n }\n\n final int dim = world.provider.getDimension();\n\n for (String user : this.getChangeMap(this.changedChunks, world).keySet())\n {\n String fileName = \"dim\" + dim + \"_\" + user + \"_changed_chunks.nbt\";\n File fileTmp = new File(saveDir, fileName + \".tmp\");\n File fileReal = new File(saveDir, fileName);\n CompressedStreamTools.writeCompressed(this.writeToNBT(world, user), new FileOutputStream(fileTmp));\n\n if (fileReal.exists())\n {\n fileReal.delete();\n }\n\n fileTmp.renameTo(fileReal);\n }\n\n this.dirty = false;\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"Failed to write exported changed chunks data to file!\");\n }\n }\n\n private void readFromNBT(Map<String, Map<Long, String>> mapIn, NBTTagCompound nbt, String tagName)\n {\n if (nbt == null || StringUtils.isBlank(nbt.getString(\"user\")))\n {\n return;\n }\n\n Map<Long, String> chunks = new HashMap<Long, String>();\n NBTTagList list = nbt.getTagList(tagName, Constants.NBT.TAG_COMPOUND);\n\n for (int i = 0; i < list.tagCount(); i++)\n {\n NBTTagCompound tag = list.getCompoundTagAt(i);\n String worldName = tag.getString(\"world\");\n int[] arr = tag.getIntArray(\"chunks\");\n\n for (int j = 0; j < arr.length - 1; j += 2)\n {\n long loc = ((long) arr[j + 1]) << 32 | (long) arr[j];\n chunks.put(loc, worldName);\n }\n }\n\n String user = nbt.getString(\"user\");\n mapIn.put(user, chunks);\n\n WorldUtils.logger.info(\"ChunkChanger: Read {} stored chunk modifications of type '{}' from file for user {}\", chunks.size(), tagName, user);\n }\n\n public NBTTagCompound writeToNBT(World world, String user)\n {\n NBTTagCompound nbt = new NBTTagCompound();\n final int dim = world.provider.getDimension();\n this.writeToNBT(this.getChangeMap(this.changedChunks, world), dim, user, nbt, TAG_CHANGED_CHUNKS);\n this.writeToNBT(this.getChangeMap(this.importedBiomes, world), dim, user, nbt, TAG_BIOMES_IMPORTED);\n this.writeToNBT(this.getChangeMap(this.setBiomes, world), dim, user, nbt, TAG_BIOMES_SET);\n\n return nbt;\n }\n\n private NBTTagCompound writeToNBT(Map<String, Map<Long, String>> mapIn, int dimension, String user, NBTTagCompound nbt, String tagName)\n {\n Map<Long, String> modifiedChunks = mapIn.get(user);\n\n if (modifiedChunks == null)\n {\n return nbt;\n }\n\n Map<String, List<Long>> changesPerWorld = new HashMap<String, List<Long>>();\n\n for (Map.Entry<Long, String> entry : modifiedChunks.entrySet())\n {\n String worldName = entry.getValue();\n List<Long> locations = changesPerWorld.get(worldName);\n\n if (locations == null)\n {\n locations = new ArrayList<Long>();\n changesPerWorld.put(worldName, locations);\n }\n\n locations.add(entry.getKey());\n }\n\n NBTTagList list = new NBTTagList();\n\n for (Map.Entry<String, List<Long>> entry : changesPerWorld.entrySet())\n {\n NBTTagCompound tag = new NBTTagCompound();\n tag.setString(\"world\", entry.getKey());\n\n List<Long> chunks = entry.getValue();\n int[] chunksArr = new int[chunks.size() * 2];\n int i = 0;\n\n for (long chunk : chunks)\n {\n chunksArr[i ] = (int) (chunk & 0xFFFFFFFF);\n chunksArr[i + 1] = (int) (chunk >>> 32);\n i += 2;\n }\n\n tag.setIntArray(\"chunks\", chunksArr);\n list.appendTag(tag);\n }\n\n nbt.setString(\"user\", user);\n nbt.setInteger(\"dim\", dimension);\n nbt.setTag(tagName, list);\n\n return nbt;\n }\n\n public void loadBiomesFromAlternateWorld(World worldIn, ChunkPos pos, String worldName, String user)\n {\n if ((worldIn instanceof WorldServer) == false)\n {\n return;\n }\n\n WorldServer world = (WorldServer) worldIn;\n\n if (StringUtils.isBlank(worldName) == false)\n {\n AnvilChunkLoader loader = this.getChunkLoaderForAlternateWorld(world, worldName);\n\n try\n {\n DataInputStream stream = RegionFileCache.getChunkInputStream(loader.chunkSaveLocation, pos.x, pos.z);\n\n if (stream != null)\n {\n NBTTagCompound nbt = CompressedStreamTools.read(stream);\n\n if (nbt != null && nbt.hasKey(\"Level\", Constants.NBT.TAG_COMPOUND))\n {\n NBTTagCompound level = nbt.getCompoundTag(\"Level\");\n\n if (level.hasKey(\"Biomes\", Constants.NBT.TAG_BYTE_ARRAY))\n {\n byte[] biomes = level.getByteArray(\"Biomes\");\n\n if (biomes.length == 256)\n {\n Chunk chunkCurrent = world.getChunk(pos.x, pos.z);\n chunkCurrent.setBiomeArray(biomes);\n chunkCurrent.markDirty();\n this.sendChunkToWatchers(world, chunkCurrent);\n this.addChangedChunkLocation(world, pos, ChangeType.BIOME_IMPORT, worldName, user);\n }\n }\n }\n }\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"ChunkUtils#loadBiomesFromAlternateWorld(): Failed to read chunk data for chunk ({}, {}) ({})\",\n pos.x, pos.z, e.getMessage());\n }\n }\n }\n\n public void setBiome(World worldIn, ChunkPos pos, Biome biome, String user)\n {\n if ((worldIn instanceof WorldServer) == false || biome == null)\n {\n return;\n }\n\n WorldServer world = (WorldServer) worldIn;\n Chunk chunkCurrent = world.getChunk(pos.x, pos.z);\n byte[] biomes = new byte[256];\n\n Arrays.fill(biomes, (byte) Biome.getIdForBiome(biome));\n chunkCurrent.setBiomeArray(biomes);\n chunkCurrent.markDirty();\n this.sendChunkToWatchers(world, chunkCurrent);\n this.addChangedChunkLocation(world, pos, ChangeType.BIOME_SET, \"\", user);\n }\n\n public void loadChunkFromAlternateWorld(World worldIn, ChunkPos pos, String worldName, String user)\n {\n if ((worldIn instanceof WorldServer) == false)\n {\n return;\n }\n\n WorldServer world = (WorldServer) worldIn;\n\n if (StringUtils.isBlank(worldName) == false)\n {\n Chunk chunk = this.loadChunk(world, pos, worldName);\n\n if (chunk != null)\n {\n this.sendChunkToWatchers(world, world.getChunk(pos.x, pos.z));\n this.addChangedChunkLocation(world, pos, ChangeType.CHUNK_CHANGE, worldName, user);\n }\n }\n }\n\n public void clearChangedChunksForUser(World world, String user)\n {\n this.getChangeMap(this.changedChunks, world).remove(user);\n }\n}" ]
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.relauncher.Side; import fi.dy.masa.worldutils.item.ItemChunkWand; import fi.dy.masa.worldutils.network.MessageChunkChanges; import fi.dy.masa.worldutils.network.MessageKeyPressed; import fi.dy.masa.worldutils.network.PacketHandler; import fi.dy.masa.worldutils.reference.HotKeys; import fi.dy.masa.worldutils.registry.WorldUtilsItems; import fi.dy.masa.worldutils.util.ChunkUtils;
package fi.dy.masa.worldutils.event; public class PlayerEventHandler { @SubscribeEvent public void onLeftClickBlock(PlayerInteractEvent.LeftClickBlock event) { EntityPlayer player = event.getEntityPlayer(); // You can only left click with the main hand, so this is fine here ItemStack stack = player.getHeldItemMainhand(); if (stack.isEmpty()) { return; } World world = event.getWorld(); BlockPos pos = event.getPos(); EnumFacing face = event.getFace(); if (stack.getItem() == WorldUtilsItems.CHUNK_WAND) { ((ItemChunkWand) stack.getItem()).onLeftClickBlock(player, world, stack, pos, player.dimension, face); event.setCanceled(true); } } @SubscribeEvent public void onLeftClickAir(PlayerInteractEvent.LeftClickEmpty event) { if (event.getSide() == Side.CLIENT) { ItemStack stack = event.getEntityPlayer().getHeldItemMainhand(); if (stack.isEmpty() == false && stack.getItem() == WorldUtilsItems.CHUNK_WAND) { PacketHandler.INSTANCE.sendToServer(new MessageKeyPressed(HotKeys.KEYCODE_CUSTOM_1)); } } } @SubscribeEvent public void onPlayerLoggedIn(PlayerLoggedInEvent event) { if (event.player instanceof EntityPlayerMP) { sendChunkChanges(event.player.getEntityWorld(), (EntityPlayerMP) event.player); } } @SubscribeEvent public void onPlayerChangedDimension(PlayerChangedDimensionEvent event) { if (event.player instanceof EntityPlayerMP) { World world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(event.toDim); if (world != null) { sendChunkChanges(world, (EntityPlayerMP) event.player); } } } private static void sendChunkChanges(World world, EntityPlayerMP player) { NBTTagCompound nbt = ChunkUtils.instance().writeToNBT(world, player.getName()); if (nbt.isEmpty() == false) {
PacketHandler.INSTANCE.sendTo(new MessageChunkChanges(nbt), player);
1
eXsio/nestedj
src/main/java/pl/exsio/nestedj/DelegatingNestedNodeRepository.java
[ "public class InvalidNodeException extends RuntimeException {\n\n public InvalidNodeException(String msg) {\n super(msg);\n }\n}", "public class InvalidParentException extends RuntimeException {\n\n public InvalidParentException(String msg) {\n super(msg);\n }\n}", "public class RepositoryLockedException extends RuntimeException {\n\n public RepositoryLockedException(String msg) {\n super(msg);\n }\n}", "public interface NestedNode<ID extends Serializable> {\n\n /**\n * Standarized Field Names used internally by NestedJ.\n * Any Java class that implements the NestedNode interface should have fields with names matching the below constants.\n */\n String LEFT = \"treeLeft\";\n String RIGHT = \"treeRight\";\n String LEVEL = \"treeLevel\";\n String PARENT_ID = \"parentId\";\n String ID = \"id\";\n\n /**\n * Should be PK if using Database.\n *\n * @return unique Identifier of the Entity/Object.\n */\n ID getId();\n\n /**\n * @return Nested Set Model LEFT value\n */\n Long getTreeLeft();\n\n /**\n * @return Nested Set Model RIGHT value\n */\n Long getTreeRight();\n\n /**\n * @return Nested Set Model LEVEL value\n */\n Long getTreeLevel();\n\n /**\n * Should be a FK if using Database.\n *\n * @return Parent Idendifier\n */\n ID getParentId();\n\n /**\n * Sets the unique Identifier of the Entity/Object.\n *\n * @param id - unique Identifier of the Entity/Object.\n */\n void setId(ID id);\n\n /**\n * Sets the Nested Set Model LEFT value\n *\n * @param treeLeft - Nested Set Model LEFT value\n */\n void setTreeLeft(Long treeLeft);\n\n /**\n * Sets the Nested Set Model RIGHT value\n *\n * @param treeRight - Nested Set Model RIGHT value\n */\n void setTreeRight(Long treeRight);\n\n /**\n * Sets the Nested Set Model LEVEL value\n *\n * @param treeLevel - Nested Set Model LEVEL value\n */\n void setTreeLevel(Long treeLevel);\n\n /**\n * Sets the Parent Idendifier\n *\n * @param parent - Parent Idendifier\n */\n void setParentId(ID parent);\n\n}", "public class NestedNodeInfo<ID extends Serializable> {\n\n private final ID id;\n\n private final ID parentId;\n\n private final Long left;\n\n private final Long right;\n\n private final Long level;\n\n public NestedNodeInfo(ID id, ID parentId, Long left, Long right, Long level) {\n this.id = id;\n this.parentId = parentId;\n this.left = left;\n this.right = right;\n this.level = level;\n }\n\n public ID getId() {\n return id;\n }\n\n public ID getParentId() {\n return parentId;\n }\n\n public Long getLeft() {\n return left;\n }\n\n public Long getRight() {\n return right;\n }\n\n public Long getLevel() {\n return level;\n }\n\n @Override\n public String toString() {\n return \"NestedNodeInfo{\" +\n \"id=\" + id +\n \", parentId=\" + parentId +\n \", left=\" + left +\n \", right=\" + right +\n \", level=\" + level +\n '}';\n }\n}", "public interface Tree<ID extends Serializable, N extends NestedNode<ID>> {\n \n void setChildren(List<Tree<ID, N>> children);\n \n void addChild(Tree<ID, N> child);\n \n List<Tree<ID, N>> getChildren();\n \n Tree<ID, N> getParent();\n \n void setParent(Tree<ID, N> parent);\n \n N getNode();\n \n void setNode(N node);\n \n}" ]
import pl.exsio.nestedj.delegate.*; import pl.exsio.nestedj.ex.InvalidNodeException; import pl.exsio.nestedj.ex.InvalidParentException; import pl.exsio.nestedj.ex.RepositoryLockedException; import pl.exsio.nestedj.model.NestedNode; import pl.exsio.nestedj.model.NestedNodeInfo; import pl.exsio.nestedj.model.Tree; import java.io.Serializable; import java.util.List; import java.util.Optional;
return this.retriever.getTreeAsList(node); } /** * {@inheritDoc} */ @Override public List<N> getChildren(N node) { return this.retriever.getChildren(node); } /** * {@inheritDoc} */ @Override public Optional<N> getParent(N node) { return this.retriever.getParent(node); } /** * {@inheritDoc} */ @Override public Optional<N> getPrevSibling(N node) { return this.retriever.getPrevSibling(node); } /** * {@inheritDoc} */ @Override public Optional<N> getNextSibling(N node) { return this.retriever.getNextSibling(node); } /** * {@inheritDoc} */ @Override public Tree<ID, N> getTree(N node) { return this.retriever.getTree(node); } /** * {@inheritDoc} */ @Override public List<N> getParents(N node) { return this.retriever.getParents(node); } /** * {@inheritDoc} */ @Override public void rebuildTree() { lockRepository(rebuilder::rebuildTree); } /** * {@inheritDoc} */ @Override public void destroyTree() { lockRepository(rebuilder::destroyTree); } /** * {@inheritDoc} */ @Override public void insertAsFirstRoot(N node) { lockNode(node, () -> { Optional<N> firstRoot = retriever.findFirstRoot(); if (firstRoot.isPresent()) { if (differentNodes(node, firstRoot.get())) { insertOrMove(node, firstRoot.get(), NestedNodeHierarchyManipulator.Mode.PREV_SIBLING); } } else { insertAsFirstNode(node); } }); } /** * {@inheritDoc} */ @Override public void insertAsLastRoot(N node) { lockNode(node, () -> { Optional<N> lastRoot = retriever.findLastRoot(); if (lastRoot.isPresent()) { if (differentNodes(node, lastRoot.get())) { insertOrMove(node, lastRoot.get(), NestedNodeHierarchyManipulator.Mode.NEXT_SIBLING); } } else { insertAsFirstNode(node); } }); } private boolean differentNodes(N node, N firstRoot) { return !firstRoot.getId().equals(node.getId()); } private void insertAsFirstNode(N node) { inserter.insertAsFirstNode(node); } public boolean isAllowNullableTreeFields() { return allowNullableTreeFields; } public void setAllowNullableTreeFields(boolean allowNullableTreeFields) { this.allowNullableTreeFields = allowNullableTreeFields; } private void lockNode(N node, TreeModifier modifier) { if (!lock.lockNode(node)) {
throw new RepositoryLockedException(String.format("Nested Node Repository is locked for Node %s. Try again later.", node));
2
wrey75/WaveCleaner
src/main/java/com/oxande/wavecleaner/ui/JFilterMeter.java
[ "public class AudioFilter extends UGen {\n\tprivate static Logger LOG = LogFactory.getLog(AudioFilter.class);\n\n\t/**\n\t * The enabled switch. This switch is NOT listed in the parameters because\n\t * it is accessed by setEnabled(). But the change can be listened though the\n\t * classic listener.\n\t * \n\t */\n\tpublic static final String ENABLE = \"enable\";\n\n\t/**\n\t * Listener to be informed when a value of a control has changed. Used\n\t * mainly by the controller component to react when a value has been\n\t * changed. This avoid to update the value when the user changed it and it\n\t * is also very cool in case of the preamplifier where the AUTO-LIMITER will\n\t * change its gain automatically!\n\t * \n\t * @author wrey75\n\t *\n\t */\n\tpublic static interface ControlListener {\n\t\t/**\n\t\t * When a control has its value changed, you are informed. Note a way to\n\t\t * do is to call the parameter to get the formatted value rather than\n\t\t * the basic floating one.\n\t\t * \n\t\t * @param filter\n\t\t * the filter who generates the change\n\t\t * @param name\n\t\t * the name of the control\n\t\t * @param val\n\t\t * the value of the control (expressed as a float).\n\t\t */\n\t\tpublic void controlChanged(AudioFilter filter, String name, float val);\n\t}\n\n\tprivate StereoSampleQueue queue;\n\tprivate UGen audio;\n\tprotected Map<String, Parameter> parameters = new HashMap<>();\n\n\t/** The original stream (not filtered) */\n\tprivate UGen originalStream;\n\n\t/** buffer we use to read from the stream */\n\tprivate MultiChannelBuffer buffer;\n\n\t/** where in the buffer we should read the next sample from */\n\tprivate float[][] samples = new float[2][];\n\tprivate int sampleIndex;\n\n\t// private UGenInput enabled = new UGenInput(InputType.CONTROL, 1);\n\n\tprivate static final Function<Float, String> BOOLEAN_FORMATTER = (v) -> {\n\t\treturn (v > 0.5f ? \"ON\" : \"OFF\");\n\t};\n\n\tprotected Parameter addBooleanParameter(String name, boolean defaultValue) {\n\t\treturn addParameter(name, 0.0f, 1.0f, 1.0f, ConvertUtils.bool2flt(defaultValue), BOOLEAN_FORMATTER);\n\t}\n\n\tprotected synchronized Parameter addParameter(String name, float min, float max, float defaultValue, float tick,\n\t\t\tFunction<Float, String> formatter) {\n\t\tParameter p = new Parameter(name, min, max, defaultValue, formatter);\n\t\tp.setTick(tick);\n\t\tthis.parameters.put(name.toUpperCase(), p);\n\t\treturn p;\n\t}\n\n\tprotected synchronized Parameter addSelectorParameter(String name, int nb) {\n\t\tParameter p = new Parameter(name, 0, nb - 1, 0, v -> String.valueOf(v));\n\t\tthis.parameters.put(name.toUpperCase(), p);\n\t\treturn p;\n\t}\n\n\t/**\n\t * Get the original stream\n\t * \n\t * @return the original stream\n\t */\n\tpublic UGen getOriginalStream() {\n\t\treturn this.originalStream;\n\t}\n\n\t/**\n\t * Set the parameter with the specified name.\n\t * \n\t * @param name\n\t * name of the parameter (case insensitive).\n\t * @param value\n\t * the value.\n\t * @return the effective value set.\n\t */\n\tpublic float setControl(String name, float value) {\n\t\tParameter p = getParameter(name);\n\t\tif (p == null) {\n\t\t\tLOG.error(\"Parameter '{}' unknown.\", name);\n\t\t\treturn 0.0f;\n\t\t}\n\t\tp.setValue(value);\n\t\treturn p.getValue();\n\t}\n\t\n\t/**\n\t * Add a value to the control.\n\t * \n\t * @param name the control name\n\t * @param value the value to add.\n\t */\n\tpublic float addToControl(String name, float value) {\n\t\tParameter p = getParameter(name);\n\t\tif (p == null) {\n\t\t\tLOG.error(\"Parameter '{}' unknown.\", name);\n\t\t\treturn 0;\n\t\t}\n\t\tfloat newValue = value;\n\t\tsynchronized(p){\n\t\t\tnewValue += p.getValue();\n\t\t\tp.setValue(newValue);\n\t\t}\n\t\treturn newValue;\n\t}\n\n\t/**\n\t * Get the parameter with the specified name.\n\t * \n\t * @param name\n\t * name of the parameter (case insensitive)\n\t * @return the value.\n\t */\n\tpublic float getControl(String name) {\n\t\tParameter p = getParameter(name);\n\t\tif (p == null) {\n\t\t\tLOG.error(\"Parameter '{}' unknown.\", name);\n\t\t\treturn 0.0f;\n\t\t}\n\t\treturn p.getValue();\n\t}\n\t\n\t/**\n\t * Get the number of samples for the specified value. The value is stored\n\t * as a number of seconds (usually, a fraction of second).\n\t * \n\t * @param name the parameter name\n\t * @return the number of samples specified by the duration expressed in seconds.\n\t */\n\tpublic int getSampleControl(String name) {\n\t\tParameter p = getParameter(name);\n\t\tif (p == null) {\n\t\t\tLOG.error(\"Parameter '{}' unknown.\", name);\n\t\t\treturn 0;\n\t\t}\n\t\treturn (int)(p.getValue() * sampleRate());\n\t}\n\n\tpublic int getIntControl(String name) {\n\t\tfloat v = this.getControl(name);\n\t\treturn (int) v;\n\t}\n\n\tpublic Parameter getParameter(String name) {\n\t\tString key = name.toUpperCase().trim();\n\t\tParameter p = this.parameters.get(key);\n\t\treturn p;\n\t}\n\n\t/**\n\t * Enables or disables the filter. When disabled, the filter is bypassed but\n\t * these parameters are kept. The already calculated audio is played first\n\t * and when all the buffer is consumed, we just swap to the original input.\n\t * \n\t * <p>\n\t * Due to the expected \"fast\" switch, we do not generate events to inform\n\t * the use the filter is now bypassed.\n\t * </p>\n\t * \n\t * @param b\n\t * true to enable the filter (or false to bypass it).\n\t */\n\tpublic void setEnable(boolean b) {\n\t\tgetParameter(ENABLE).setValue(b ? 1.0f : 0.0f);\n\t\tLOG.info(\"Filter {} {}\", this.getClass().getSimpleName(), (getControl(ENABLE) > 0.5f ? \"enabled\" : \"disabled\"));\n\t}\n\n\t/**\n\t * Resize an array of floats\n\t * \n\t * @param array\n\t * the original array or null\n\t * @param newSize\n\t * the new size\n\t * @return an array having the new size and the values from the original\n\t * array copied.\n\t */\n\tpublic static float[] newFloatArray(float[] array, int newSize) {\n\t\tfloat[] newArray = new float[newSize];\n\t\tif (array != null) {\n\t\t\tint len = Math.min(newSize, array.length);\n\t\t\tSystem.arraycopy(array, 0, newArray, 0, len);\n\t\t}\n\t\treturn newArray;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn getControl(ENABLE) > 0.5f;\n\t}\n\n\tprotected float[][] loadSamples(int len) {\n\t\treturn loadSamples(len, 0);\n\t}\n\n\t/** \n\t * Load samples including an extra an extra size of\n\t * bytes.\n\t * \n\t * @param len the length to get from the buffer\n\t * @param extra extra samples read again at the next\n\t * read.\n\t * \n\t * @return an stereo array of the requested number of samples.\n\t */\n\tprotected float[][] loadSamples(int len, int extra) {\n\t\tfloat[][] loaded = queue.getSamples(len, extra);\n\t\treturn loaded;\n\t}\n\n\tpublic class Parameter {\n\t\tprivate String name;\n\t\tprivate int type;\n\t\tprivate float min;\n\t\tprivate float max;\n\t\tprivate UGenInput input;\n\t\tprivate float tick = 0.1f;\n\t\tprivate boolean locked = false;\n\t\tprivate Function<Float, String> formatter;\n\n\t\tprivate ListenerManager<ControlListener> listenerManager = new ListenerManager<>();\n\n\t\t/**\n\t\t * Return the parameters in a list.\n\t\t * \n\t\t * @return the control parameters for the filter.\n\t\t */\n\t\tpublic List<Parameter> getParameters() {\n\t\t\treturn new ArrayList<Parameter>(parameters.values());\n\t\t}\n\n\t\tParameter(String name, float min, float max, float defaultValue, Function<Float, String> formatter) {\n\t\t\tthis.name = name;\n\t\t\tthis.min = min;\n\t\t\tthis.max = max;\n\t\t\tthis.input = new UGenInput(InputType.CONTROL);\n\t\t\tthis.setValue(defaultValue);\n\t\t\tthis.formatter = formatter;\n\t\t}\n\n\t\t/**\n\t\t * Add the listener for callback when a control change.\n\t\t * \n\t\t * @param listener\n\t\t * the listener to call when a control is changed.\n\t\t */\n\t\tpublic void addListener(ControlListener listener) {\n\t\t\tlistenerManager.add(listener);\n\t\t}\n\n\t\tpublic void removeListener(ControlListener listener) {\n\t\t\tlistenerManager.remove(listener);\n\t\t}\n\t\t\n\t\tpublic float getTick() {\n\t\t\treturn this.tick;\n\t\t}\n\n\t\tpublic void setTick(float tick) {\n\t\t\tthis.tick = tick;\n\t\t}\n\t\t\n\t\tpublic void lock(boolean b) {\n\t\t\tthis.locked = b;\n\t\t}\n\t\t\n\t\tpublic boolean isLocked() {\n\t\t\treturn this.locked;\n\t\t}\n\n\t\tsynchronized boolean setValue(float v) {\n\t\t\tfloat val; // Needed to be final\n\t\t\tif(this.locked){\n\t\t\t\tLOG.warn(\"Parameter '{}' is currently locked.\", name);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (v < min) {\n\t\t\t\tLOG.warn(\"Parameter '{}' set to minimum {} instead of {}\", name, min, v);\n\t\t\t\tval = min;\n\t\t\t} else if (v > max) {\n\t\t\t\tLOG.warn(\"Parameter '{}' set to maximum {} instead of {}\", name, max, v);\n\t\t\t\tval = max;\n\t\t\t} else {\n\t\t\t\tval = v;\n\t\t\t}\n\t\t\tif (val != this.input.getLastValue()) {\n\t\t\t\tLOG.debug(\"Parameter '{}' set to {}\", name, val);\n\t\t\t\tthis.input.setLastValue(val);\n\t\t\t\tlistenerManager.publish((listener) -> {\n\t\t\t\t\tlistener.controlChanged(AudioFilter.this, getName(), val);\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic float getValue() {\n\t\t\tfloat v = this.input.getLastValue();\n\t\t\t// LOG.warn(\"Parameter '{}' returns {}\", name, v);\n\t\t\treturn v;\n\t\t}\n\n\t\tpublic String getFormattedValue() {\n\t\t\tfloat v = this.input.getLastValue();\n\t\t\treturn this.formatter.apply(v);\n\t\t}\n\n\t\tpublic String getName() {\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic int getType() {\n\t\t\treturn type;\n\t\t}\n\n\t\tpublic float getMinimum() {\n\t\t\treturn min;\n\t\t}\n\n\t\tpublic float getMaximum() {\n\t\t\treturn max;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void addInput(UGen input) {\n\t\taudio = input;\n\t\tif (audio != null) {\n\t\t\tif (input instanceof AudioFilter) {\n\t\t\t\tLOG.info(\"Filter {} attached to {}\", audio, this);\n\t\t\t\tthis.originalStream = ((AudioFilter) input).getOriginalStream();\n\t\t\t} else if (input instanceof FilePlayer) {\n\t\t\t\tLOG.info(\"FilePlayer {} attached to {}\", audio, this);\n\t\t\t\tthis.originalStream = audio;\n\t\t\t}\n\t\t\tthis.queue = new StereoSampleQueue(this.audio);\n\t\t}\n\t}\n\n\t@Override\n\tprotected void removeInput(UGen input) {\n\t\tif (audio == input) {\n\t\t\taudio = null;\n\t\t\tthis.queue = null;\n\t\t}\n\t}\n\n\t/**\n\t * Check if we are bypassing the filter. This method returns the opposite\n\t * value compared to isEnabled() except in a small range of time. You should\n\t * refer the usage of {@link AudioFilter#isEnabled()} except if you need a\n\t * real time (less than 20 milliseconds) information. Note also if this is\n\t * the first filter of a pipeline, the sound currently played can be still\n\t * filtered even you are already bypassing the filters.\n\t * \n\t * @return true is the filter is bypassed.\n\t */\n\tpublic final boolean isBypassing() {\n\t\tif (sampleIndex > samples[0].length) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tfinal protected void uGenerate(float[] channels) {\n\t\t++sampleIndex;\n\t\tif (sampleIndex >= samples[0].length) {\n\t\t\t// We have to consume ALL the audio before switching off the filter.\n\t\t\tsynchronized (this) {\n\t\t\t\tif (isEnabled()) {\n\t\t\t\t\t// We have to synchronize here because the\n\t\t\t\t\t// synchronization is not inherited in JAVA\n\t\t\t\t\t// (see\n\t\t\t\t\t// https://stackoverflow.com/questions/15998335/is-synchronized-inherited-in-java)\n\t\t\t\t\tsamples = nextSamples();\n\t\t\t\t} else {\n\t\t\t\t\t// Just load some samples\n\t\t\t\t\tsamples = loadSamples(500);\n\t\t\t\t}\n\t\t\t\tsampleIndex = 0; // Reset.\n\t\t\t}\n\t\t}\n\n\t\tchannels[0] = samples[0][sampleIndex];\n\t\tchannels[1] = samples[1][sampleIndex];\n\t}\n\n\t/**\n\t * Create an audio filter. You should always call this method because it\n\t * initialize the stream and creates a buffer.\n\t * \n\t * @param iStream\n\t * the input stream.\n\t */\n\tpublic AudioFilter() {\n\t\t// Create empty samples array\n\t\tthis.samples = new float[2][];\n\t\tthis.samples[0] = new float[0];\n\t\tthis.samples[1] = new float[0];\n\t\tthis.sampleIndex = 0;\n\t\tthis.init(1024);\n\t\tthis.addBooleanParameter(ENABLE, true);\n\t}\n\n\t/**\n\t * Construct a FilePlayer that will read from iFileStream.\n\t * \n\t * @param iStream\n\t * AudioRecordingStream: the stream this should read from\n\t * @param bufferSize\n\t * the size in samples of the buffer. Try to keep it the lowest\n\t * possible (less than 512 bytes if possible) to ensure the\n\t * updated parameters are taken into account quickly.\n\t * \n\t * @example Synthesis/filePlayerExample\n\t */\n\tpublic void init(int bufferSize) {\n\t\tthis.buffer = new MultiChannelBuffer(bufferSize, 2);\n\t}\n\n\t/**\n\t * Get the buffer size of the stream.\n\t * \n\t * @return the buffer size\n\t */\n\tfinal public int getBufferSize() {\n\t\treturn this.buffer.getBufferSize();\n\t}\n\n\t/**\n\t * Overwrite this method if you want to work with the current buffer. This\n\t * is quite ideal for applying FFT and some other stuff. Basically, you have\n\t * to rewrite the contents of the {@link MultiChannelBuffer} which contains\n\t * the samples.\n\t * \n\t * <p>\n\t * Currently this method does nothing.\n\t * </p>\n\t * \n\t * @param buff\n\t * the buffer to modify.\n\t */\n\tprotected void process(MultiChannelBuffer buff) {\n\t\tLOG.debug(\"process() MUST BE IMPLEMENTED.\");\n\t}\n\n\t/**\n\t * Process the next part. wHen the buffer is empty, process the next one.\n\t * This work should be done as fast as possible because we read the next\n\t * samples.\n\t * \n\t * <p>\n\t * Basically, the contract is to read new data (using the\n\t * {@link AudioStream#read(MultiChannelBuffer)}) and processing the new data\n\t * loaded. In the default implementation, the next buffer is read and\n\t * process by the {@link AudioFilter#process(MultiChannelBuffer)} method. If\n\t * you need to work with ahead samples, this method is the correct one to\n\t * modify.\n\t * </p>\n\t * \n\t * @param stream\n\t * the audio stream (we have to read the next samples)\n\t * @param buff\n\t * the current {@link MultiChannelBuffer} to store the STEREO\n\t * data.\n\t * @return a new (or the current) {@link MultiChannelBuffer} where we will\n\t * read the next samples.\n\t * \n\t */\n\tprotected MultiChannelBuffer processNext(MultiChannelBuffer buf) {\n\t\tfloat[][] samples = loadSamples(buf.getBufferSize());\n\t\tbuf.setChannel(0, samples[0]);\n\t\tbuf.setChannel(1, samples[1]);\n\t\tprocess(buf);\n\t\treturn buf;\n\t}\n\n\t/**\n\t * The basic way. Returns the next samples available. The default\n\t * implementation relies on processing buffers by buffer size of samples.\n\t * But in some cases, the input buffer can overlap then we create the exact\n\t * portion of output necessary.\n\t * \n\t * @return an array of floats containing the left side on the index 0 and\n\t * the right side in the index 1. The left and right channels must\n\t * have the same number of samples and 2 channels only are accepted.\n\t */\n\tprotected float[][] nextSamples() {\n\t\t// Generally return the same buffer but not a requirement.\n\t\tthis.buffer = processNext(this.buffer);\n\t\tif (this.buffer == null) {\n\t\t\tthrow new IllegalArgumentException(\"The returned buffer is null!\");\n\t\t} else if (this.buffer.getChannelCount() != Minim.STEREO) {\n\t\t\tthrow new IllegalArgumentException(\"The returned buffer must be STEREO!\");\n\t\t}\n\n\t\t// Create a new array for output\n\t\tfloat[][] ret = new float[2][];\n\t\tret[0] = this.buffer.getChannel(0);\n\t\tret[1] = this.buffer.getChannel(1);\n\t\treturn ret;\n\t}\n\t\n\t/**\n\t * Get the next power of 2.\n\t * Algorithm from <href=\"https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2\">Stack\n\t * Overflow</a>.\n\t * \n\t * @param v the original value to increase.\n\t * @return the next power of two.\n\t */\n\tpublic static int nextPower2(int v ){\n\t\tv--;\n\t\tv |= v >> 1;\n\t\tv |= v >> 2;\n\t\tv |= v >> 4;\n\t\tv |= v >> 8;\n\t\tv |= v >> 16;\n\t\tv++;\n\t\treturn v;\n\t}\n\n}", "public class Parameter {\n\tprivate String name;\n\tprivate int type;\n\tprivate float min;\n\tprivate float max;\n\tprivate UGenInput input;\n\tprivate float tick = 0.1f;\n\tprivate boolean locked = false;\n\tprivate Function<Float, String> formatter;\n\n\tprivate ListenerManager<ControlListener> listenerManager = new ListenerManager<>();\n\n\t/**\n\t * Return the parameters in a list.\n\t * \n\t * @return the control parameters for the filter.\n\t */\n\tpublic List<Parameter> getParameters() {\n\t\treturn new ArrayList<Parameter>(parameters.values());\n\t}\n\n\tParameter(String name, float min, float max, float defaultValue, Function<Float, String> formatter) {\n\t\tthis.name = name;\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t\tthis.input = new UGenInput(InputType.CONTROL);\n\t\tthis.setValue(defaultValue);\n\t\tthis.formatter = formatter;\n\t}\n\n\t/**\n\t * Add the listener for callback when a control change.\n\t * \n\t * @param listener\n\t * the listener to call when a control is changed.\n\t */\n\tpublic void addListener(ControlListener listener) {\n\t\tlistenerManager.add(listener);\n\t}\n\n\tpublic void removeListener(ControlListener listener) {\n\t\tlistenerManager.remove(listener);\n\t}\n\t\t\n\tpublic float getTick() {\n\t\treturn this.tick;\n\t}\n\n\tpublic void setTick(float tick) {\n\t\tthis.tick = tick;\n\t}\n\t\t\n\tpublic void lock(boolean b) {\n\t\tthis.locked = b;\n\t}\n\t\t\n\tpublic boolean isLocked() {\n\t\treturn this.locked;\n\t}\n\n\tsynchronized boolean setValue(float v) {\n\t\tfloat val; // Needed to be final\n\t\tif(this.locked){\n\t\t\tLOG.warn(\"Parameter '{}' is currently locked.\", name);\n\t\t\treturn false;\n\t\t}\n\t\tif (v < min) {\n\t\t\tLOG.warn(\"Parameter '{}' set to minimum {} instead of {}\", name, min, v);\n\t\t\tval = min;\n\t\t} else if (v > max) {\n\t\t\tLOG.warn(\"Parameter '{}' set to maximum {} instead of {}\", name, max, v);\n\t\t\tval = max;\n\t\t} else {\n\t\t\tval = v;\n\t\t}\n\t\tif (val != this.input.getLastValue()) {\n\t\t\tLOG.debug(\"Parameter '{}' set to {}\", name, val);\n\t\t\tthis.input.setLastValue(val);\n\t\t\tlistenerManager.publish((listener) -> {\n\t\t\t\tlistener.controlChanged(AudioFilter.this, getName(), val);\n\t\t\t});\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic float getValue() {\n\t\tfloat v = this.input.getLastValue();\n\t\t// LOG.warn(\"Parameter '{}' returns {}\", name, v);\n\t\treturn v;\n\t}\n\n\tpublic String getFormattedValue() {\n\t\tfloat v = this.input.getLastValue();\n\t\treturn this.formatter.apply(v);\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic int getType() {\n\t\treturn type;\n\t}\n\n\tpublic float getMinimum() {\n\t\treturn min;\n\t}\n\n\tpublic float getMaximum() {\n\t\treturn max;\n\t}\n}", "public class ListenerManager<T> {\r\n\tprivate static Logger LOG = LogFactory.getLog(ListenerManager.class);\r\n\tprivate List<ListenerInfo<T>> listenerInfos = new ArrayList<>();\r\n\t\r\n\t/**\r\n\t * We keep information on the listener\r\n\t *\r\n\t *\r\n\t */\r\n\tprivate static class ListenerInfo<T> {\r\n\t\tAtomicInteger mutex = new AtomicInteger(0);\r\n\t\tT listener;\r\n\t\tint skipped = 0;\r\n\t\tint calls = 0;\r\n\t\t\r\n\t\tpublic ListenerInfo(T listener){\r\n\t\t\tthis.listener = listener;\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * We invoke the listener but only if a call is not already\r\n\t\t * in the queue. This avoid multiple calls. Note only the\r\n\t\t * first call is, in this case, used. The other calls are\r\n\t\t * dimissed.\r\n\t\t * \r\n\t\t * @param val the value for invocation.\r\n\t\t */\r\n\t\tpublic void invoke(Consumer<T> fnct){\r\n\t\t\tcalls++;\r\n\t\t\tif( mutex.getAndIncrement() < 1 ){\r\n\t\t\t\t// We can run the code in the SWING thread...\r\n\t\t\t\t// the value is now \"1\" (means: waiting)\r\n\t\t\t\t// we boost once \r\n\t\t\t\tmutex.incrementAndGet();\r\n\t\t\t\tSwingUtilities.invokeLater( () -> {\r\n\t\t\t\t\t// LOG.debug(\"invoked.\");\r\n\t\t\t\t\tfnct.accept(this.listener);\r\n\t\t\t\t\tmutex.decrementAndGet();\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t// for debugging purposes\r\n\t\t\t\tskipped++;\r\n\t\t\t\tif( skipped % 1000 == 0 ){\r\n\t\t\t\t\tint ratio = (int)(100.0 * (calls - skipped) / calls);\r\n\t\t\t\t\tLOG.debug(\"Listener {} called {} times ({}%).\", this.listener.getClass().getSimpleName(), (calls - skipped), ratio);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tmutex.decrementAndGet();\r\n\t\t}\r\n\t\t\r\n\t\tT getListener(){\r\n\t\t\treturn listener;\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Very basic constructor\r\n\t */\r\n\tpublic ListenerManager() {\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Notify all the listeners. We use a {@link Function}\r\n\t * to keep the code simple. Note the listener \r\n\t * \r\n\t */\r\n\tpublic void publishOnce(Consumer<T> function){\r\n\t\tfor(ListenerInfo<T> infos : this.listenerInfos){\r\n\t\t\tinfos.invoke(function);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Force to publish.\r\n\t * \r\n\t * @param function the code to call.\r\n\t */\r\n\tpublic void publish(final Consumer<T> function){\r\n\t\tfor(ListenerInfo<T> infos : this.listenerInfos){\r\n\t\t\tSwingUtilities.invokeLater( () -> {\r\n\t\t\t\tfunction.accept(infos.getListener());\r\n\t\t\t});\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Send directly on the current thread.\r\n\t * \r\n\t * @param function the code to call.\r\n\t */\r\n\tpublic void send(final Consumer<T> function){\r\n\t\tfor(ListenerInfo<T> infos : this.listenerInfos){\r\n\t\t\tfunction.accept(infos.getListener());\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add a new listener for this manager. If the listener was already there,\r\n\t * it is replaced.\r\n\t * \r\n\t * @param listener the listener to add.\r\n\t */\r\n\tpublic void add(T listener ) {\r\n\t\tsynchronized(this.listenerInfos){\r\n\t\t\tthis.listenerInfos.remove(listener); // in case already there!\r\n\t\t\tListenerInfo<T> infos = new ListenerInfo<T>(listener);\r\n\t\t\tthis.listenerInfos.add(infos);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Remove the specified listener.\r\n\t * \r\n\t * @param listener\r\n\t */\r\n\tpublic void remove(T listener ) {\r\n\t\tsynchronized(this.listenerInfos){\r\n\t\t\tthis.listenerInfos.remove(listener);\r\n\t\t}\r\n\t}\r\n\r\n}\r", "public class WaveUtils {\n\tprivate static Logger LOG = LogFactory.getLog(WaveUtils.class);\n\t\n\tpublic static Icon loadIcon(String fileName, int size){\n\t\tIcon icon = null;\n\t\ttry {\n\t\t\tString name = \"images/\" + fileName;\n\t\t\tURL url = WaveUtils.class.getClassLoader().getResource(name);\n\t\t\tBufferedImage img = ImageIO.read(url);\n\t\t\tif( size > 0 ){\n\t\t\t\t// Dimension newSize = new Dimension(size, size);\n\t\t\t\tImage resized = img.getScaledInstance( size, size, Image.SCALE_SMOOTH);\n\t\t\t\ticon = new ImageIcon(resized);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ticon = new ImageIcon(img);\n\t\t\t}\n\t\t} catch (IOException ex) {\n\t\t\tLOG.error(\"Can not load image: {}\", ex.getMessage());\n\t\t}\n\t\treturn icon;\n\t}\n}", "public class LogFactory {\r\n\tpublic static final Logger getLog(final Class<?> clazz) {\r\n\t\tLogger log = LogManager.getLogger(clazz);\r\n\t\treturn log;\r\n\t}\r\n}\r" ]
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Timer; import java.util.TimerTask; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import org.apache.logging.log4j.Logger; import com.oxande.wavecleaner.filters.AudioFilter; import com.oxande.wavecleaner.filters.AudioFilter.Parameter; import com.oxande.wavecleaner.util.ListenerManager; import com.oxande.wavecleaner.util.WaveUtils; import com.oxande.wavecleaner.util.logging.LogFactory;
package com.oxande.wavecleaner.ui; /** * A replacement for the {@link JSlider} which is not perfect for what we want. * Basically, we need a precise value using steps like a incrementing value but * it is not perfect in terms of user interface. I opted for a "-"/"+" interface. * Buttons are replaced by {@link JLabel} for a better control. The user has to use * the mouse to change the values. Using a shortcut could be possible in the future * versions. * * @author wrey75 * */ @SuppressWarnings("serial") public class JFilterMeter extends JPanel { private static Logger LOG = LogFactory.getLog(JFilterMeter.class); private AudioFilter filter;
private Parameter control;
1
in-the-keyhole/khs-sherpa
src/main/java/com/khs/sherpa/servlet/RequestMapper.java
[ "public interface ApplicationContext extends ManagedBeanFactory {\n\n\tpublic static final String CONTEXT_PATH = \"com.khs.sherpa.SHREPA.CONTEXT\";\n\tpublic static final String SHERPA_CONTEXT = \"com.khs.sherpa.SHREPA.CONTEXT\";\n\t\n\tpublic static final String SETTINGS_JSONP = \"com.khs.sherpa.SETTGINS.JSONP\";\n\tpublic static final String SETTINGS_ADMIN_USER = \"com.khs.sherpa.SETTGINS.ADMIN_USER\";\n\tpublic static final String SETTINGS_ENDPOINT_AUTH = \"com.khs.sherpa.SETTGINS.ENDPOINT_AUTH\";\n\t\n\t\n\tpublic void setAttribute(String key, Object value);\n\t\n\tpublic Object getAttribute(String key);\n\n\tpublic ManagedBeanFactory getManagedBeanFactory();\n\t\n}", "public interface ApplicationContextAware {\n\n\tpublic void setApplicationContext(ApplicationContext applicationContext);\n\t\n}", "public class SherpaRuntimeException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 3997371687805128093L;\n\n\tpublic SherpaRuntimeException() {\n\t\tsuper();\n\t}\n\n\tpublic SherpaRuntimeException(String arg0, Throwable arg1) {\n\t\tsuper(arg0, arg1);\n\t}\n\n\tpublic SherpaRuntimeException(String arg0) {\n\t\tsuper(arg0);\n\t}\n\n\tpublic SherpaRuntimeException(Throwable arg0) {\n\t\tsuper(arg0);\n\t}\n\n}", "public interface ParamParser<T> {\n\n\tpublic boolean isValid(Class<?> clazz);\n\t\n\tpublic T parse(String value, Param annotation, Class<?> clazz);\n\t\n}", "public interface RequestProcessor {\n\n\tpublic String getEndpoint(HttpServletRequest request);\n\t\n\tpublic String getAction(HttpServletRequest request);\n\t\n\tpublic String getParmeter(HttpServletRequest request, String value);\n}", "public class UrlUtil {\n\n\t// KEEP\n\tpublic static String getPath(HttpServletRequest request) {\n\t\tString url = request.getRequestURI();\n\t\t\n\t\turl = StringUtils.removeStart(url, request.getContextPath());\n\t\turl = StringUtils.removeStart(url, request.getServletPath());\n\t\t\n\t\treturn url;\n\t}\n\t\n\t// not easily tested\n\tpublic static String getRequestBody(HttpServletRequest request) {\n\t\tif(request.getMethod().equals(\"GET\") || request.getMethod().equals(\"DELETE\")) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tStringBuilder stringBuilder = new StringBuilder();\n\t\tBufferedReader bufferedReader = null;\n\t\ttry {\n\t\t\tInputStream inputStream = request.getInputStream();\n\t\t\tif (inputStream != null) {\n\t\t\t\tbufferedReader = new BufferedReader(new InputStreamReader(\n\t\t\t\t\t\tinputStream));\n\t\t\t\tchar[] charBuffer = new char[128];\n\t\t\t\tint bytesRead = -1;\n\t\t\t\twhile ((bytesRead = bufferedReader.read(charBuffer)) > 0) {\n\t\t\t\t\tstringBuilder.append(charBuffer, 0, bytesRead);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstringBuilder.append(\"\");\n\t\t\t}\n\t\t} catch (IOException ex) {\n\t\t\t// to nothing\n\t\t} finally {\n\t\t\tif (bufferedReader != null) {\n\t\t\t\ttry {\n\t\t\t\t\tbufferedReader.close();\n\t\t\t\t} catch (IOException ex) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!StringUtils.isEmpty(stringBuilder)) {\n\t\t\treturn stringBuilder.toString();\n\t\t}\n\n\t\tif (request.getParameterMap().keySet().size() > 0) {\n\t\t\treturn request.getParameterMap().keySet().toArray()[0].toString();\n\t\t}\n\n return null;\n\t}\n//\t\n//\tpublic static String getParamValue(HttpServletRequest request, String param) {\n//\t\tString value = null;\n//\t\tString currentUrl = UrlUtil.getPath(request);\n//\t\tString path = ReflectionCache.getUrl(currentUrl, request.getMethod());\n//\t\tif(StringUtils.isNotEmpty(path)) {\n//\t\t\tif(StringUtils.contains(path, \".\")) {\n//\t\t\t\tpath = StringUtils.removeStart(path, request.getMethod() + \".\");\n//\t\t\t}\n//\t\t\tvalue = UrlUtil.getRequestUrlParameter(request, path, param);\n//\t\t}\n//\t\t\n//\t\tif(value == null) {\n//\t\t\tvalue = UrlUtil.getRequestParameter(request, param);\n//\t\t}\n//\t\t\n//\t\treturn value;\n//\t\t\n//\t}\n//\t\n//\tprotected static String getCacheUrl(String url, String method) {\n//\t\tString path = ReflectionCache.getUrl(url, method);\n//\t\tif(path == null) {\n//\t\t\tpath = ReflectionCache.getUrlMethod(url, method);\n//\t\t}\n//\t\treturn path;\n//\t}\n}" ]
import com.khs.sherpa.util.UrlUtil; import java.lang.annotation.Annotation; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.khs.sherpa.annotation.Param; import com.khs.sherpa.context.ApplicationContext; import com.khs.sherpa.context.ApplicationContextAware; import com.khs.sherpa.exception.SherpaRuntimeException; import com.khs.sherpa.parser.ParamParser; import com.khs.sherpa.processor.RequestProcessor;
package com.khs.sherpa.servlet; /* * Copyright 2012 the original author or authors. * * 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 RequestMapper { private HttpServletRequest request; private HttpServletResponse response;
private RequestProcessor requestProcessor;
4
k3b/ToGoZip
libK3bZip/src/main/java/de/k3b/zip/example/HelloZip.java
[ "abstract public class CompressItem {\n protected static final String FIELD_DELIMITER = \";\";\n protected boolean processed;\n\n /** the antry may contain path within zip file */\n private String zipEntryFileName;\n\n /** if not null this will become the zip entry comment */\n private String zipEntryComment;\n\n /**\n * false means store without compression, which is faster\n */\n private boolean doCompress = true;\n\n /** stream where the source file can be read from. */\n abstract public InputStream getFileInputStream() throws IOException ;\n\n /** when source file was last modified. */\n abstract public long getLastModified();\n\n /** return true if both refer to the same entry in zip file */\n public boolean isSame(CompressItem other) {\n if (other == null) return false;\n return this.zipEntryFileName.equals(other.zipEntryFileName);\n }\n\n /** the entry may contain path within zip file */\n public String getZipEntryFileName() {\n return zipEntryFileName;\n }\n\n /** the entry may contain path within zip file */\n public CompressItem setZipEntryFileName(String zipEntryFileName) {\n this.zipEntryFileName = zipEntryFileName;\n return this;\n }\n\n /**\n * false means store without compression, which is faster\n */\n public boolean isDoCompress() {\n return doCompress;\n }\n\n public void setDoCompress(boolean doCompress) {\n this.doCompress = doCompress;\n }\n\n public boolean isProcessed() {\n return processed;\n }\n\n public void setProcessed(boolean processed) {\n this.processed = processed;\n }\n\n /** if not null this will become the zip entry comment */\n public String getZipEntryComment() {\n return zipEntryComment;\n }\n\n public void setZipEntryComment(String zipEntryComment) {\n this.zipEntryComment = zipEntryComment;\n }\n\n public StringBuilder getLogEntry(StringBuilder _result) {\n StringBuilder result = (_result == null) ? new StringBuilder() : _result;\n result.append(getZipEntryFileName());\n return result;\n }\n\n @Override\n public String toString() {\n StringBuilder result = getLogEntry(null);\n result.insert(0, FIELD_DELIMITER);\n result.insert(0,this.getClass().getSimpleName());\n result.insert(0, processed ? \"[v] \" : \"[ ] \");\n return result.toString();\n }\n}", "public class CompressJob implements ZipLog {\n public static final int RESULT_NO_CHANGES = 0;\n public static final int RESULT_ERROR_ABOART = -1;\n private static final Logger logger = LoggerFactory.getLogger(CompressJob.class);\n\n\n // global processing options\n /** set to false (in gui thread) if operation is canceled and should be rolled back */\n protected boolean continueProcessing = true;\n\n /**\n * true: remove obsolete bak file when done\n */\n private final boolean optDeleteBakFileWhenFinished = true;\n\n /**\n * true: if filename already existed in old zip rename it. Else Do not copy old\n * zipItem into new.\n */\n private final boolean optRenameExistingOldEntry = true;\n\n /**\n * logger used for compressing or null\n */\n private final ZipLog zipLog;\n\n private int itemNumber = 0;\n private int itemTotal = 0;\n /**\n * items To Be Added to be processed in the job.\n */\n private List<CompressItem> compressQue = new ArrayList<CompressItem>();\n\n /** this item from the que will receive all short texts */\n private TextCompressItem compressTextItem = null;\n\n /** this item from the que will receive all log texts */\n private TextCompressItem compressLogItem = null;\n\n private ZipStorage zipStorage;\n\n // used to copy content\n private byte[] buffer = new byte[4096];\n\n /**\n * Creates an empty job.\n *\n * @param zipLog if not null use zipLog to write logging info into while executing zipping.\n * @param fileLogInZip if not null: path inside the generated that will receive the zip-logging.\n */\n public CompressJob(ZipLog zipLog, String fileLogInZip) {\n this.zipLog = zipLog;\n if (!StringUtils.isNullOrEmpty((CharSequence) fileLogInZip)) {\n this.compressLogItem = addLog2CompressQue(fileLogInZip, null);\n\n // do not process this item in qoueOutPutLoop\n this.compressLogItem.setProcessed(true);\n }\n }\n\n /**\n * Mandatory: Define the source/target zip file used to process the zip\n */\n public CompressJob setZipStorage(ZipStorage zipStorage) {\n this.zipStorage = zipStorage;\n return this;\n }\n\n /**\n * Remember files that should be added to the zip.\n * Used in unittests.\n *\n * @param destZipPath directory within zip where the files will go to (either empty or with trailing \"/\"\n * @param srcFiles path where new-toBeZipped-compressQue come from\n */\n void addToCompressQue(String destZipPath, String... srcFiles) {\n if (srcFiles != null) {\n for (String srcFile : srcFiles) {\n addToCompressQue(destZipPath, new File(srcFile));\n }\n }\n\n }\n\n /**\n * Remember files that should be added to the zip.\n * @param destZipPath directory within zip where the files will go to (either empty or with trailing \"/\"\n */\n public CompressItem addToCompressQue(String destZipPath, File... srcFiles) {\n CompressItem item = null;\n if (srcFiles != null) {\n for (File srcFile : srcFiles) {\n if (srcFile.isDirectory()) {\n String subDir = (!StringUtils.isNullOrEmpty((CharSequence) destZipPath))\n ? destZipPath + srcFile.getName() + \"/\"\n : srcFile.getName() + \"/\";\n addToCompressQue(subDir, srcFile.listFiles());\n } else if (srcFile.isFile()) {\n item = addItemToCompressQue(destZipPath, srcFile, null);\n }\n }\n }\n return item;\n }\n\n public boolean addToCompressQueue(CompressItem item) {\n if (findInCompressQue(item) != null) {\n // already inside current collection. Do not add again\n return false;\n }\n\n compressQue.add(item);\n return true;\n }\n\n /**\n * adds one file to the CompressQue\n * @param outDirInZipForNoneRelPath directory within zip where the files will go to (either empty or with trailing \"/\"\n */\n CompressItem addItemToCompressQue(String outDirInZipForNoneRelPath, File srcFile, String zipEntryComment) {\n CompressItem item = new FileCompressItem(outDirInZipForNoneRelPath, srcFile, zipEntryComment);\n if (addToCompressQueue(item)) {\n return item;\n }\n return null;\n }\n\n public int addToCompressQueue(CompressItem[] items) {\n int addCount = 0;\n if (items != null) {\n for (CompressItem item : items) {\n if (addToCompressQueue(item)) {\n addCount++;\n }\n }\n }\n return addCount;\n }\n\n public TextCompressItem addTextToCompressQue(String zipEntryPath, String textToBeAdded) {\n this.compressTextItem = addTextToCompressQue(this.compressTextItem, zipEntryPath, textToBeAdded);\n return this.compressTextItem;\n }\n\n public TextCompressItem addLog2CompressQue(String zipEntryPath, String textToBeAdded) {\n this.compressLogItem = addTextToCompressQue(this.compressLogItem, zipEntryPath, textToBeAdded);\n return this.compressLogItem;\n }\n\n private TextCompressItem addTextToCompressQue(TextCompressItem textItem, String zipEntryPath,\n String textToBeAdded) {\n if (textItem == null) {\n\n textItem = new TextCompressItem(zipEntryPath, null);\n textItem.setLastModified(new Date().getTime());\n addToCompressQueue(textItem);\n }\n if ((textToBeAdded!=null) && (textToBeAdded.length() > 0)) {\n textItem.addText(textToBeAdded);\n }\n return textItem;\n }\n\n /**\n * return null, if file is not in the CompressQue yet.\n */\n private CompressItem findInCompressQue(CompressItem file) {\n for (CompressItem item : this.compressQue) {\n if (file.isSame(item)) return item;\n }\n return null;\n }\n\n /**\n * a unittest friendly version of handleDuplicates:<br/>\n * depending on global options: duplicate zip entries are either ignored or renamed\n *\n * @return For unittests-only: collection of items that where renamed or null if no renaming\n * took place.\n */\n List<CompressItem> handleDuplicates(Map<String, Long> existingZipEntries) {\n\n // used by unittest to find out if renaming duplicates works as expected.\n List<CompressItem> renamedItems = new ArrayList<CompressItem>();\n for (CompressItem itemToAdd : this.compressQue) {\n if (!itemToAdd.isProcessed()) {\n String addFileName = (itemToAdd != null) ? itemToAdd.getZipEntryFileName() : null;\n Long zipEntryFileLastModified = (addFileName != null) ? existingZipEntries.get(addFileName) : null;\n\n if (zipEntryFileLastModified != null) {\n // Threre is already an entry with the same name as the new item\n\n // null means means do not add this\n // else new entry gets a new name\n final String newEntryName = getRenamedZipEntryFileName(existingZipEntries, itemToAdd,\n zipEntryFileLastModified);\n\n itemToAdd.setZipEntryFileName(newEntryName);\n // itemToAdd.setZipEntryComment(createItemComment());\n renamedItems.add(itemToAdd);\n addFileName = newEntryName;\n }\n\n if (addFileName != null) {\n // add new item to existing so that a second instance with the same filename will be renamed\n existingZipEntries.put(addFileName, itemToAdd.getLastModified());\n }\n }\n }\n\n // remove the ithems that are marked with null filename\n for (int i = this.compressQue.size() - 1; i >= 0; i--) {\n if (getCompressItemAt(i).getZipEntryFileName() == null) {\n this.compressQue.remove(i);\n }\n }\n\n if (renamedItems.size() > 0) {\n return renamedItems;\n }\n return null;\n }\n\n /** scope package to allow unittests */\n CompressItem getCompressItemAt(int i) {\n return this.compressQue.get(i);\n }\n\n /**\n * package to allow unittesting: <br/>\n * gets a fixed (renamed) name for the zip entry or null if file\n * should not be added to zip.\n */\n String getRenamedZipEntryFileName(Map<String, Long> existingZipEntries, CompressItem itemToAdd,\n long zipEntryFileLastModified) {\n String zipEntryFileName = itemToAdd.getZipEntryFileName();\n\n String traceMassgeFormat = \"new {0} is already in zip: {1}\";\n if (!optRenameExistingOldEntry) {\n traceMessage(ZipJobState.RENAME_COMMENT, itemNumber, itemTotal, traceMassgeFormat,itemToAdd,\n \"do not include: optRenameExistingOldEntry disabled.\");\n return null;\n }\n\n if (sameDate(zipEntryFileName, itemToAdd.getLastModified(), zipEntryFileLastModified)) {\n traceMessage(ZipJobState.RENAME_COMMENT, itemNumber, itemTotal, traceMassgeFormat,itemToAdd,\n \"do not include: duplicate with same datetime found.\");\n return null;\n }\n\n String extension = \")\";\n int extensionPosition = zipEntryFileName.lastIndexOf(\".\");\n if (extensionPosition >= 0) {\n extension = \")\" + zipEntryFileName.substring(extensionPosition);\n zipEntryFileName = zipEntryFileName.substring(0, extensionPosition) + \"(\";\n }\n int id = 1;\n while (true) {\n String newZifFileName = zipEntryFileName + id + extension;\n Long fileLastModified = existingZipEntries.get(newZifFileName);\n if (fileLastModified == null) {\n traceMessage(ZipJobState.RENAME_COMMENT, itemNumber, itemTotal, traceMassgeFormat,\n itemToAdd,\n newZifFileName);\n return newZifFileName;\n }\n\n if (sameDate(newZifFileName, fileLastModified.longValue(), zipEntryFileLastModified)) {\n traceMessage(ZipJobState.RENAME_COMMENT, itemNumber, itemTotal,\n traceMassgeFormat,itemToAdd,\n \"do not include: duplicate with same datetime found.\");\n return null;\n }\n\n id++;\n }\n }\n\n private boolean sameDate(String zipEntryFileName, long fileLastModified, long zipLastModified) {\n long timeDiff = Math.abs(fileLastModified - zipLastModified);\n\n if (logger.isDebugEnabled()) {\n DateFormat f = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.US);\n logger.debug(\"sameDate({}): {} <=> {} : diff {} millisecs\"\n , zipEntryFileName\n , f.format(new Date(zipLastModified))\n , f.format(new Date(fileLastModified))\n , timeDiff\n );\n }\n\n return timeDiff < 10000; // are same if diff < 10 seconds\n }\n\n /**\n * Processes the compressQue: renaming duplicates and add items to zip.\n *\n * @param renameDuplicateTextFile true: add an additional renamed entry for the texts.\n * False: append to existing entry\n * @return number of modified items (compressQue and/or text appended); -1 if error/cancleded\n */\n public int compress(boolean renameDuplicateTextFile) {\n // Workflow (that makes shure that orginal is not broken if there is an error):\n // 1) addToCompressQue to somefile.tmp.zip, (a) old content from somefile.zip, (b) new content\n // 2) rename existing somefile.zip to somefile.bak.zip\n // 3) rename somefile.tmp.zip to somefile.zip\n // 4) delete existing somefile.bak.zip\n // 5) free resources\n\n boolean preventTextFromRenaming = (!renameDuplicateTextFile) && (this.compressTextItem != null) && !this.compressTextItem.isProcessed();\n\n int emptyCount = (compressLogItem != null) ? 1 : 0;\n if (compressQue.size() <= emptyCount) {\n logger.debug(\"aboard: no (more) files to addToCompressQue to zip\");\n return RESULT_NO_CHANGES;\n }\n\n itemNumber=0; itemTotal=compressQue.size();\n\n // global to allow garbage collection if there is an exception\n ZipOutputStream zipOutputStream = null;\n ZipInputStream zipInputStream = null;\n InputStream zipEntryInputStream = null;\n String context = \"\";\n int itemCount = 0;\n\n try {\n // map from path to lastModifiedDate used to find the duplicates\n Map<String, Long> existingEntries = new HashMap<>();\n\n String curZipFileName = this.zipStorage.getZipFileNameWithoutPath(ZipStorage.ZipInstance.current);\n String newZipFileName = this.zipStorage.getZipFileNameWithoutPath(ZipStorage.ZipInstance.new_);\n\n context = traceMessage(ZipJobState.CREATE_NEW_ZIP_0, itemNumber, itemTotal,\n \"(0) create new result file {0}\", newZipFileName);\n try {\n OutputStream outputStream = this.zipStorage.createOutputStream(ZipStorage.ZipInstance.new_);\n zipOutputStream = new ZipOutputStream(outputStream);\n } catch (IOException ex) {\n continueProcessing = false;\n String errorMessage = \"Cannot create '\"\n + newZipFileName\n + \"' for '\"\n + this.zipStorage.getAbsolutePath()\n + \"': \" + ex.getMessage();\n\n addError(errorMessage);\n return RESULT_ERROR_ABOART;\n }\n\n String oldZipFileName = null;\n if (this.zipStorage.exists()) {\n context = traceMessage(ZipJobState.COPY_EXISTING_ITEM_1A, itemNumber, itemTotal,\n \"(1a) copy existing compressQue from {1} to {2}\",\n \"\", curZipFileName, newZipFileName);\n zipInputStream = new ZipInputStream(this.zipStorage.createInputStream());\n\n InputStream prependInputStream = null;\n for (ZipEntry zipOldEntry = zipInputStream.getNextEntry(); zipOldEntry != null; zipOldEntry = zipInputStream\n .getNextEntry()) {\n throwIfCancleded();\n if (null != zipOldEntry) {\n if (null != (prependInputStream = this.getPrependInputStream(zipOldEntry, this.compressTextItem))) {\n itemNumber++; itemTotal++;\n itemCount++;\n context = traceMessage(\n ZipJobState.ADD_TEXT_TO_EXISTING_1A1, itemNumber, itemTotal,\n \"- (1a+) add text to existing item {0} from {1} to {2}\",\n zipOldEntry, curZipFileName, newZipFileName);\n } else if (isSameFile(this.compressLogItem, zipOldEntry)) {\n context = traceMessage(\n ZipJobState.READ_OLD_EXISTING_LOG_ITEM_1A2, itemNumber, itemTotal,\n \"- (1a+) read old log text {0} from {1} to {2}\",\n zipOldEntry, curZipFileName, newZipFileName, zipOldEntry);\n\n this.compressLogItem.addText(FileUtils.readFile(zipInputStream, this.buffer));\n this.compressLogItem.setZipEntryComment(zipOldEntry.getComment());\n\n // add latter when all log entries are written\n zipOldEntry = null;\n } else {\n itemNumber++; itemTotal++;\n context = traceMessage(\n ZipJobState.COPY_EXISTING_ITEM_1A, itemNumber, itemTotal,\n \"- (1a) copy existing item {0} from {1} to {2}\",\n zipOldEntry, curZipFileName, newZipFileName);\n }\n }\n\n if (null != zipOldEntry) {\n itemNumber++; itemTotal++;\n add(zipOutputStream, zipOldEntry, prependInputStream, zipInputStream);\n existingEntries.put(zipOldEntry.getName(), zipOldEntry.getTime());\n }\n }\n zipInputStream.close();\n zipInputStream = null;\n // i.e. /path/to/somefile.bak.zip\n oldZipFileName = this.zipStorage.getZipFileNameWithoutPath(ZipStorage.ZipInstance.old);\n }\n\n boolean oldProcessed = false;\n\t\t\tif (preventTextFromRenaming) {\n oldProcessed = this.compressTextItem.isProcessed();\n this.compressTextItem.setProcessed(true);\n }\n\n\t\t\tif (continueProcessing) handleDuplicates(existingEntries);\n\n\t\t\tif (preventTextFromRenaming) this.compressTextItem.setProcessed(oldProcessed);\n\n if ((this.compressTextItem != null) && !this.compressTextItem.isProcessed()) {\n this.compressTextItem.addText(this.getTextFooter());\n // this.compressTextItem.setProcessed(true);\n // itemCount++;\n }\n\n if (this.compressLogItem != null) {\n this.compressLogItem.addText(\";;;;;---\");\n }\n\n // (1b) copy new compressQue\n for (CompressItem item : this.compressQue) {\n throwIfCancleded();\n\n if (!item.isProcessed()) {\n String newFullDestZipItemName = item.getZipEntryFileName();\n\n itemNumber++;\n context = traceMessage(ZipJobState.COPY_NEW_ITEM_1B, itemNumber, itemTotal,\n \"(1b) copy new item {0} as {1} to {2}\",\n item, newFullDestZipItemName, newZipFileName);\n zipEntryInputStream = item.getFileInputStream();\n ZipEntry zipEntry = createZipEntry(newFullDestZipItemName,\n item.getLastModified(), item.getZipEntryComment());\n if (!item.isDoCompress()) zipEntry.setMethod(ZipEntry.STORED);\n add(zipOutputStream, zipEntry, null, zipEntryInputStream);\n zipEntryInputStream.close();\n zipEntryInputStream = null;\n itemCount++;\n item.setProcessed(true);\n\n if (this.compressLogItem != null) {\n this.compressLogItem.addText(item.getLogEntry(null).toString());\n }\n }\n }\n\n if (continueProcessing && (compressLogItem != null)) {\n CompressItem item = compressLogItem;\n String newFullDestZipItemName = item.getZipEntryFileName();\n itemNumber++;\n context = traceMessage(ZipJobState.COPY_LOG_ITEM_1C, itemNumber, itemTotal,\n \"(1c) copy log item {0} as {1} to {2}\",\n item, newFullDestZipItemName, newZipFileName);\n\n if (this.zipLog != null) {\n this.compressLogItem.addText(\"Detailed log\");\n this.compressLogItem.addText(zipLog.getLastError(true));\n }\n zipEntryInputStream = item.getFileInputStream();\n ZipEntry zipEntry = createZipEntry(newFullDestZipItemName,\n item.getLastModified(), item.getZipEntryComment());\n add(zipOutputStream, zipEntry, null, zipEntryInputStream);\n zipEntryInputStream.close();\n zipEntryInputStream = null;\n itemCount++;\n }\n\n zipOutputStream.close();\n zipOutputStream = null;\n\n throwIfCancleded();\n\n // no exception yet: Assume it is save to change the old zip\n // (2) rename existing-old somefile.zip to somefile.bak.zip\n if (oldZipFileName != null) {\n this.zipStorage.delete(ZipStorage.ZipInstance.old);\n\n context = traceMessage(\n ZipJobState.RENAME_OLD_ZIP_2, itemNumber, itemTotal,\n \"(2) rename old zip file from {1} to {0}\",\n curZipFileName, oldZipFileName);\n // i.e. /path/to/somefile.zip => /path/to/somefile.bak.zip\n\n if (!zipStorage.rename(ZipStorage.ZipInstance.current, ZipStorage.ZipInstance.old)) {\n thowrError(context);\n }\n }\n\n // 3) rename new created somefile.tmp.zip to somefile.zip\n context = traceMessage(ZipJobState.RENAME_NEW_CREATED_ZIP_3, itemNumber, itemTotal,\n \"(3) rename new created zip file {1} to {0}\",\n newZipFileName, curZipFileName);\n\n if (!zipStorage.rename(ZipStorage.ZipInstance.new_, ZipStorage.ZipInstance.current)) {\n // something went wrong. try to restore old zip\n // i.e. somefile.bak.zip => somefile.zip\n if (oldZipFileName != null) {\n zipStorage.rename(ZipStorage.ZipInstance.old, ZipStorage.ZipInstance.current);\n }\n\n thowrError(context);\n }\n\n // 4) delete existing renamed old somefile.bak.zip\n if ((optDeleteBakFileWhenFinished) && (oldZipFileName != null)) {\n context = traceMessage(\n ZipJobState.DELETE_EXISTING_RENAMED_ZIP_4, itemNumber, itemTotal,\n \"(4) delete existing renamed old zip file {0}\", oldZipFileName);\n this.zipStorage.delete(ZipStorage.ZipInstance.old);\n }\n context = traceMessage(ZipJobState.SUCCESSFULL_UPDATED_ZIP_5A, itemNumber, itemTotal,\n \"(5a) successfull updated zip file {0}\",\n curZipFileName);\n\n } catch (Exception e) {\n String errorMessage = e.getMessage();\n if (errorMessage == null) {\n errorMessage = \"\";\n }\n if (!errorMessage.contains(context)) {\n errorMessage = \"Error in \" + context + \":\" + errorMessage;\n }\n logger.error(errorMessage, e);\n addError(errorMessage);\n return RESULT_ERROR_ABOART;\n } finally {\n context = traceMessage(ZipJobState.FREE_RESOURCES_5B, itemNumber, itemTotal,\n \"(5b) free resources\", \"\");\n\n FileUtils.close(zipEntryInputStream,context + \"zipEntryInputStream\");\n FileUtils.close(zipOutputStream,context + \"zipOutputStream\");\n }\n return itemCount;\n }\n\n /** footer added to text collector. null means no text. */\n protected String getTextFooter() {\n return null;\n }\n\n /** get stream to be prepended before zip-content or null if there is nothing to prepend. */\n private static InputStream getPrependInputStream(ZipEntry zipEntry,\n TextCompressItem textItem) throws IOException {\n if ((textItem == null) ||\n (!isSameFile(textItem, zipEntry))) {\n // not matching current zip: do not prepend.\n return null;\n }\n\n long newLastModified = textItem.getLastModified();\n\n textItem.setProcessed(true); // do not add later\n zipEntry.setTime(newLastModified);\n\n // \"------ date ----\" between new content and old content\n textItem.addText(getTextDelimiter(newLastModified, zipEntry.getTime()));\n\n InputStream prependInputStream = textItem.getFileInputStream();\n\n return prependInputStream;\n }\n\n private static boolean isSameFile(CompressItem compressItem, ZipEntry zipEntry) {\n if ((compressItem == null) || (zipEntry == null)) return false;\n final String zipEntryFileName = compressItem.getZipEntryFileName();\n return isSameFile(zipEntryFileName, zipEntry);\n }\n\n protected static boolean isSameFile(String zipEntryFileName, ZipEntry zipEntry) {\n if (zipEntry == null) return false;\n return zipEntry.getName().equalsIgnoreCase(zipEntryFileName);\n }\n\n /**\n * @return append text delimiter if last text file write had different date than current. Else null.\n */\n private static String getTextDelimiter(long newLastModified, long oldLastModified) {\n DateFormat f = new SimpleDateFormat(\" -------- yyyy-MM-dd --------\", Locale.US);\n String currentDelimiter = f.format(new java.util.Date(newLastModified));\n String previousDelimiter = f.format(new java.util.Date(oldLastModified));\n if (!currentDelimiter.equalsIgnoreCase(previousDelimiter)) {\n return previousDelimiter;\n }\n\n return null;\n }\n\n /**\n * local helper to generate a ZipEntry.\n */\n private ZipEntry createZipEntry(String renamedFile, long time,\n String comment) {\n ZipEntry result = new ZipEntry(renamedFile);\n if (time != 0)\n result.setTime(time);\n if (comment != null)\n result.setComment(comment);\n\n return result;\n }\n\n private void thowrError(String message) throws IOException {\n throw new IOException(\"failed in \" + message);\n }\n\n /**\n * add one item to zip. closing outZipStream when done.\n */\n private void add(ZipOutputStream outZipStream, ZipEntry zipEntry,\n InputStream prependInputStream, InputStream inputStream) throws IOException {\n outZipStream.putNextEntry(zipEntry);\n\n if (prependInputStream != null) {\n FileUtils.copyStream(outZipStream, prependInputStream, buffer);\n prependInputStream.close();\n }\n FileUtils.copyStream(outZipStream, inputStream, buffer);\n outZipStream.closeEntry();\n }\n\n /**\n * return number of remaining itemes that should be added to zip\n */\n public int getAddCount() {\n return this.compressQue.size();\n }\n\n protected void throwIfCancleded() throws IOException {\n if (!continueProcessing) {\n thowrError(\"[canceled by user]\");\n }\n }\n\n @Override\n public String traceMessage(int zipStateID, int itemNumber, int itemTotal, String format, Object... params) {\n if (zipLog != null)\n return zipLog.traceMessage(zipStateID, itemNumber, itemTotal, format, params);\n return format;\n }\n\n @Override\n public void addError(String errorMessage) {\n if (zipLog != null) zipLog.addError(errorMessage);\n }\n\n @Override\n public String getLastError(boolean detailed) {\n if (zipLog != null) return zipLog.getLastError(detailed);\n return \"\";\n }\n\n public String getAbsolutePath() {return this.zipStorage.getAbsolutePath();}\n\n /**\n * allows async canceling of running compression job from other thread\n */\n public void cancel() {\n continueProcessing = false;\n }\n}", "public class FileCompressItem extends CompressItem {\n private static final Logger logger = LoggerFactory.getLogger(LibZipGlobal.LOG_TAG);\n private static final String DBG_CONTEXT = \"FileCompressItem:\";\n\n /** source file to be compressed */\n private File file;\n\n /** if not null file adds will be relative to this path if file is below this path */\n private static String zipRelPath = null;\n\n /**\n *\n * @param outDirInZipForNoneRelPath directory with trailing \"/\" (without filename) where\n * the entry goes to if outside FileCompressItem.zipRelPath.\n * null==root dir.\n * @param srcFile full path to source file\n * @param zipEntryComment\n */\n public FileCompressItem(String outDirInZipForNoneRelPath, File srcFile, String zipEntryComment) {\n String zipEntryName = calculateZipEntryName(outDirInZipForNoneRelPath, srcFile, FileCompressItem.zipRelPath);\n setFile(srcFile);\n setZipEntryFileName(zipEntryName);\n setZipEntryComment(zipEntryComment);\n }\n\n /**\n * Calculates the path within the zip file.\n *\n * Scope: package to allow unittesting.\n *\n * @param outDirInZipForNoneRelPath directory with trailing \"/\" (without filename) where\n * the entry goes to if outside zipRelPath.\n * null==root dir.\n * @param srcFile full path to source file\n * @param zipRelPath if not empty paths are caclulated relative to this directory.\n * Must have trailing \"/\" and be lower case.\n * @return\n */\n static String calculateZipEntryName(String outDirInZipForNoneRelPath, File srcFile, String zipRelPath) {\n String result = FileNameUtil.makePathRelative(zipRelPath, srcFile);\n\n if (result == null) {\n StringBuilder resultMessage = new StringBuilder();\n\n if (outDirInZipForNoneRelPath != null)\n resultMessage.append(outDirInZipForNoneRelPath);\n resultMessage.append(srcFile.getName());\n result = resultMessage.toString();\n }\n if (LibZipGlobal.debugEnabled) {\n logger.info(DBG_CONTEXT + \"[match={}] <== calculateZipEntryName(... , srcFile='{}' , zipRelPath='{}')\",\n result, srcFile, zipRelPath);\n }\n return result;\n }\n\n /** if not null enables zipRelPath mode. \"add\"-s will be relative to this path if file is below this path */\n public static void setZipRelPath(File zipRelPath) {\n if (zipRelPath != null) {\n FileCompressItem.zipRelPath = FileNameUtil.getCanonicalPath(zipRelPath).toLowerCase();\n } else {\n FileCompressItem.zipRelPath = null;\n }\n if (LibZipGlobal.debugEnabled) {\n logger.info(DBG_CONTEXT + \"setZipRelPath('{}') from '{}'\",FileCompressItem.zipRelPath, zipRelPath );\n }\n }\n\n\n /** source file to be compressed */\n public FileCompressItem setFile(File file) {\n this.file = file;\n this.processed = false;\n return this;\n }\n\n /** source file to be compressed */\n public File getFile() {\n return file;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public InputStream getFileInputStream() throws IOException {\n return new FileInputStream(file);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public long getLastModified() {\n return this.getFile().lastModified();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isSame(CompressItem other) {\n return super.isSame(other) && (this.file.equals(((FileCompressItem) other).file));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public StringBuilder getLogEntry(StringBuilder _result) {\n StringBuilder result = super.getLogEntry(_result);\n result.append(FIELD_DELIMITER);\n if (getFile() != null) result.append(getFile());\n return result;\n }\n\n}", "public interface ZipStorage {\n /** return true if ZipInstance.current exists */\n boolean exists();\n\n /**\n * return true if zip file directory exists and is writable\n */\n boolean writableZipFileParentDirectoryExists();\n\n /**\n * deletes the zip file.\n * i.e. new ZipStorage(\"/path/to/file.zip\").delete(ZipStorage.ZipInstance.new_) will\n * delete \"/path/to/file.tmp.zip\"\n */\n boolean delete(ZipInstance zipInstance);\n\n /**\n * Creates an output stream that reperesents an empty zip file where files can be added to.\n * i.e. new ZipStorage(\"/path/to/file.zip\").createOutputStream(ZipStorage.ZipInstance.new_) will\n * delete exisit \"/path/to/file.tmp.zip\", create dirs \"/path/to\" and\n * create outputstream for \"/path/to/file.tmp.zip\"\n */\n OutputStream createOutputStream(ZipInstance zipInstance) throws FileNotFoundException;\n\n /**\n * Creates an input stream that reperesents a zip file where files can be extracted from.\n * i.e. new ZipStorage(\"/path/to/file.zip\").createInputStream() will\n * create intputstream for \"/path/to/file.zip\"\n */\n InputStream createInputStream() throws FileNotFoundException;\n\n /**\n * get zip filename for zipInstance\n * i.e. new ZipStorage(\"/path/to/file.zip\").getName(ZipStorage.ZipInstance.current) will\n * return \"file.zip\"\n * @param zipInstance\n */\n String getZipFileNameWithoutPath(ZipInstance zipInstance);\n\n /**\n * get absolute path of zipFile that is compatible with File.\n * i.e. new ZipStorage(\"/path/to/file.zip\").getAbsolutePath() will\n * return \"/path/to/file.zip\"\n */\n String getAbsolutePath();\n\n /**\n * get absolute path zipFile as Uri-string or null if zip does not exist\n */\n String getFullZipUriOrNull();\n\n /**\n * rename zipfile.\n * i.e. new ZipStorage(\"/path/to/file.zip\").rename(ZipStorage.ZipInstance.new_,ZipStorage.ZipInstance.current) will\n * rename from \"/path/to/file.tmp.zip\" to from \"/path/to/file.zip\"\n */\n boolean rename(ZipInstance zipInstanceFrom, ZipInstance zipInstanceTo);\n\n /** While processing a zip-file there can be 3 different instances of the zip:\n * current, old, new */\n public enum ZipInstance {\n /** path of the zip when CompressJob has finished i.e. /path/to/file.zip */\n current(SUFFIX_CURRENT_ZIP),\n\n /** path of the original unmodified zip while CompressJob is active /path/to/file.bak.zip */\n old(SUFFIX_OLD_ZIP),\n /** path of the new updated zip while CompressJob is active /path/to/file.tmp.zip */\n new_(SUFFIX_NEW_ZIP),\n\n /** path of the crash log file if something goes wrong (or save logcat in settings is pressed) /path/to/file.crash.log */\n logfile(SUFFIX_CRASH_LOG);\n\n private final String zipFileSuffix;\n\n private ZipInstance(String zipFileSuffix) {\n this.zipFileSuffix = zipFileSuffix;\n }\n\n public String getZipFileSuffix() {\n return zipFileSuffix;\n }\n }\n\n static final String SUFFIX_NEW_ZIP = \".tmp.zip\";\n static final String SUFFIX_OLD_ZIP = \".bak.zip\";\n static final String SUFFIX_CURRENT_ZIP = \"\";\n static final String SUFFIX_CRASH_LOG = \".crash.log\";\n}", "public class ZipStorageFile implements de.k3b.zip.ZipStorage {\n private final File fileCur;\n private final File fileNew;\n private final File fileOld;\n\n /**\n * Constructs a new zip-file-storage using the specified path.\n *\n * @param path the path to be used for the zip-file.\n * @throws NullPointerException if {@code path} is {@code null}.\n */\n public ZipStorageFile(String path) {\n this.fileCur = new File(path + SUFFIX_CURRENT_ZIP);\n this.fileNew = new File(path + SUFFIX_NEW_ZIP);\n this.fileOld = new File(path + SUFFIX_OLD_ZIP);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean exists() {\n return fileCur.exists();\n }\n\n /**\n * return true if zip file directory exists\n */\n @Override\n public boolean writableZipFileParentDirectoryExists() {\n File directory = (fileCur != null) ? fileCur.getParentFile() : null;\n return (directory != null) && (directory.exists()) && (directory.isDirectory()) && (directory.canWrite());\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean delete(ZipInstance zipInstance) {\n return file(zipInstance).delete();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public OutputStream createOutputStream(ZipInstance zipInstance) throws FileNotFoundException {\n // create parent dirs if not exist\n fileCur.getParentFile().mkdirs();\n\n // i.e. /path/to/somefile.tmp.zip\n File newZip = file(zipInstance);\n\n // replace existing\n newZip.delete();\n return new FileOutputStream(newZip);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public InputStream createInputStream() throws FileNotFoundException {\n // return this;\n return new FileInputStream(fileCur);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getZipFileNameWithoutPath(ZipInstance zipInstance) {\n return file(zipInstance).getName();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getAbsolutePath() {\n return fileCur.getAbsolutePath();\n }\n\n /**\n * get absolute path zipFile as Uri-string or null if zip does not exist\n */\n @Override\n public String getFullZipUriOrNull() {\n return \"file://\" + getAbsolutePath();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean rename(ZipInstance zipInstanceFrom, ZipInstance zipInstanceTo) {\n return file(zipInstanceFrom).renameTo(file(zipInstanceTo));\n }\n\n\n private File file(ZipInstance zipInstance) {\n switch (zipInstance) {\n case new_: return fileNew;\n case old: return fileOld;\n default: return fileCur;\n }\n }\n}" ]
import java.io.File; import de.k3b.zip.CompressItem; import de.k3b.zip.CompressJob; import de.k3b.zip.FileCompressItem; import de.k3b.zip.ZipStorage; import de.k3b.zip.ZipStorageFile;
/* * Copyright (C) 2014-2019 k3b * * This file is part of de.k3b.android.toGoZip (https://github.com/k3b/ToGoZip/) . * * 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 de.k3b.zip.example; /** * A Minimal program to demonstrate how to add files to an existing zip file. */ public class HelloZip { void addSomeItemsToExistingZip() { ZipStorage testZip = new ZipStorageFile("/tmp/hello.zip"); /** // under android with SAF use ZipStorageDocumentFile instead of ZipStorageFile. i.e. DocumentFile docDir = android.support.v4.provider.DocumentFile.fromTreeUri(getActivity(), uriToAndroidDirectory) ZipStorage testZip = new de.k3b.android.zip.ZipStorageDocumentFile(getActivity(), docDir, "hello.zip"); */ /** // This code adds files to existing zip. // to replace existing old zip delete it before. i.e. testZip.delete(ZipStorage.ZipInstance.current); */
CompressJob job = new CompressJob(null, null).setZipStorage(testZip);
1
Beloumi/PeaFactory
src/peafactory/peas/editor_pea/LockFrameEditor.java
[ "public class CipherStuff {\n\t\n\tprivate static CipherStuff cipherStuff = new CipherStuff();\n\t\n\tprivate static BlockCipher cipherAlgo;\n\t\n\tprivate static AuthenticatedEncryption authenticatedEncryption = new EAXMode();\n\t\n\tprivate static String errorMessage = null;\n\t\n\tprivate static SessionKeyCrypt skc = null;\n\t\n\tprivate static boolean bound = true;\n\t\n\t// returns required length of key in bytes\n\tpublic final static int getKeySize() {\n\t\t\n\t\tint keySize = 0;\n\t\t\n\t\tif (cipherAlgo == null) {\n\t\t\tSystem.err.println(\"CipherStuff getKeySize: cipherAlgo null\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\t\n\t\tif (cipherAlgo.getAlgorithmName().startsWith(\"Threefish\") ) {\n\t\t\t// key size = block size for Threefish 256/512/1024\n\t\t\tkeySize = cipherAlgo.getBlockSize();\n\t\t} else if ( cipherAlgo.getAlgorithmName().equals(\"Twofish\" )) {\n\t\t\tkeySize = 32; // Bytes\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"Serpent\") ) {\n\t\t\t//System.out.println(\"SerpentEngine\");\n\t\t\tkeySize = 32; // Bytes\t\t\t\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"AES\") ) {\n\t\t\tkeySize = 32; // Bytes\t\t\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"AESFast\") ) {\n\t\t\tkeySize = 32; // Bytes\t\n\t\t} else if (cipherAlgo.getAlgorithmName().equals(\"Shacal2\") ) {\n\t\t\tkeySize = 64; // Bytes\n\t\t} else {\n\t\t\tSystem.err.println(\"CipherStuff getKeySize: invalid Algorithm\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\treturn keySize;\n\t}\n\t\n\t/**\n\t * Encrypt/decrypt an array of bytes. This function is only used to \n\t * encrypt the session key\n\t * \n\t * @param forEncryption - true for encryption, false for decryption\n\t * @param input\t\t\t- plain text or cipher text\n\t * @param key\t\t\t- the cryptographic key for the cipher\n\t * @param zeroize\t\t- fills the key with 0 for true (when the key is no longer used)\n\t * @return\t\t\t\t- plain text or cipher text\n\t */\n\tpublic final static byte[] processCTR(boolean forEncryption, byte[] input, byte[] key,\n\t\t\tboolean zeroize) {\n\t\t//Help.printBytes(\"key\", input);\n\t\tKeyParameter kp = new KeyParameter(key);\n\t\tif (zeroize == true) {\n\t\t\tZeroizer.zero(key);\n\t\t}\n\t\t\n\t\tbyte[] iv = null;\n\t\t\n\t\tif (forEncryption == false) {\n\t\t\t// input is ciphertext, IV is stored on top of ciphertext\n\t\t\t// get IV:\n\t\t\tiv = new byte[CipherStuff.getCipherAlgo().getBlockSize()];\n\t\t\tSystem.arraycopy(input, 0, iv, 0, iv.length);\n\t\t\t// truncate ciphertext:\n\t\t\tbyte[] tmp = new byte[input.length - iv.length];\n\t\t\tSystem.arraycopy(input, iv.length, tmp, 0, tmp.length);\n\t\t\tinput = tmp;\n\t\t} else {\n\t\t\t// input is plaintext\n\t\t\tiv = new RandomStuff().createRandomBytes(CipherStuff.getCipherAlgo().getBlockSize());\n\t\t}\n\t\tParametersWithIV ivp = new ParametersWithIV(kp, iv);\n\n\t\tBufferedBlockCipher b = new BufferedBlockCipher(new SICBlockCipher(cipherAlgo));\n\n b.init(true, ivp);\n byte[] out = new byte[input.length];\n\n int len = b.processBytes(input, 0, input.length, out, 0);\n\n try {\n\t\t\tlen += b.doFinal(out, len);\n\t\t} catch (DataLengthException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IllegalStateException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidCipherTextException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n Zeroizer.zero(kp.getKey());\n\n\t\tif (forEncryption == false) {// decryption: output plaintext\n\t\t\treturn out;\n\t\t} else { // encryption: output (IV || ciphertext)\n\t\t\tZeroizer.zero(input);\n\t\t\t// store IV on top of ciphertext\n\t\t\tbyte[] tmp = new byte[out.length + iv.length];\n\t\t\tSystem.arraycopy(iv, 0, tmp, 0, iv.length);\n\t\t\tSystem.arraycopy(out, 0, tmp, iv.length, out.length);\n\t\t\treturn tmp;\n\t\t}\t\t\n\t}\n\n\t\n\t/*\n\t * Encryption if plainBytes can be loaded in memory in one block\n\t */\n\t/**\n\t * Encrypt an array of bytes. \n\t * \n\t * @param plainBytes\t\t\tthe plain text to encrypt\n\t * @param keyMaterial\t\t\tthe derived key or null (there\n\t * \t\t\t\t\t\t\t\tis a session key available)\n\t * @param encryptBySessionKey\tif true, the derived key is encrypted, \n\t * \t\t\t\t\t\t\t\totherwise the key is cleared\n\t * @return\t\t\t\t\t\tthe cipher text\n\t */\n\tpublic final byte[] encrypt(byte[] plainBytes, byte[] keyMaterial, \n\t\t\tboolean encryptBySessionKey){\n\t\t\n\t\tcheckSessionKeyCrypt();\n\t\t\n\t\t// Check if plainBytes is too long to be loaded in memory:\n\t\tif (plainBytes.length > 8192 * 64 * 16) { // fileBlockSize = 8192 * 64 * 16\n\t\t\t\n\t\t\t// check free memory to avoid swapping:\n\t\t\tSystem.gc(); // this might not work...\n\t\t\tlong freeMemory = Runtime.getRuntime().maxMemory() \n\t\t\t\t\t- (Runtime.getRuntime().totalMemory()\n\t\t\t\t\t\t\t- Runtime.getRuntime().freeMemory());\n\t\t\t//System.out.println(\"Free memory: \" + freeMemory);\n\t\t\tif (plainBytes.length <= freeMemory) {\t\t\t\n\t\t\t\tSystem.out.println(\"Warning: long plain text\");\n\t\t\t} else {\n\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t \"The content you want to encrypt is too large \\n\"\n\t\t\t\t\t + \"to encrypt in one block on your system: \\n\"\n\t\t\t\t\t + plainBytes.length + \"\\n\\n\"\n\t\t\t\t\t + \"Use the file encrytion pea instead. \\n\"\n\t\t\t\t\t + \"(If you blew up an existing text based pea, \\n\"\n\t\t\t\t\t + \"you have to save the content by copy-and-paste).\",\n\t\t\t\t\t \"Memory error\",\n\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\tSystem.exit(1);\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\t// unique for each encryption\n\t\tbyte[] iv = Attachments.getNonce();\n\t\tif (iv == null) {\n\t\t\t// for every file: new unique and random IV\n\t\t\tiv = Attachments.generateNonce( );\n\t\t\tAttachments.setNonce(iv);\n\t\t}\n\t\tbyte[] key = detectKey(keyMaterial);\n\t\t//\n\t\t//------ENCRYPTION: \n\t\t//\t\t\t\t\n\t\t// add pswIdentifier to check password in decryption after check of Mac\n\t\tplainBytes = Attachments.addPswIdentifier(plainBytes);\n\n\t\tbyte[] cipherBytes = authenticatedEncryption.processBytes(true, plainBytes, key, iv);\t\n\t\tZeroizer.zero(plainBytes);\t\t\t\t\n\t\t// prepare to save:\n\t\tcipherBytes = Attachments.addNonce(cipherBytes, iv);\t\n\t\tif (CipherStuff.isBound() == false) {\n\t\t\tcipherBytes = Attachments.attachBytes(cipherBytes, KeyDerivation.getAttachedSalt());\n\t\t}\n\t\tcipherBytes = Attachments.addFileIdentifier(cipherBytes);\t\n\t\t//\n\t\t// handle the keys\n\t\t//\n\t\thandleKey(key, encryptBySessionKey);\n\n//\tHelp.printBytes(\"cipherBytes\", cipherBytes);\n\t\treturn cipherBytes;\n\t}\n\t\n\n\t\n\t// changes the encryptedKey for new keyMaterial\n\t// used by changing password\n\t/**\n\t * Encrypt the derived key and use as session key\n\t * \n\t * @param keyMaterial\tthe derived key\n\t */\n\tpublic final void encryptKeyFromKeyMaterial(byte[] keyMaterial) {\n\t\t\n\t\tcheckSessionKeyCrypt();\n\t\t\n\t\tif (keyMaterial == null) {\n\t\t\tSystem.err.println(\"Error: new keyMaterial null (CryptStuff.encryptKeyFromKeyMaterial\");\n\t\t\tSystem.exit(1);\n\t\t}\t\t\n\t\tbyte[] key = detectKey(keyMaterial);\n\t\thandleKey(key, true);\n\t}\n\n\t\n\t\n\t//\n\t// returns null for incorrect password or input\n\t//\n\t/**\n\t * Decrypt an array of bytes. \n\t * \n\t * @param cipherText\t\t\tthe cipher text to decrypt\n\t * @param keyMaterial\t\t\tthe derived key or null if \n\t * \t\t\t\t\t\t\t\tthere is a session key\n\t * @param encryptBySessionKey\tencrypt the key or clear it\n\t * @return\t\t\t\t\t\tthe plain text or null if the\n\t * \t\t\t\t\t\t\t\tdecryption failed\n\t */\n\tpublic final byte[] decrypt(byte[] cipherText, byte[] keyMaterial, \t\t\n\t\t\tboolean encryptBySessionKey) {\n\t\t\n\t\tcheckSessionKeyCrypt();\n\t\t//Help.printBytes(\"ciphertext + Nonce + fileId\", cipherText);\n\t\t// check\n\t\tif (cipherText == null) {\n\t\t\terrorMessage = \"no cipher text\";\n\t\t\treturn null;\n\t\t}\n\t\tcipherText = Attachments.checkFileIdentifier(cipherText, true);\n\t\tif (cipherText == null) { // check returns null if failed\n\t\t\terrorMessage = \"unsuitable cipher text (identifier)\";\n\t\t\treturn null;\n\t\t}\n\t\tif (CipherStuff.isBound() == false){ // cut salt\n\t\t\tcipherText = Attachments.cutSalt(cipherText);\n\t\t}\n\n\t\tbyte[] iv = Attachments.calculateNonce(cipherText);\n\t\tif (iv == null) {\n\t\t\terrorMessage = \"unsuitable cipher text (length)\";\n\t\t\treturn null;\n\t\t} else {\n\t\t\tcipherText = Attachments.cutNonce(cipherText);\n\t\t}\t\t\n\n\t\t// Check if plainBytes is too long to be loaded in memory:\n\t\tif (cipherText.length > 8192 * 64 * 16) { // fileBlockSize = 8192 * 64 * 16\n\t\t\t\n\t\t\t// get free memory to avoid swapping:\n\t\t\tSystem.gc(); // this might not work...\n\t\t\tlong freeMemory = Runtime.getRuntime().maxMemory() \n\t\t\t\t\t- (Runtime.getRuntime().totalMemory()\n\t\t\t\t\t\t\t- Runtime.getRuntime().freeMemory());\n\t\t\t//System.out.println(\"Free memory: \" + freeMemory);\n\t\t\tif (cipherText.length <= freeMemory) {\t\t\t\n\t\t\t\tSystem.out.println(\"Warning: long plain text\");\n\t\t\t\t\n\t\t\t\tif (cipherText.length > (freeMemory - 8192 * 64)){\n\t\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t\t \"The content you want to decrypt is already large: \\n\"\n\t\t\t\t\t\t + cipherText.length + \"\\n\\n\"\n\t\t\t\t\t\t + \"Adding more content may cause a memory error. \\n\",\n\t\t\t\t\t\t \"Memory warning\",\n\t\t\t\t\t\t JOptionPane.WARNING_MESSAGE);\t\t\t\t\t\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tJOptionPane.showMessageDialog(null,\n\t\t\t\t\t \"The content you want to decrypt is too large \\n\"\n\t\t\t\t\t + \"to decrypt in one block on your system: \\n\"\n\t\t\t\t\t + cipherText.length + \"\\n\\n\"\n\t\t\t\t\t + \"It was probably encrypted on a system with more memory. \\n\"\n\t\t\t\t\t + \"You have to decrypt it on another system... \\n\",\n\t\t\t\t\t \"Memory error\",\n\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\tSystem.exit(1);\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\tbyte[] key = detectKey(keyMaterial);\n\n\t\tint macLength = CipherStuff.getCipherAlgo().getBlockSize();\t\t\n\t\t// check mac length:\n\t\tif (cipherText.length < macLength) {\n\t\t\terrorMessage = \"unsuitable cipher text (Mac length)\";\n\t\t\treturn null;\t\t\t\n\t\t}\n\n\t\tbyte[] plainText = authenticatedEncryption.processBytes(false, cipherText, key, iv);\n\t\tif (plainText == null) { // wrong password\n\t\t\terrorMessage = \"authentication failed for password\";\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] rescueText = null;\n\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode: make copy of plainText\n\t\t\trescueText = new byte[plainText.length];\n\t\t\tSystem.arraycopy(plainText, 0, rescueText, 0, plainText.length);\n\t\t}\n\t\tplainText = Attachments.checkAndCutPswIdentifier(plainText); // truncates pswIdentifier\n\n\t\tif (plainText == null) {\n\t\t\t\n\t\t\tSystem.out.println(\"Password identifier failed.\");\n\t\t\t\n\t\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode\n\t\t\t\t \n\t\t\t\t Object[] options = {\"Continue\",\n\t \"Break\"};\n\t\t\t\t int n = JOptionPane.showOptionDialog(null,\n\t\t\t\t\t\t \"Password identifier failed: \\n\"\n\t\t\t\t\t\t\t\t + \"The password identifier checks if the beginning and the end \\n\"\n\t\t\t\t\t\t\t\t + \"of the content.\\n \"\n\t\t\t\t\t\t\t\t + \"An error means that wether the beginning or the end is not correct.\\n\"\n\t\t\t\t\t\t\t\t + \"Normally that means, that the password is wrong, \\n\"\n\t\t\t\t\t\t\t\t + \"but there is the possibility that a file is damaged. \\n\"\n\t\t\t\t\t\t\t\t + \"In this case, some parts of the file might be restored \\n\"\n\t\t\t\t\t\t\t\t + \"by the decryption. \\n\"\n\t\t\t\t\t\t\t\t + \"If you are sure, the password is correct, continue.\\n\"\n\t\t\t\t\t\t\t\t + \"Warning: For incorrect password files may be irretrievably lost. \",\n\t\t\t\t\t\t\"Password Identification Error\",\n\t\t\t\t\t\tJOptionPane.YES_NO_OPTION,\n\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\toptions[1]);\n\t\t\t \n\t\t\t\t if (n == JOptionPane.YES_OPTION) {\n\t\t\t\t\t// do nothing\n\t\t\t\t\t System.out.println(\"continue\");\n\t\t\t\t\t plainText = rescueText;\n\t\t\t\t } else {\n\t\t\t\t\t System.out.println(\"break\");\n\t\t\t\t\treturn null;\n\t\t\t\t }\t\t \n\t\t\t } else {// not recue mode\n\t\t\t\t\terrorMessage = \"password failed (identifier)\";\n\t\t\t\t\treturn null;\n\t\t\t }\t\t\t\t\n\t\t} \n\n\t\t//\n\t\t// handle the keys\n\t\t//\t\t\n\t\thandleKey(key, encryptBySessionKey);\n\t\treturn plainText;\n\t}\n\n\t/**\n\t * Get the key from keyMaterial or the session key\n\t * \n\t * @param keyMaterial\tthe derived key or null\n\t * @return\t\t\t\tthe key\n\t */\n\tprotected final byte[] detectKey(byte[] keyMaterial) {\n\t\t\n\t\tbyte[] key = null;\n\t\tif (keyMaterial != null) { // use as key \n\t\t\t\n\t\t\t// check size:\n\t\t\tint keySize = CipherStuff.getKeySize();\n\t\t\tif (keyMaterial.length != keySize) {\n\t\t\t\tSystem.err.println(\"CryptStuff detectKey: invalid size of keyMaterial\");\n\t\t\t\tSystem.exit(1);\n\t\t\t} else {\n\t\t\t\tkey = keyMaterial;\n\t\t\t}\n\t\t\t\n\t\t} else { // keyMaterial == null: decrypt encryptedKey to get key\n\t\t\tif (skc == null) {\n\t\t\t\tskc = new SessionKeyCrypt();\n\t\t\t}\n\t\t\tkey = skc.getKey();\n\t\t}\n\t\treturn key;\n\t}\n\t/**\n\t * Encrypt or clear the key\n\t * \n\t * @param key\t\t\t\tthe key\n\t * @param encryptSessionKey\tif true, encrypt the key, if\n\t * \t\t\t\t\t\t\tfalse clear it\n\t */\n\tprotected final void handleKey(byte[] key, boolean encryptSessionKey) {\t\t\n\n\t\tif (encryptSessionKey == false) {\n\t\t\tZeroizer.zero(key);\n\t\t\t\n\t\t} else {\t\t\n\t\t\tif (skc == null) {\n\t\t\t\tskc = new SessionKeyCrypt();\n\t\t\t}\n\t\t\tskc.storeKey(key);\n\t\t}\n\t}\n\tprivate final void checkSessionKeyCrypt(){\n\t\tif (skc == null) {\n\t\t\tskc = new SessionKeyCrypt();\n\t\t}\n\t}\n\n\t\n\t//=========================\n\t// Getter & Setter:\n\tpublic final static void setCipherAlgo (BlockCipher _cipherAlgo) {\n\t\tcipherAlgo = _cipherAlgo;\n\t}\n\tpublic final static BlockCipher getCipherAlgo () {\n\t\treturn cipherAlgo;\n\t}\t\n\t\n\tpublic final static void setCipherMode (AuthenticatedEncryption _cipherMode) {\n\t\tauthenticatedEncryption = _cipherMode;\n\t}\n\tpublic final static AuthenticatedEncryption getCipherMode(){\n\t\treturn authenticatedEncryption;\n\t}\n\t\n\tpublic final SessionKeyCrypt getSessionKeyCrypt(){\n\t\treturn skc;\n\t}\n\t// used in PswDialogFile for initialization\n\tpublic final static void setSessionKeyCrypt(SessionKeyCrypt _skc){ \n\t\tskc = _skc;\n\t}\n\tpublic final static String getErrorMessage() {\n\t\treturn errorMessage;\n\t}\n\tpublic final static void setErrorMessage(String _errorMessage) {\n\t\terrorMessage = _errorMessage;\n\t}\n\n\t/**\n\t * @return the cipherStuff\n\t */\n\tpublic final static CipherStuff getInstance() {\n\t\tif(cipherStuff == null){\n\t\t\tcipherStuff = new CipherStuff();\n\t\t}\n\t\treturn cipherStuff;\n\t}\n\n\t/**\n\t * @return the bound\n\t */\n\tpublic static boolean isBound() {\n\t\treturn bound;\n\t}\n\n\t/**\n\t * @param bound the bound to set\n\t */\n\tpublic static void setBound(boolean bound) {\n\t\tCipherStuff.bound = bound;\n\t}\n}", "public abstract class PswDialogBase { \n\n\t// special panel for PswDialogView, currently only used in fileType:\n\tprivate static JPanel typePanel;\n\t\n\tprivate static String encryptedFileName;\t\n\t\n\tprivate static String fileType; // set in daughter class\n\t\n\tprivate final static String PATH_FILE_NAME = PeaSettings.getJarFileName() + \".path\";\n\t\n\tprivate static PswDialogBase dialog;\n\t\n\tprivate char[] initializedPassword = null;\n\t\n\tprivate static String errorMessage = null;\n\t\n\t// i18n: \t\n\tprivate static String language; \n\tprivate static Locale currentLocale;\n\tprivate static Locale defaultLocale = Locale.getDefault();\n\tprivate static ResourceBundle languagesBundle;\n\t\n\tpublic static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\t\n\t\n\tprivate static String workingMode = \"\"; // rescue mode or test mode\n\t\n\t//============================================================\n\t// --- abstract Methods:\n\t//\n\n\t// pre computation with windowOpening\n\t// this is nowhere used yet, but maybe used later \n\t// for example ROM-hard KDF schemes \n\tpublic abstract void preComputeInThread();\n\t//\n\t// before exit: clear secret values\n\tpublic abstract void clearSecretValues();\n\t//\n\tpublic abstract void startDecryption();\n\n\t\n\t// currently only used in fileType:\n\tpublic abstract String[] getSelectedFileNames();\n\n\t//============================================================\n\t\n\tpublic final static void setLanguagesBundle(String _language) throws MalformedURLException {\n\t\t\n\t\t\n/*\t\tif(languagesBundle == null){\n\t\t\ttry {\n\t\t\t\t//System.out.println(\"language: \" + Locale.getDefault().getLanguage());\n\t\t\t\tif (Locale.getDefault().getLanguage().contains(\"de\")) {\n\t\t\t\t\tsetLanguagesBundle(Locale.getDefault().getLanguage());\n\t\t\t\t} else {\n\t\t\t\t\tsetLanguagesBundle(null);\n\t\t\t\t}\n\t\t\t} catch (MalformedURLException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}*/\n\t\t\n\t\t// i18n: \n\t\tif (_language == null) {\n\t\t\tif (defaultLocale == null) { // openSuse\n\t\t\t\tdefaultLocale = new Locale( System.getProperty(\"user.language\") );\n\t\t\t}\t\t\n\t\t\tlanguage = defaultLocale.getLanguage(); // get default language\n\t\t} else {\n\t\t\tlanguage = _language;\n\t\t}\n\t currentLocale = new Locale(language); // set default language as language\n\t \n\t // First try to open Peafactory i18n, if PswDialogBase is not used inside of a pea \n\t // FilePanel uses this bundle\n\t try {\n\t \tlanguagesBundle = ResourceBundle.getBundle(\"config.i18n.LanguagesBundle\", currentLocale);\n\t } catch (MissingResourceException mre) {// used inside of pea\n\n\t \ttry {\t \n\t \t /* File file = new File(\"resources\"); \n\t \t URL[] urls = {file.toURI().toURL()}; \n\t \t ClassLoader loader = new URLClassLoader(urls); \n\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); */ \n\t \t\tlanguagesBundle = ResourceBundle.getBundle(\"resources.PeaLanguagesBundle\", currentLocale);\n\t \t} catch (MissingResourceException mre1) {\n\t \t\t\n\t \t\ttry{\n\t \t\t\tFile file = new File(\"resources\"); \n\t\t \t URL[] urls = {file.toURI().toURL()}; \n\t\t \t ClassLoader loader = new URLClassLoader(urls); \n\t\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); \n\n\t \t\t} catch (MissingResourceException mre2) {\n\t \t\t\n\t\t \t\tcurrentLocale = new Locale(\"en\"); // set default language as language\n\t\t \t\tlanguage = \"en\";\n\n\t\t \t //File file = new File(\"src\" + File.separator + \"config\" + File.separator + \"i18n\");\n\t\t \t File file = new File(\"resources\"); \n\n\t\t \t URL[] urls = {file.toURI().toURL()}; \n\t\t \t ClassLoader loader = new URLClassLoader(urls); \n\t\t \t languagesBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader);\n\t \t\t}\n\t \t}\n\t }\n\t}\n\t\n\n\t@SuppressWarnings(\"all\")\n\tpublic final static void printInformations() {\n\t\tSystem.out.println(\"Cipher: \" + PeaSettings.getCipherAlgo().getAlgorithmName() );\n\t\tSystem.out.println(\"Hash: \" + PeaSettings.getHashAlgo().getAlgorithmName() );\n\t}\n\t\n\tpublic final static byte[] deriveKeyFromPsw(char[] pswInputChars) { \n\n\t\tif (pswInputChars == null) {\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\t\t} else if (pswInputChars.length == 0) {\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\t\t}\n\t\tbyte[] pswInputBytes = Converter.chars2bytes(pswInputChars); \n\t\tif (pswInputBytes.length > 0) {\n\t\t\tZeroizer.zero(pswInputChars);\n\t\t}\n\t\t// prevent using a zero password:\n\t\tpswInputChars = null;\n\n\t\t//=============\n\t\t// derive key: \n\t\t//\t\n\t\t// 1. initial hash: Bcrypt limited password length, password remains n RAM in Bcrypt and Scrypt\n\t\tbyte[] pswHash = HashStuff.hashAndOverwrite(pswInputBytes);\n\t\tZeroizer.zero(pswInputBytes);\n\n\t\t// 2. derive key from selected KDF: \n\t\tbyte[] keyMaterial = KeyDerivation.getKdf().deriveKey(pswHash);\n\n\t\tZeroizer.zero(pswHash);\t\t\n\t\n\t\treturn keyMaterial;\n\t}\n\n\n\tprotected final byte[] getKeyMaterial() {\n\n\t\t//-------------------------------------------------------------------------------\n\t\t// Check if t is alive, if so: wait...\n\t\tif (PswDialogView.getThread().isAlive()) { // this should never happen... \n\t\t\tSystem.err.println(\"PswDialogBase: WhileTypingThread still alive!\");\n\t\t\ttry {\n\t\t\t\tPswDialogView.getThread().join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tSystem.err.println(\"PswDialogBase: Joining thread interrupted\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\t\t\t\t\t\t\t\t\n\t\t\n\t\t//---------------------------------------------------------------------\n\t\t// get password \n\t\tchar[] pswInputChars = null;\n\t\tif (PswDialogView.isInitializing() == false){\n\t\t\tpswInputChars = PswDialogView.getPassword();\t\n\t\t} else {\n\t\t\tpswInputChars = initializedPassword;\n\t\t}\n\n\t\tbyte[] keyMaterial = deriveKeyFromPsw(pswInputChars);\t\n\t\t\n\t\tZeroizer.zero(initializedPassword);\n\t\tinitializedPassword = null;\n\n\t\tprintInformations();\n\t\n\t\tif (keyMaterial == null) {\n\t\t\tPswDialogView.getView().displayErrorMessages(\"Key derivation failed.\\n\"\n\t\t\t\t\t+ \"Program bug.\");\n\t\t\tPswDialogView.clearPassword();\n\t\t\tif (CipherStuff.isBound() == false) {\n\t\t\t\t// reset the salt:\n\t\t\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\t\t\t}\n\t\t}\t\t\n\t\treturn keyMaterial;\n\t}\n\n\tpublic final static void initializeVariables() {\t\n\t\t\n\t\tHashStuff.setHashAlgo(PeaSettings.getHashAlgo() );\n\t\tCipherStuff.setCipherAlgo(PeaSettings.getCipherAlgo() );\n\t\tCipherStuff.setBound(PeaSettings.getBound());\n\t\tKeyDerivation.setKdf( PeaSettings.getKdfScheme() );\n\t\tKeyDerivation.settCost(PeaSettings.getIterations() );\n\t\t//KDFScheme.setScryptCPUFactor(PeaSettings.getIterations() );\n\t\tKeyDerivation.setmCost(PeaSettings.getMemory() );\n\t\tKeyDerivation.setArg3(PeaSettings.getParallelization());\n\t\tKeyDerivation.setVersionString(PeaSettings.getVersionString() );\n\t\tAttachments.setProgramRandomBytes(PeaSettings.getProgramRandomBytes() );\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes() );\n\t\t\n\t\tAttachments.setFileIdentifier(PeaSettings.getFileIdentifier() );\n\t}\n\t\n\t// If a blank PEA is started first: \n\tpublic final byte[] initializeCiphertext(byte[] ciphertext){\n\t\t// salt must be set manually and will be attached to the file later\n\t\t// in encryption step\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\t\tbyte[] attachedSalt = new RandomStuff().createRandomBytes(KeyDerivation.getSaltSize());\n\t\t// this will set attachedSalt and update the salt:\n\t\tKeyDerivation.setAttachedAndUpdateSalt(attachedSalt);\n\t\t\n\t\t// attach salt:\n\t\tciphertext = Attachments.attachBytes(ciphertext, attachedSalt);\n\t\t// attach fileIdentifier\n\t\tciphertext = Attachments.attachBytes(ciphertext, Attachments.getFileIdentifier());\n\t\t\n\t\treturn ciphertext;\n\t}\n\t\n\t// if the PAE is not bonded to a content: the salt is attached\n\tpublic final void handleAttachedSalt(byte[] ciphertext) {\n\t\t// reset salt if password failed before:\n\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes());\n\n\t\tbyte[] tmp = new byte[KeyDerivation.getSaltSize()];\n\t\tSystem.arraycopy(ciphertext, \n\t\t\t\tciphertext.length \n\t\t\t\t- Attachments.getFileIdentifierSize()\n\t\t\t\t- KeyDerivation.getSaltSize(), \n\t\t\t\ttmp, 0, tmp.length);\n\t\tKeyDerivation.setAttachedAndUpdateSalt(tmp);\n\t}\n\n\t//== file functions: ===============================================================\t\n\t\n\t// checks access and file identifier\n\t// sets errorMessages\n\tpublic final static boolean checkFile(String fileName) {\n\t\tFile file = new File( fileName );\t\t\n\t\t\n\n\t\tif (file.exists() && file.isFile() && file.canRead() && file.canWrite() ) {\n\t\t\t//byte[] content = ReadResources.readExternFile(PswDialogBase.getExternalFilePath());\n\t\t\tRandomAccessFile f;\n\t\t\ttry {\n\t\t\t\tf = new RandomAccessFile(file, \"rwd\");\n\t\t \tif ( Attachments.checkFileIdentifier(f, false) == true) {\n\t\t\t \tf.close();\n\t\t\t \t//============================\n\t\t\t \t// external file name success:\n\t\t\t \t//============================\n\t\t\t \treturn true;\n\t\t\t\t} else {\t\t\t\t\t\n\t\t\t\t\t/*if (fileType.equals(\"passwordSafe\") && f.length() == 0) { // just not initialized\n\t\t\t\t\t\tSystem.out.println(\"Program not initialized.\");\n\t\t\t\t\t\tf.close();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}*/\n\t\t\t\t\tf.close();\n\t\t\t\t\tSystem.out.println(\"PswDialogView: External file path - file identifier failed : \" + fileName );\n\t\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t\t+ fileName + languagesBundle.getString(\"file_identifier_failed\") + \"\\n\");//\": \\n file identifier failed.\\n\");\n\t\t\t\t}\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (HeadlessException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t} catch (Exception e) {\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t+ fileName + \": \" + e +\".\\n\");\n\t\t\t\t//e.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\n\t\n\t//\n\t// 1. checks external file name\n\t// 2. checks path file\n\t// success-> sets fileLabel, PswDialogBase.setEncryptedFileName(...)\n\t// no success -> PswDialogBase.setErrorMessage(...)\n\tpublic final static String searchSingleFile() {\n\t\t\n\t\tPswDialogBase.setErrorMessage(\"\");\n\n\t\t// 1. externalFilePath:\n\t\tif ( PeaSettings.getExternalFilePath() != null) {\n\t\t\t\n\t\t\tString externalFileName = PeaSettings.getExternalFilePath();\n\t\t/*\tif (PswDialogBase.getFileType().equals(\"passwordSafe\")) { \n\t\t\t\texternalFileName = externalFileName \n\t\t\t\t\t\t+ File.separator \n\t\t\t\t\t\t+ PswDialogBase.getJarFileName() + File.separator\n\t\t\t\t\t\t+ \"resources\" + File.separator + \"password_safe_1.lock\";\t\n\t\t\t}*/\n\t\t\tif ( checkFile(externalFileName) == true ) { // access and fileIdentifier\n\t\t\t\tPswDialogView.setFileName( PeaSettings.getExternalFilePath() );\n\t\t\t\tPswDialogBase.setEncryptedFileName( PeaSettings.getExternalFilePath() ); \n\t\t \treturn externalFileName;\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"PswDialogView: External file path invalid : \" + externalFileName );\n\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t\t//+ \"Default file: \" + EXTERNAL_FILE_PATH + \"--- No access.\\n\");\n\t\t\t\t\t\t+ languagesBundle.getString(\"default_file\") + \" \"\n\t\t\t\t\t\t+ PeaSettings.getExternalFilePath()\n\t\t\t\t\t\t+ \"--- \" + languagesBundle.getString(\"no_access\") + \"\\n\");\n\t\t\t}\n\n\t\t} else { //if (PswDialogBase.getEncryptedFileName() == null) {\n\t\t\tif (fileType.equals(\"image\") ) {\n\t\t\t\t//if ( PeaSettings.getBound() == false) {\n\t\t\t\t//\tSystem.out.println(\"Base\");\n\t\t\t\t//} else {\n\t\t\t\t\t// image was stored as text.lock inside jar file in directory resource\n\t\t\t\treturn \"insideJar\";\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t// check path file\n\t\tString[] pathNames = accessPathFile();\n\t\t\n\t\tif (pathNames == null) {\n\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\tPswDialogBase.getErrorMessage()\n\t\t\t\t\t+ languagesBundle.getString(\"no_path_file_result\") + \"\\n\");\n\t\t\t\t\t//+ \"No result from previously saved file names in path file.\\n\");\n\t\t} else {\n\t\t\t\n\t\t\tfor (int i = 0; i < pathNames.length; i++) {\n\t\t\t\t\n\t\t\t\tif (checkFile(pathNames[i]) == true ) {\n\t\t\t\t\tPswDialogView.setFileName(pathNames[i]);\n\t\t\t\t\tPswDialogBase.setEncryptedFileName(pathNames[i]);\n\t\t\t\t\treturn pathNames[i];\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\tPswDialogBase.setErrorMessage(\n\t\t\t\t\t\t\tPswDialogBase.getErrorMessage() +\n\t\t\t\t\t\t\t//\"File from path file: \" + pathNames[i] + \"--- No access.\\n\");\n\t\t\t\t\t languagesBundle.getString(\"file_from_path_file\") + \" \"\n\t\t\t\t\t+ pathNames[i] \n\t\t\t\t\t+ \"--- \" + languagesBundle.getString(\"no_access\") + \"\\n\");\n\t\t\t\t}\n\t\t\t}\t\t\t\t\t\t\n\t\t}\n\n\t\t// no file found from external file name and path file:\n\t\tif (PswDialogView.getFileName() == null) {\n\t\t\tPswDialogView.setFileName(languagesBundle.getString(\"no_valid_file_found\"));//\"no valid file found\");\n\t\t}\t\t\t\t\n\t\treturn null;\n\t}\n\t\n\t// detects file names from path file\n\tprotected final static String[] accessPathFile() {\n\t\tFile file = new File(PATH_FILE_NAME);\n\t\tif (! file.exists() ) {\n\t\t\tSystem.err.println(\"PswDialogBase: no path file specified\");\n\t\t\treturn null;\n\t\t}\n\t\tif (! file.canRead() ) {\n\t\t\tSystem.err.println(\"PswDialogBase: can not read path file \" + file.getName() );\n\t\t\tPswDialogView.setMessage(languagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t+ \"\\n\" + PATH_FILE_NAME);\n/*\t\t\tJOptionPane.showInternalMessageDialog(PswDialogView.getView(),\n\t\t\t\t\tlanguagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t//\"There is are file containing names of potentially encrypted files,\\n\" +\n\t\t\t\t//\" but no access to it: \\n\"\n\t\t\t\t+ PATH_FILE_NAME, \n\t\t\t\t\"Info\",//title\n\t\t\t\tJOptionPane.INFORMATION_MESSAGE);*/\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tbyte[] pathBytes = ReadResources.readExternFile( file.getName() );\n\t\tif (pathBytes == null) {\n\t\t\tSystem.err.println(\"PswDialogBase: path file does not contain any file name: \" + file.getPath() );\n\t\t\treturn null;\n\t\t}\n\t\tString pathString = new String(pathBytes, UTF_8);\n\n\t\tString[] pathNames = pathString.split(\"\\n\");\n\t\n\t\treturn pathNames;\t\t\t\n\t}\n\t\n\t// checks if file names already exist in path file\n\t// if not: adds them\t\n\tpublic final static void addFilesToPathFile(String[] selectedFileNames) {\n\n\t\tbyte[] newPathBytes = null;\n\t\tStringBuilder newPathNames = null;\n\t\t\t\t\n\t\tFile file = new File(PATH_FILE_NAME);\n\t\t\n\t\tif (! file.exists() ) { // WriteResources creates new file\n\t\t\t\n\t\t\tnewPathNames = new StringBuilder();\n\t\t\t\n\t\t\tfor (int i = 0; i < selectedFileNames.length; i++) {\n\t\t\t\tnewPathNames.append(selectedFileNames[i]);\n\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t}\n\t\t\t\n\t\t} else {\t// path file exists\n\t\t\n\t\t\tif (! file.canRead() || ! file.canWrite() ) {\n\t\t\t\tSystem.err.println(\"PswDialogBase: can not read and write path file \" + file.getName() );\n\t\t\t\t\n\t\t\t\tPswDialogView.setMessage(languagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t\t\t+ \"\\n\" \n\t\t\t\t\t\t+ PATH_FILE_NAME);\n\t\t\t/*\tJOptionPane.showInternalMessageDialog(PswDialogView.getView(),\n\t\t\t\t\t\tlanguagesBundle.getString(\"path_file_access_error\")\n\t\t\t\t\t//\"There is are file containing names of potentially encrypted files,\\n\" +\n\t\t\t\t\t//\" but no access to it: \\n\" \n\t\t\t\t\t+ PATH_FILE_NAME, \n\t\t\t\t\t\"Info\",//title\n\t\t\t\t\tJOptionPane.INFORMATION_MESSAGE); */\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// get file names from path file:\n\t\t\tString[] oldPathNames = accessPathFile();\n\t\t\t\n\t\t\tnewPathNames = new StringBuilder();\n\t\t\t\n\t\t\t// append old file names:\n\t\t\tfor (int i = 0; i < oldPathNames.length; i++) {\n\t\t\t\tnewPathNames.append(oldPathNames[i]);\n\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t}\n\t\t\t// check if file name already exists, if not append\n\t\t\tfor (int i = 0; i < selectedFileNames.length; i++) {\n\t\t\t\tboolean append = true;\n\t\t\t\tfor (int j = 0; j < oldPathNames.length; j++) {\n\t\t\t\t\tif (selectedFileNames[i].equals(oldPathNames[j] )){\n\t\t\t\t\t\tappend = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (append == true) {\n\t\t\t\t\tnewPathNames.append(selectedFileNames[i]);\n\t\t\t\t\tnewPathNames.append(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnewPathBytes = new String(newPathNames).getBytes(UTF_8);\n\t\t\t\n\t\tWriteResources.write(newPathBytes, PATH_FILE_NAME, null);\t\t\n\t}\n\t\n\t// checks if current encryptedFileName is in path file\n\t// asks to remember if not\n\tprotected final static void pathFileCheck() {\n\t\t//String encryptedFileName = getEncryptedFileName();\n\t\tif (encryptedFileName != null) {\n\t\t\tif (encryptedFileName.equals(PeaSettings.getExternalFilePath() )) {\n\t\t\t\treturn; // no need to remember\n\t\t\t}\t\t\t\n\t\t}\n\t\tString pathFileName = PeaSettings.getJarFileName() + \".path\";\n\t\tbyte[] pathFileContent = ReadResources.readExternFile(pathFileName);\n\t\tif (pathFileContent == null) {\n\t\t\tint n = JOptionPane.showConfirmDialog(null,\n\t\t\t\t\tlanguagesBundle.getString(\"remember_files\")\n\t\t\t//\t\t\"Should the name of the file be saved to remember for the next program start? \\n\" \n\t\t\t\t\t+ languagesBundle.getString(\"path_file_storage_info\")\n\t\t\t\t//+ \"The name is then saved in the same folder as this program in:\"\n\t\t\t+ pathFileName , \n\t\t\t\t\"?\", \n\t\t\t\tJOptionPane.OK_CANCEL_OPTION, \n\t\t\t\tJOptionPane.PLAIN_MESSAGE);\n\t\t\t\tif (n == 2) { // cancel\n\t\t\t\t\treturn;\n\t\t\t\t} else if (n == 0){\n\t\t\t\t\tbyte[] encryptedFileNameBytes = encryptedFileName.getBytes(UTF_8);\n\n\t\t\t\t\tWriteResources.write(encryptedFileNameBytes, pathFileName, null);\n\t\t\t\t}\n\t\t\treturn;\n\t\t} else {\n\t\t\tString pathNamesString = new String(pathFileContent, UTF_8);\n\n\t\t\tString[] pathNames = pathNamesString.split(\"\\n\");\n\t\t\t// check if encryptedFileName is already included\n\t\t\tfor (int i = 0; i < pathNames.length; i++) {\n\t\t\t\tif (pathNames[i].equals(encryptedFileName)) {\n\t\t\t\t\tSystem.out.println(\"Already included: \" + encryptedFileName);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t// is not included:\n\t\t\tint n = JOptionPane.showConfirmDialog(null,\n\t\t\t//\t\"Should the name of the file be saved to remember for the next program start? \\n\" \n\t\t\t//+ \"(The name is then saved in \" + pathFileName + \" in the same folder as this program).\", \n\t\t\tlanguagesBundle.getString(\"remember_files\")\n\t\t\t+ languagesBundle.getString(\"path_file_storage_info\")\n\t\t\t+ pathFileName , \n\t\t\t\"?\", \n\t\t\tJOptionPane.OK_CANCEL_OPTION, \n\t\t\tJOptionPane.PLAIN_MESSAGE);\n\t\t\tif (n == 2) { // cancel\n\t\t\t\treturn;\n\t\t\t} else if (n == 0){\n\t\t\t\tbyte[] encryptedFileNameBytes = (\"\\n\" + encryptedFileName).getBytes(UTF_8);\n\n\t\t\t\tbyte[] newContent = new byte[pathFileContent.length + encryptedFileNameBytes.length];\n\t\t\t\tSystem.arraycopy(pathFileContent, 0, newContent, 0, pathFileContent.length);\n\t\t\t\tSystem.arraycopy(encryptedFileNameBytes, 0, newContent, pathFileContent.length, encryptedFileNameBytes.length);\n\t\t\t\t\n\t\t\t\tif (newContent != null) {\n\t\t\t\t\tWriteResources.write(newContent, pathFileName, null);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\t\t\n\t} \n\n\n\t//==========================================\n\t// Getter & Setter\n\n\tpublic final static Charset getCharset(){\n\t\treturn UTF_8;\n\t}\n\t\n\tprotected final static void setFileType(String _fileType) {\n\t\tfileType = _fileType;\n\t}\n\tpublic final static String getFileType() {\n\t\treturn fileType;\n\t}\n\tpublic final static String getEncryptedFileName() {\n\t\treturn encryptedFileName;\n\t}\n\tpublic final static void setEncryptedFileName(String _encryptedFileName) {\n\t\tencryptedFileName = _encryptedFileName;\n\t}\n\tprotected final static void setDialog(PswDialogBase _dialog) {\n\t\tdialog = _dialog;\n\t}\n\tpublic final static PswDialogBase getDialog() {\n\t\treturn dialog;\n\t}\n\tpublic final static String getPathFileName() {\n\t\treturn PATH_FILE_NAME;\n\t}\n\tpublic final static JPanel getTypePanel() {\n\t\treturn typePanel;\n\t}\n\tpublic final static void setTypePanel( JPanel panel){\n\t\ttypePanel = panel;\n\t}\n\tpublic final static String getErrorMessage() {\n\t\treturn errorMessage;\n\t}\n\tpublic final static void setErrorMessage(String newErrorMessage) {\n\t\terrorMessage = newErrorMessage;\n\t}\n\tpublic final static ResourceBundle getBundle(){\n\t\tif (languagesBundle == null) { // set default language\n\t\t\ttry {\n\t\t\t\tsetLanguagesBundle(null);\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn languagesBundle;\n\t}\n\t\n\tpublic char[] getInitializedPasword(){\n\t\treturn initializedPassword;\n\t}\n\tpublic void setInitializedPassword(char[] psw){\n\t\tinitializedPassword = psw;\n\t}\n\t/**\n\t * @return the workingMode\n\t */\n\tpublic static String getWorkingMode() {\n\t\treturn workingMode;\n\t}\n\t/**\n\t * @param workingMode the workingMode to set\n\t */\n\tpublic static void setWorkingMode(String workingMode) {\n\t\tPswDialogBase.workingMode = workingMode;\n\t}\n}", "@SuppressWarnings(\"serial\")\npublic abstract class LockFrame extends JFrame implements WindowListener {\n\t\n\n\tprotected abstract void windowClosingCommands();\n\t\n\tprotected abstract byte[] getPlainBytes();\n\t\n\t\n\t\n\tpublic final static void saveContent(byte[] keyMaterial, byte[] plainBytes, String fileName) {\n\t\t\n\t\tif (new File(fileName).isFile() == false) {\n\t\t\tSystem.err.println(\"LockFrame wrong file\");\n\t\t\treturn;\n\t\t}\n\n\t\t//Help.printBytes(\"LockFrame: plainBytes\", plainBytes);\n\t\tbyte[] cipherBytes = CipherStuff.getInstance().encrypt(plainBytes, keyMaterial, \n\t\t\t\ttrue );\n\n\t\tif(PeaSettings.getExternFile() == true) {\n\t\t\tWriteResources.write(cipherBytes,fileName, null);\n\t\t} else {\n\t\t\tWriteResources.write(cipherBytes, \"text.lock\", \"resources\");// PswDialog2.jarFileName + File.separator +\n\t\t}\n\t}\n\t\n\tpublic final void changePassword(byte[] plainBytes, String[] fileNames){\n\t\t\n\t\tNewPasswordDialog newPswDialog = NewPasswordDialog.getInstance(this);\n\t\tchar[] newPsw = newPswDialog.getDialogInput();\t\t\n\t\t\n\t\tbyte[] keyMaterial = PswDialogBase.deriveKeyFromPsw(newPsw);\n\t\tif (newPsw != null){\n\t\t\tZeroizer.zero(newPsw);\n\t\t}\n\t\tbyte[] unfilledKeyMaterial = new byte[keyMaterial.length];\n\t\tfor (int i = 0; i < fileNames.length; i++) {\t\t\t\n\t\t\tif (keyMaterial != null) {\n\t\t\t\t// keyMaterial is filled/overwritten in encryption\n\t\t\t\tSystem.arraycopy(keyMaterial, 0, unfilledKeyMaterial, 0, keyMaterial.length);\t\n\t\t\t}\n\t\t\tsaveContent(unfilledKeyMaterial, plainBytes, fileNames[i]);\n\t\t}\n\t\tZeroizer.zero(keyMaterial);\n\t}\n\t\n\n\n\t@Override\n\tpublic void windowActivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowClosed(WindowEvent arg0) {}\n\n\t@Override\n\tpublic void windowClosing(WindowEvent arg0) {\n\t\twindowClosingCommands();\n\t\tSystem.exit(0);\n\t}\n\n\t@Override\n\tpublic void windowDeactivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowDeiconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowIconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowOpened(WindowEvent arg0) {}\n}", "@SuppressWarnings(\"serial\")\npublic class PswDialogView extends JDialog implements WindowListener,\n\t\tActionListener, KeyListener {\n\t\n\tprivate static final Color peaColor = new Color(230, 249, 233);\n\tprivate static final Color messageColor = new Color(252, 194, 171);//(255, 216, 151)\n\t\n\tprivate static JLabel pswLabel;\n\tprivate static JPasswordField pswField;\n\tprivate JButton okButton;\n\t\n\tprivate JPanel filePanel;\n\t\n\tprivate static JLabel fileLabel;\n\n\tprivate static String fileType = \"dingsda\";\n\t\n\tprivate static JCheckBox rememberCheck;\n\t\n\tprivate static PswDialogView dialog;\n\t\n\t// display warnings and error messages\n\tprivate static JTextArea messageArea;\n\t\n\tprivate static WhileTypingThread t;\n\t\n\tprivate static Image image;\n\t\n\tprivate static ResourceBundle languagesBundle;\n\t\n\tprivate static boolean started = false;// to check if decryption was startet by ok-button\n\t\n\tprivate static boolean initializing = false; // if started first time (no password, no content)\n\t\n\tprivate PswDialogView() {\n\t\t\n\t\tsetUI();\n\t\t\n\t\tlanguagesBundle = PswDialogBase.getBundle();\n\t\t\n\t\tfileType = PswDialogBase.getFileType();\n\t\n\t\tdialog = this;\n\t\tthis.setTitle(PeaSettings.getJarFileName() );\n\t\t\t\t\n\t\tthis.setBackground(peaColor);\n\n\t\tURL url = this.getClass().getResource(\"resources/pea-lock.png\");\n\t\tif (url == null) {\n\t\t\ttry{\n\t\t\timage = new ImageIcon(getClass().getClassLoader().getResource(\"resources/pea-lock.png\")).getImage();\n\t\t\t} catch (Exception e) {\n\t\t\t\tSystem.out.println(\"image not found\");\n\t\t\t}\n\t\t} else {\t\t\t\n\t\t\timage = new ImageIcon(url).getImage();\n\t\t}\n\n\n\t this.setIconImage(image);\n\t\n\t\tthis.addWindowListener(this);\n\t\t\n\t\tthis.addMouseMotionListener(new MouseRandomCollector() );\n\n\t\tJPanel topPanel = (JPanel) this.getContentPane();\n\t\t// more border for right and bottom to start\n\t\t// EntropyPool if there is no password\n\t\ttopPanel.setBackground(peaColor);\n\t\ttopPanel.setBorder(new EmptyBorder(5,5,15,15));\n\t\t\n\t\ttopPanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\n\t\tmessageArea = new JTextArea();\n\t\tmessageArea.setEditable(false);\t\n\t\tmessageArea.setLineWrap(true);\n\t\tmessageArea.setWrapStyleWord(true);\n\t\tmessageArea.setBackground(topPanel.getBackground());\t\t\n\t\t\n\t\tokButton = new JButton(\"ok\");\n\t\tokButton.setPreferredSize(new Dimension( 60, 30));\n\t\tokButton.setActionCommand(\"ok\");\n\t\tokButton.addActionListener(this);\n\t\t// if there is no password, this might be the only \n\t\t// chance to start EntropyPool\n\t\tokButton.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\n\t\ttopPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));\t\t\n\t\t\n\t\ttopPanel.add(messageArea);\n\t\t\n\t\tif (initializing == false) {\t\t\t\n\t\t\t\n\t\t\tif (PswDialogBase.getWorkingMode().equals(\"-r\")) { // rescue mode\n\t\t\t\tJLabel rescueLabel = new JLabel(\"=== RESCUE MODE ===\");\n\t\t\t\trescueLabel.setForeground(Color.RED);\n\t\t\t\ttopPanel.add(rescueLabel);\n\t\t\t}\n\n\t\t\tif (PeaSettings.getExternFile() == true) {\t// display files and menu\t\t\n\t\t\t\t\n\t\t\t\tif (fileType.equals(\"file\") ) {\n\t\t\t\t\tfilePanel = PswDialogBase.getTypePanel();\n\t\t\t\t\tfilePanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\t\t\ttopPanel.add(filePanel);\n\t\t\t\t\t\n\t\t\t\t} else { // text, passwordSafe, image: one single file\n\t\t\t\t\t\n\t\t\t\t\tJPanel singleFilePanel = new JPanel();\n\t\t\t\t\tsingleFilePanel.setLayout(new BoxLayout(singleFilePanel, BoxLayout.Y_AXIS));\n\t\t\t\t\t\n\t\t\t\t\tJPanel fileNamePanel = new JPanel();\n\t\t\t\t\tfileNamePanel.setLayout(new BoxLayout(fileNamePanel, BoxLayout.X_AXIS));\n\t\t\t\t\tsingleFilePanel.add(fileNamePanel);\n\t\t\t\t\t\n\t\t\t\t\tJLabel noteLabel = new JLabel();\n\t\t\t\t\tnoteLabel.setText(languagesBundle.getString(\"encrypted_file\"));//\"encryptedFile: \");\t\t\t\t\n\t\t\t\t\tfileNamePanel.add(noteLabel);\n\t\t\t\t\tfileNamePanel.add(Box.createHorizontalStrut(10));\n\t\t\t\t\t\n\t\t\t\t\tfileLabel = new JLabel(languagesBundle.getString(\"no_valid_file_found\") + languagesBundle.getString(\"select_new_file\"));//\"no valid file found - select a new file\");\n\t\t\t\t\tfileNamePanel.add(fileLabel);\n\t\t\t\t\tfileNamePanel.add(Box.createHorizontalGlue() );\n\t\t\t\t\t\n\t\t\t\t\tJPanel openButtonPanel = new JPanel();\n\t\t\t\t\topenButtonPanel.setLayout(new BoxLayout(openButtonPanel, BoxLayout.X_AXIS));\n\t\t\t\t\tsingleFilePanel.add(openButtonPanel);\n\t\t\t\t\t\n\t\t\t\t\tJButton openFileButton = new JButton();\n\t\t\t\t\topenFileButton.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11));\n\t\t\t\t\t\n\t\t\t\t\tif (fileType.equals(\"passwordSafe\")){\n\t\t\t\t\t\topenFileButton.setText(\"open directory\");\n\t\t\t\t\t} else { // text, image\n\t\t\t\t\t\topenFileButton.setText(languagesBundle.getString(\"open_file\"));//\"open file\");\n\t\t\t\t\t}\n\t\t\t\t\topenFileButton.addActionListener(this);\n\t\t\t\t\topenFileButton.setActionCommand(\"openFile\");\n\t\t\t\t\topenButtonPanel.add(openFileButton);\n\t\t\t\t\topenButtonPanel.add(Box.createHorizontalGlue() );\n\t\t\t\t\t\n\t\t\t\t\ttopPanel.add(singleFilePanel);\n\t\t\t\t\t\n\t\t\t\t\tif (PswDialogBase.searchSingleFile() == null) {\n\t\t\t\t\t\tJOptionPane.showMessageDialog(this,\n\t\t\t\t\t\t\t\tPswDialogBase.getErrorMessage(),\n\t\t\t\t\t\t\t \"Error\",\n\t\t\t\t\t\t\t JOptionPane.ERROR_MESSAGE);\n\t\t\t\t\t\t//reset errorMessage:\n\t\t\t\t\t\tPswDialogBase.setErrorMessage(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}//else\n\t\t\ttopPanel.add(Box.createVerticalStrut(10));//Box.createVerticalStrut(10));\n\t\t\t\n\t\t\tJPanel pswLabelPanel = new JPanel();\n\t\t\tpswLabelPanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tpswLabelPanel.setLayout(new BoxLayout(pswLabelPanel, BoxLayout.X_AXIS));\n\t\t\ttopPanel.add(pswLabelPanel);\n\t\t\t\n\t\t\tif (PeaSettings.getLabelText() == null) {\n\t\t\t\tpswLabel = new JLabel( languagesBundle.getString(\"enter_password\") );\n\t\t\t} else {\n\t\t\t\tpswLabel = new JLabel( PeaSettings.getLabelText() );\n\t\t\t\t//pswLabel.setText(PeaSettings.getLabelText() );\n\t\t\t}\n\t\t\tpswLabel.setPreferredSize(new Dimension( 460, 20));\n\t\t\tpswLabelPanel.add(pswLabel);\n\t\t\tpswLabelPanel.add(Box.createHorizontalGlue());\n\t\t\tJButton charTableButton = new JButton(languagesBundle.getString(\"char_table\"));\n\t\t\tcharTableButton.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tcharTableButton.addActionListener(this);\n\t\t\tcharTableButton.setActionCommand(\"charTable1\");\n\t\t\tpswLabelPanel.add(charTableButton);\n\n\t\t\t\n\t\t\tJPanel pswPanel = new JPanel();\n\t\t\tpswPanel.setLayout(new BoxLayout(pswPanel, BoxLayout.X_AXIS));\n\t\t\t\n\t\t\tpswField = new JPasswordField();\n\t\t\tpswField.setBackground(new Color(231, 231, 231) );\n\t\t\tpswField.setPreferredSize(new Dimension(400, 30));\n\t\t\tpswField.addKeyListener(this);\n\t\t\tpswField.addKeyListener(new KeyRandomCollector() );\n\n\t\t\tpswPanel.add(pswField);\n\t\t\t\n\t\t\tpswPanel.add(okButton);\n\t\t\ttopPanel.add(pswPanel);\n\t\t\n\t\t} else {// initializing\n\t\t\t\n\t\t\tif (fileType.equals(\"file\") ) {\n\t\t\t\tJPanel initPanel1 = new JPanel();\n\t\t\t\tinitPanel1.setLayout(new BoxLayout(initPanel1, BoxLayout.X_AXIS));\n\t\t\t\tJLabel fileInitializationLabel = new JLabel(\"Select one file and type a password to initialize...\");\n\t\t\t\tinitPanel1.add(fileInitializationLabel);\n\t\t\t\tinitPanel1.add(Box.createHorizontalGlue());\n\t\t\t\ttopPanel.add(initPanel1);\n\t\t\t\t\n\t\t\t\tJPanel initPanel2 = new JPanel();\n\t\t\t\tinitPanel2.setLayout(new BoxLayout(initPanel2, BoxLayout.X_AXIS));\n\t\t\t\tJLabel fileInitializationLabel2 = new JLabel(\"(you can add more files or directories later).\");\n\t\t\t\tinitPanel2.add(fileInitializationLabel2);\n\t\t\t\tinitPanel2.add(Box.createHorizontalGlue());\n\t\t\t\ttopPanel.add(initPanel2);\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tJPanel panel = new JPanel();\n\t\t\tpanel.setPreferredSize(new Dimension(400, 300));\n\t\t\tpanel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\t\n\t\t\tJLabel infoLabel = new JLabel(\"Initialization... \");\n\t\t\tinfoLabel.setForeground(Color.RED);\n\t\t\tinfoLabel.addMouseMotionListener(new MouseRandomCollector() );\n\t\t\tpanel.add(infoLabel);\n\t\t\tpanel.add(okButton);\n\t\t\t\n\t\t\ttopPanel.add(panel);\n\t\t}\t\t\n\t\t\n\t\tif (PeaSettings.getExternFile() == true){\t\t\n\t\t\t\n\t\t\tJPanel checkRememberPanel = new JPanel();\n\t\t\tcheckRememberPanel.setLayout(new BoxLayout(checkRememberPanel, BoxLayout.X_AXIS));\n\t\t\t\n\t\t\trememberCheck = new JCheckBox();\n\t\t rememberCheck = new JCheckBox();\t\n\t\t rememberCheck.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));\n\t\t rememberCheck.setText(languagesBundle.getString(\"remember_file_names\"));//\"remember selected file names\");\n\t\t rememberCheck.setToolTipText(languagesBundle.getString(\"file_storage_info\")// \"file names will be saved in the file \" +\n\t\t \t\t+ \" \" + PeaSettings.getJarFileName() + \".path\");// in current directory\");\n\t\t\t\n\t\t checkRememberPanel.add(Box.createVerticalStrut(10));\n\t\t checkRememberPanel.add(rememberCheck);\n\t\t checkRememberPanel.add(Box.createHorizontalGlue() );\n\t\t \n\t\t topPanel.add(checkRememberPanel);\n\t\t}\n\t\tif (PeaSettings.getKeyboard() != null) {\n\t\t\tJButton keyboardButton = new JButton(\"keyboard\");\n\t\t\tkeyboardButton.addActionListener(this);\n\t\t\tkeyboardButton.setActionCommand(\"keyboard\");\n\t\t\ttopPanel.add(keyboardButton);\t\t\t\n\t\t}\n\n\t\tthis.setLocation(100,30);\n\t\tpack();\n\t}\n\t\n\tpublic final static PswDialogView getInstance() {\n\t\tif (dialog == null) {\n\t\t\tdialog = new PswDialogView();\n\t\t} else {\n\t\t\t//return null\n\t\t}\n\t\treturn dialog;\n\t}\n\t\n\tpublic static void checkInitialization(){\n\t\t// check if this file was not yet initialized and if not, \n\t\t// remove password field\n\t\ttry {\n\t\t\t// the String \"uninitializedFile\" is stored in the file \"text.lock\"\n\t\t\t// if the pea was not yet initialized\n\t\t\t\n\t\t\t// try to read only the first line: \n\t\t\tBufferedReader brTest = new BufferedReader(new FileReader(\"resources\" + File.separator + \"text.lock\"));\n\t\t String test = brTest .readLine();\n\t\t brTest.close();\n\t\t\tif (test.startsWith(\"uninitializedFile\")){\n\t\t\t\t// set variable initializing to indicate that there is no password or content \n\t\t\t\t//PswDialogView.setInitialize(true);\n\t\t\t\tinitializing = true;\n\t\t\t\tSystem.out.println(\"Initialization\");\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\tpublic final void displayErrorMessages(String topic) {\n\t\t\n\t\tsetMessage(topic + \":\\n\" + CipherStuff.getErrorMessage());\n\n\t\tPswDialogView.clearPassword();\n\t}\n\n\t@Override\n\tpublic void keyPressed(KeyEvent kpe) {\n\t\t// EntropyPool must be started by mouse events if initializing\n\t\tif(kpe.getKeyChar() == KeyEvent.VK_ENTER && initializing == false){\n\t\t\tokButton.doClick();\n\t\t}\n\t}\n\t@Override\n\tpublic void keyReleased(KeyEvent arg0) {}\n\t@Override\n\tpublic void keyTyped(KeyEvent arg0) {}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent ape) {\n\t\tString command = ape.getActionCommand();\n\t\t//System.out.println(\"command: \" + command);\n\t\tif(command.equals(\"keyboard\")){\n\t\t\tPeaSettings.getKeyboard().setVisible(true);\n\t\t\t\n\t\t} else if (command.equals(\"charTable1\")){\n\t\t\tCharTable table = new CharTable(this, pswField);\n\t\t\ttable.setVisible(true);\n\t\t\t\n\t\t} else if (command.equals(\"ok\")){\n\n\t\t\tif (PeaSettings.getKeyboard() != null) {\n\t\t\t\tPeaSettings.getKeyboard().dispose();\n\t\t\t}\n\t\t\t\n\t\t\tstarted = true;\n\n\t\t\tEntropyPool.getInstance().stopCollection();\n\n\t\t\tif (PeaSettings.getExternFile() == true && initializing == false) {\n\n\t\t\t\t// remember this file?\n\t\t\t\tif (rememberCheck.isSelected() ) {\n\t\t\t\t\t\n\t\t\t\t\t\tString[] newNames;\n\t\t\t\t\t\tif (PswDialogBase.getFileType().equals(\"file\")) {\n\t\t\t\t\t\t\t// set encrypted file names:\n\t\t\t\t\t\t\tnewNames = PswDialogBase.getDialog().getSelectedFileNames();\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnewNames = new String[1];\n\t\t\t\t\t\t\tnewNames[0] = PswDialogBase.getEncryptedFileName();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tPswDialogBase.addFilesToPathFile( newNames );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif ( ! fileType.equals(\"file\")) { // text, image\n\t\t\t\t\t\n\t\t\t\t\t// check if one valid file is selected:\n\t\t\t\t\tif (PswDialogBase.getEncryptedFileName() == null) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tsetMessage(languagesBundle.getString(\"no_file_selected\"));\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\t\t} else { // file\n\t\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\t\t}\n\t\t\t} else { // internal File in directory \"resources\"\n\n\t\t\t\t// set resources/text.lock as encryptedFileName\n\t\t\t\tString newFileName = \"resources\" + File.separator + \"text.lock\";\n\n\t\t\t\tPswDialogBase.setEncryptedFileName(newFileName);\n\n\t\t\t\tPswDialogBase.getDialog().startDecryption();\n\t\t\n\t\t\t\t// remember this file?\n\t\t\t\tif (PeaSettings.getExternFile() == true && initializing == false) {\n\t\t\t\t\tif (rememberCheck.isSelected() ) {\n\t\t\t\t\t\tString[] newName = { PswDialogBase.getEncryptedFileName() };\n\t\t\t\t\t\tPswDialogBase.addFilesToPathFile( newName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstarted = false;\n\n\t\t\t\n\t\t} else if (command.equals(\"openFile\")) {\n\n\t\t\tJFileChooser chooser = new JFileChooser();\n\n\t\t\tif (fileType.equals(\"text\")) {\n\t\t\t\tFileNameExtensionFilter filter = new FileNameExtensionFilter(\"TEXT FILES\", \"txt\", \"text\", \"rtf\");\n\t\t\t\tchooser.setFileFilter( filter );\n\t\t\t} else if (fileType.equals(\"passwordSafe\")) {\n\t\t\t\tchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n\t\t\t chooser.setAcceptAllFileFilterUsed(false);\n\t\t\t} else if (fileType.equals(\"image\")) {\n\t\t\t\tFileNameExtensionFilter filter = new FileNameExtensionFilter(\"IMAGE FILES\", \"png\", \"jpg\", \"jpeg\", \"bmp\", \"gif\");\n\t\t\t\tchooser.setFileFilter( filter );\n\t\t\t}\n\t\t int returnVal = chooser.showOpenDialog(this);\n\t\t if(returnVal == JFileChooser.APPROVE_OPTION) {\t\t \n\t\t \t\n\t\t \tFile file = chooser.getSelectedFile();\n\t\t \tString selectedFileName = file.getAbsolutePath();\n\t\t \t\n\t\t \tif ( PswDialogBase.checkFile(selectedFileName ) == true ) {\n\t\t\t\t\tfileLabel.setText( selectedFileName );\n\t\t\t\t\tPswDialogBase.setEncryptedFileName( selectedFileName ); \n\t\t \t} else {\n\t\t \t\tsetMessage(languagesBundle.getString(\"error\") \n\t\t \t\t\t\t+ \"\\n\" + languagesBundle.getString(\"no_access_to_file\")\n\t\t \t\t\t\t+ \"\\n\" + file.getAbsolutePath());\n\t\t\t\t\treturn;\n\t\t \t}\n\t\t }\n\t\t}\t\t\n\t}\n\t\n\n\t@Override\n\tpublic void windowActivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowClosed(WindowEvent arg0) { // dispose\n\n\t\t// if attacker has access to memory but not to file\n\t\tif (Attachments.getNonce() != null) {\n\t\t\tZeroizer.zero(Attachments.getNonce());\n\t\t}\n\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\tPswDialogBase.getDialog().clearSecretValues();\n\t\t}\t\n\n\t\tthis.dispose();\n\t\t//System.exit(0);\t// do not exit, otherwise files leave unencrypted\t\n\t}\n\t@Override\n\tpublic void windowClosing(WindowEvent arg0) { // x\n\t\t\n\t\tif (started == true) {\n\t\t\treturn;\n\t\t} else {\n\t\t\t// if attacker has access to memory but not to file\n\t\t\tif (Attachments.getNonce() != null) {\n\t\t\t\tZeroizer.zero(Attachments.getNonce());\n\t\t\t}\n\t\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\t\tPswDialogBase.getDialog().clearSecretValues();\n\t\t\t}\n\t\t\tSystem.exit(0);\n\t\t}\t\n\t}\n\t@Override\n\tpublic void windowDeactivated(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowDeiconified(WindowEvent arg0) {}\n\t@Override\n\tpublic void windowIconified(WindowEvent arg0) {}\n\n\t@Override\n\tpublic void windowOpened(WindowEvent arg0) {\n\t\t\n\t\t// do some expensive computations while user tries to remember the password\n\t\tt = this.new WhileTypingThread();\n\t\tt.setPriority( Thread.MAX_PRIORITY );// 10\n\t\tt.start();\n\t\tif (initializing == false) {\n\t\t\tpswField.requestFocus();\n\t\t}\n\t}\n\n\t\n\t//=======================================\n\t// Helper Functions\n\t\n\tpublic final static void setUI() {\n//\t\tUIManager.put(\"Button.background\", peaColor );\t\t\t\t\t\n//\t\tUIManager.put(\"MenuBar.background\", peaColor ); // menubar\n//\t\tUIManager.put(\"MenuItem.background\", color2 ); // menuitem\n\t\tUIManager.put(\"PopupMenu.background\", peaColor );\t//submenu\t\t\t\t\t\t\t\t\t\n\t\tUIManager.put(\"OptionPane.background\", peaColor );\n\t\tUIManager.put(\"Panel.background\", peaColor );\n\t\tUIManager.put(\"RadioButton.background\", peaColor );\n\t\tUIManager.put(\"ToolTip.background\", peaColor );\n\t\tUIManager.put(\"CheckBox.background\", peaColor );\t\n\t\t\n\t\tUIManager.put(\"InternalFrame.background\", peaColor );\n\t\tUIManager.put(\"ScrollPane.background\", peaColor );\n\t\tUIManager.put(\"Viewport.background\", peaColor );\t\n\t\t// ScrollBar.background Viewport.background\n\t}\n\t\n\n\t\n\tprotected final static void updateView(){\n\t\tdialog.dispose();\n\t\tdialog = new PswDialogView();\n\t\tdialog.setVisible(true);\n\t}\n\t\n\t/**\n\t * Perform he action for ok button. Used for initialization. \n\t */\n\tpublic void clickOkButton() {\n\t\tokButton.doClick();\n\t}\n\t\n\n\t\n\t//===============================================\n\t// Getter & Setter\n\tpublic final static char[] getPassword() {\n\t\treturn pswField.getPassword();\n\t}\n\tprotected final static void setPassword(char[] psw) { // for Keyboard\n\t\tpswField.setText( new String(psw) );\n\t}\n\tprotected final static void setPassword(char pswChar) { // for charTable\n\t\tpswField.setText(\"\" + pswChar );\n\t}\n\tpublic final static void clearPassword() {\n\t\tif (pswField != null) {\n\t\t\tpswField.setText(\"\");\n\t\t}\n\t}\n\tpublic final static void setMessage(String message) {\n\t\tif (message != null) {\n\t\t\tmessageArea.setBackground(messageColor);\n\t\t\tmessageArea.setText(message);\n\t\t\tdialog.pack();\n\t\t}\n\t}\n\tpublic final static void setLabelText(String labelText) {\n\t\tif (initializing == true){\n\t\t\tpswLabel.setText(labelText);\n\t\t}\n\t}\n\tpublic final static WhileTypingThread getThread() {\n\t\treturn t;\n\t}\n\tpublic final static Image getImage() {\n\t\tif (image == null) {\n\t\t\tSystem.err.println(\"PswDialogView getImage: image null\");\n\t\t}\n\t return image;\n\t}\n\tpublic final static PswDialogView getView() {\n\t\treturn dialog;\n\t}\n\tpublic final JPanel getFilePanel() {\n\t\treturn filePanel;\n\t}\n\tpublic final static void setFileName(String fileName) {\n\t\tfileLabel.setText(fileName);\n\t}\n\tpublic final static String getFileName() {\n\t\treturn fileLabel.getText();\n\t}\n\tpublic final static Color getPeaColor(){\n\t\treturn peaColor;\n\t}\n\t\n\t/**\n\t * @return the initializing\n\t */\n\tpublic static boolean isInitializing() {\n\t\treturn initializing;\n\t}\n\n\t/**\n\t * @param initializing the initializing to set\n\t */\n\tpublic static void setInitializing(boolean initialize) {\n\t\tPswDialogView.initializing = initialize;\n\t}\n\n\t//================================================\n\t// inner class\n\tpublic class WhileTypingThread extends Thread {\n\t\t// some pre-computations while typing the password\n\t\t@Override\n\t\tpublic void run() {\t\t\n\t\t\tif (PswDialogBase.getDialog() != null) {\n\t\t\t\tPswDialogBase.getDialog().preComputeInThread();\n\t\t\t}\n\t\t}\n\t}\n}", "public final class Converter {\n\t\n\tpublic final static int[] chars2ints( char[] input) {\n\t\tif (input == null) {\n\t\t\tSystem.err.println(\"Converter: input null (char -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (input.length %2 != 0) {\n\t\t\tSystem.err.println(\"Converter (char -> int): wrong size, must be even. Is padded.\");\n\t\t\tchar[] tmp = new char[input.length + 1];\n\t\t\tSystem.arraycopy(input, 0 ,tmp, 0, input.length);\n\t\t\ttmp[tmp.length - 1] = '\\0';\n\t\t}\n\t\tint[] result = new int[input.length / 2];\n\t\t\n\t\tfor (int i=0; i<result.length; i++) {\n\t\t\t//System.out.println(\" \" + ( (int)input[i*2]) + \" \" + (((int) (input[i*2+1]) << 16)));\n\t\t\tresult[i] = ( (int)input[i*2]) | (((int) (input[i*2+1]) << 16));\n\t\t}\n\t\treturn result;\n\t}\t\t\n\t// Converts char[] to byte[]\n\tpublic final static byte[] chars2bytes(char[] charArray) {\n\t\tif (charArray == null) {\n\t\t\tSystem.err.println(\"Converter: input null (char -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = Charset.forName(\"UTF-8\").encode(CharBuffer.wrap(charArray)).array();\n\t\treturn result;\n\t}\n\t// Converts byte[] to char[]\n\tpublic final static char[] bytes2chars(byte[] byteArray) {\t\t\n\t\t//ByteBuffer bbuff = ByteBuffer.allocate(byteArray.length);\n\t\tif (byteArray == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> char)\");\n\t\t\treturn null;\n\t\t}\t\t\n\t\tchar[] result = Charset.forName(\"UTF-8\").decode(ByteBuffer.wrap(byteArray)).array();\n\t\t\n\t\t// cut last null-bytes, appeared because of Charset/CharBuffer in bytes2chars for Linux\n\t\tint cutMarker;\n\t\tfor (cutMarker = result.length - 1; cutMarker > 0; cutMarker--) {\n\t\t\tif (result[cutMarker] != 0) break;\n\t\t}\n\t\tchar[] tmp = new char[cutMarker + 1];\n\t\tSystem.arraycopy(result, 0, tmp, 0, cutMarker + 1);\n\t\tZeroizer.zero(result);\n\t\tresult = tmp;\t\t\t\n\t\t\n\t\treturn result;\n\t}\n\n\t\n\t//===============================\n\t// BIG ENDIAN:\n\t\n\tpublic final static int[] bytes2intsBE( byte[] bytes) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+3] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Convert an array of 8-bit signed values (Java: bytes) \n\t * into an array of 32-bit signed values (Java: int)\n\t * \n\t * @param bytes\t\tinput: array of 8-bit signed values to convert\n\t * @param inIndex\tindex at input to start\n\t * @param inLen\t\tnumber of bytes to convert\n\t * @param outIndex\tindex at output, to store the converted values\n\t * @return\t\t\toutput: array of 32-bit signed vales, \n\t * \t\t\t\t\tmust be larger than outIndex + inLen/4\n\t */\n\tpublic final static int[] bytes2intsBE( byte[] bytes, int inIndex, int inLen, int outIndex) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+3] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic final static byte[] ints2bytesBE(int[] ints) {\n\t\tif (ints == null) {\n\t\t\tSystem.err.println(\"Converter: input null (int -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[ints.length * 4];\n\t\tfor (int i = 0; i < ints.length; i++ ) {\n\t\t\tresult[i*4+3] = (byte) (ints[i]);\n\t\t\tresult[i*4+2] = (byte)(ints[i] >>> 8);\n\t\t\tresult[i*4+1] = (byte)(ints[i] >>> 16);\n\t\t\tresult[i*4] = (byte)(ints[i] >>> 24);\n\t\t}\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] int2bytesBE(int input) {\n\n\t\tbyte[] result = new byte[4];\n\n\t\t\tresult[3] = (byte) (input);\n\t\t\tresult[2] = (byte)(input >>> 8);\n\t\t\tresult[1] = (byte)(input >>> 16);\n\t\t\tresult[0] = (byte)(input >>> 24);\n\t\t\n\t\treturn result;\n\t}\n\t\n\t\n\tpublic final static byte[] long2bytesBE(long longValue) {\n\t return new byte[] {\n\t (byte) (longValue >> 56),\n\t (byte) (longValue >> 48),\n\t (byte) (longValue >> 40),\n\t (byte) (longValue >> 32),\n\t (byte) (longValue >> 24),\n\t (byte) (longValue >> 16),\n\t (byte) (longValue >> 8),\n\t (byte) longValue\n\t };\n\t}\n\tpublic final static byte[] longs2bytesBE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 8];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 8 + 0] = (byte) (longArray[i] >>> 56);\n\t\t\tresult[i * 8 + 1] = (byte) (longArray[i] >>> 48);\n\t\t\tresult[i * 8 + 2] = (byte) (longArray[i] >>> 40);\n\t\t\tresult[i * 8 + 3] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 8 + 4] = (byte) (longArray[i] >>> 24);\n\t\t\tresult[i * 8 + 5] = (byte) (longArray[i] >>> 16);\n\t\t\tresult[i * 8 + 6] = (byte) (longArray[i] >>> 8);\n\t\t\tresult[i * 8 + 7] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static long bytes2longBE(byte[] byteArray) {\n\t\tif (byteArray.length != 8) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t return ((long)(byteArray[0] & 0xff) << 56) |\n\t ((long)(byteArray[1] & 0xff) << 48) |\n\t ((long)(byteArray[2] & 0xff) << 40) |\n\t ((long)(byteArray[3] & 0xff) << 32) |\n\t ((long)(byteArray[4] & 0xff) << 24) |\n\t ((long)(byteArray[5] & 0xff) << 16) |\n\t ((long)(byteArray[6] & 0xff) << 8) |\n\t ((long)(byteArray[7] & 0xff));\n\t}\n\tpublic final static long[] bytes2longsBE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length: \" + byteArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[byteArray.length / 8];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = \n\t\t\t ((long)(byteArray[i * 8 + 0] & 0xff) << 56) |\n\t\t ((long)(byteArray[i * 8 + 1] & 0xff) << 48) |\n\t\t ((long)(byteArray[i * 8 + 2] & 0xff) << 40) |\n\t\t ((long)(byteArray[i * 8 + 3] & 0xff) << 32) |\n\t\t ((long)(byteArray[i * 8 + 4] & 0xff) << 24) |\n\t\t ((long)(byteArray[i * 8 + 5] & 0xff) << 16) |\n\t\t ((long)(byteArray[i * 8 + 6] & 0xff) << 8) |\n\t\t ((long)(byteArray[i * 8 + 7] & 0xff));\n\t\t}\n\t return result;\n\t}\n\tpublic final static long[] ints2longsBE(int[] intArray) {\n\t\tif (intArray.length % 2 != 0) {\n\t\t\tSystem.err.println(\"Converter ints2long: invalid length: \" + intArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[intArray.length / 2];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = (long) (intArray[i * 2 + 1] & 0x00000000FFFFFFFFL) \n\t\t\t\t\t| (long)intArray[i * 2 + 0] << 32;\n\t\t}\n\t return result;\n\t}\n\t\n\t//===============================\n\t// LITTLE ENDIAN:\n\tpublic final static int[] bytes2intsLE( byte[] bytes) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4+3 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+0] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\tpublic final static byte[] ints2bytesLE(int[] ints) {\n\t\tif (ints == null) {\n\t\t\tSystem.err.println(\"Converter: input null (int -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[ints.length * 4];\n\t\tfor (int i = 0; i < ints.length; i++ ) {\n\t\t\tresult[i*4+0] = (byte) (ints[i]);\n\t\t\tresult[i*4+1] = (byte)(ints[i] >>> 8);\n\t\t\tresult[i*4+2] = (byte)(ints[i] >>> 16);\n\t\t\tresult[i*4+3] = (byte)(ints[i] >>> 24);\n\t\t}\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] int2bytesLE(int input) {\n\n\t\tbyte[] result = new byte[4];\n\t\tresult[0] = (byte) (input);\n\t\tresult[1] = (byte)(input >>> 8);\n\t\tresult[2] = (byte)(input >>> 16);\n\t\tresult[3] = (byte)(input >>> 24);\t\n\t\treturn result;\n\t}\n\n\t\n\tpublic final static byte[] long2bytesLE(long longValue) {\n\t return new byte[] {\n\t (byte) (longValue),\n\t (byte) (longValue >> 8),\n\t (byte) (longValue >> 16),\n\t (byte) (longValue >> 24),\n\t (byte) (longValue >> 32),\n\t (byte) (longValue >> 40),\n\t (byte) (longValue >> 48),\n\t (byte) (longValue >> 56)\n\t };\n\t}\n\tpublic final static byte[] longs2bytesLE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 8];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 8 + 7] = (byte) (longArray[i] >>> 56);\n\t\t\tresult[i * 8 + 6] = (byte) (longArray[i] >>> 48);\n\t\t\tresult[i * 8 + 5] = (byte) (longArray[i] >>> 40);\n\t\t\tresult[i * 8 + 4] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 8 + 3] = (byte) (longArray[i] >>> 24);\n\t\t\tresult[i * 8 + 2] = (byte) (longArray[i] >>> 16);\n\t\t\tresult[i * 8 + 1] = (byte) (longArray[i] >>> 8);\n\t\t\tresult[i * 8 + 0] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static byte[] longs2intsLE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 2];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 2 + 1] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 2 + 0] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static long bytes2longLE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length: \" + byteArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t return \n\t ((long)(byteArray[7] & 0xff) << 56) |\n\t ((long)(byteArray[6] & 0xff) << 48) |\n\t ((long)(byteArray[5] & 0xff) << 40) |\n\t ((long)(byteArray[4] & 0xff) << 32) |\n\t ((long)(byteArray[3] & 0xff) << 24) |\n\t ((long)(byteArray[2] & 0xff) << 16) |\n\t ((long)(byteArray[1] & 0xff) << 8) |\n\t ((long)(byteArray[0] & 0xff));\n\t}\n\tpublic final static long[] bytes2longsLE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[byteArray.length / 8];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = \n\t\t\t ((long)(byteArray[i * 8 + 7] & 0xff) << 56) |\n\t\t ((long)(byteArray[i * 8 + 6] & 0xff) << 48) |\n\t\t ((long)(byteArray[i * 8 + 5] & 0xff) << 40) |\n\t\t ((long)(byteArray[i * 8 + 4] & 0xff) << 32) |\n\t\t ((long)(byteArray[i * 8 + 3] & 0xff) << 24) |\n\t\t ((long)(byteArray[i * 8 + 2] & 0xff) << 16) |\n\t\t ((long)(byteArray[i * 8 + 1] & 0xff) << 8) |\n\t\t ((long)(byteArray[i * 8 + 0] & 0xff));\n\t\t}\n\t return result;\n\t}\n\tpublic final static long[] ints2longsLE(int[] intArray) {\n\t\tif (intArray.length % 2 != 0) {\n\t\t\tSystem.err.println(\"Converter ints2long: invalid length: \" + intArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[intArray.length / 2];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = (long)intArray[i * 2 + 1] << 32 |\n\t\t\t\t\t(long) (intArray[i * 2 + 0] & 0x00000000FFFFFFFFL);\n\t\t}\n\t return result;\n\t}\n\t\n/*\tpublic final static byte[] swapBytes(byte[] byteArray) {\n\t\tbyte[] result = new byte[byteArray.length];\n\t\tint index = result.length -1;\n\t\tfor (int i = 0; i < byteArray.length; i++) {\n\t\t\tresult[index--] = byteArray[i];\n\t\t}\n\t\treturn result;\n\t}*/\n\t\n\tpublic final static long swapEndianOrder (long longValue) {\n\t\treturn\n\t\t\t((((long)longValue) << 56) & 0xff00000000000000L) | \n\t\t\t((((long)longValue) << 40) & 0x00ff000000000000L) | \n\t\t\t((((long)longValue) << 24) & 0x0000ff0000000000L) | \n\t\t\t((((long)longValue) << 8) & 0x000000ff00000000L) | \n\t\t\t((((long)longValue) >> 8) & 0x00000000ff000000L) | \n\t\t\t((((long)longValue) >> 24) & 0x0000000000ff0000L) | \n\t\t\t((((long)longValue) >> 40) & 0x000000000000ff00L) | \n\t\t\t((((long)longValue) >> 56) & 0x00000000000000ffL);\n\t}\n\tpublic final static int swapEndianOrder (int intValue) {\n\t\treturn\n\t\t\t((((int)intValue) << 24) & 0xff000000) | \n\t\t\t((((int)intValue) << 8) & 0x00ff0000) | \n\t\t\t((((int)intValue) >>> 8) & 0x0000ff00) | \n\t\t\t((((int)intValue) >>> 24) & 0x000000ff);\n\t}\n\t\n\t//==============================================\n\t// HEX STRINGS AND BYTE ARRAYS:\n\tpublic final static byte[] hex2bytes(String hexString) {\n\n\t\tbyte[] byteArray = new byte[hexString.length() / 2];// 2 Character = 1 Byte\n\t\t\tint len = hexString.length();\n\t\t\tif ( (len & 1) == 1){ // ungerade\n\t\t\t\tSystem.err.println(\"Illegal Argument (Function hexStringToBytes): HexString is not even\");\n\t\t\t\treturn byteArray; // return null-Array\n\t\t\t}\n\t\t\tfinal char [] hexCharArray = hexString.toCharArray ();// Umwandeln in char-Array\n\t\t\tfor (int i = 0; i < hexString.length(); i+=2) {\n\t\t\t\t// 1. char in hex <<4, 2. char in hex\n\t\t\t\tbyteArray[i / 2] = (byte) ((Character.digit (hexCharArray[i], 16) << 4) \n\t\t\t\t\t\t\t\t+ Character.digit (hexCharArray[i + 1], 16));\n\t\t\t}\t\t\n\t\t\treturn byteArray;\n\t}\n\t\n\tpublic final static char[] hexArray = \"0123456789ABCDEF\".toCharArray();\n\tpublic static String bytes2hex(byte[] bytes) {\n\t char[] hexChars = new char[bytes.length * 2];\n\t for ( int j = 0; j < bytes.length; j++ ) {\n\t int v = bytes[j] & 0xFF;\n\t hexChars[j * 2] = hexArray[v >>> 4];\n\t hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n\t }\n\t return new String(hexChars);\n\t}\n\tprivate static final String HEXES = \"0123456789ABCDEF\";\n\tpublic static String getHex( byte [] raw ) {\n\t final StringBuilder hex = new StringBuilder( 2 * raw.length );\n\t for ( final byte b : raw ) {\n\t hex.append(HEXES.charAt((b & 0xF0) >> 4))\n\t .append(HEXES.charAt((b & 0x0F)));\n\t }\n\t return hex.toString();\n\t // oder: System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));\n\t}\n\t\n\t//===========================================\n\t// DOCUMENTS AND BYTE ARRAYS\n\tpublic final static byte[] serialize(DefaultStyledDocument dsd) {\n\n\t\tRTFEditorKit kit = new RTFEditorKit();\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\ttry {\n\t\t\tkit.write( out, dsd, 0, dsd.getLength() );\n\t\t\tout.close();\n\t\t} catch (BadLocationException e) {\n\t\t\tSystem.err.println(\"Converter: \" + e);\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"Converter: \" + e);\n\t\t\te.printStackTrace();\n\t\t} \n\t return out.toByteArray();\n\t}\n\tpublic final static DefaultStyledDocument deserialize(byte[] data) {\n\t\tRTFEditorKit kit = new RTFEditorKit();\n\t\tDefaultStyledDocument dsd = new DefaultStyledDocument();\n\t\tByteArrayInputStream in = new ByteArrayInputStream(data);\n\t\ttry {\n\t\t\tkit.read(in, dsd, 0);\n\t\t\tin.close();\n\t\t} catch (BadLocationException e) {\n\t\t\t// \n\t\t\tSystem.err.println(\"Converter deserialize: \"+ e.toString());\n\t\t\treturn null;\n\t\t\t//e.printStackTrace();\n\t\t\t//System.err.println(\"BadLocationException\");\n\t\t} catch (IOException e) {\n\n\t\t\tSystem.err.println(\"Converter deserialize: \"+ e.toString());\n\t\t\treturn null;\n\t\t\t//e.printStackTrace();\n\t\t}\t\t\n\t return dsd;\n\t}\n}" ]
import cologne.eck.peafactory.crypto.CipherStuff; import cologne.eck.peafactory.peas.PswDialogBase; import cologne.eck.peafactory.peas.gui.LockFrame; import cologne.eck.peafactory.peas.gui.PswDialogView; import cologne.eck.peafactory.tools.Converter; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.*; import javax.swing.text.rtf.RTFEditorKit; import javax.swing.undo.*;
package cologne.eck.peafactory.peas.editor_pea; /* * Peafactory - Production of Password Encryption Archives * Copyright (C) 2015 Axel von dem Bruch * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See: http://www.gnu.org/licenses/gpl-2.0.html * You should have received a copy of the GNU General Public License * along with this library. */ /** * Main frame of editor pea. */ @SuppressWarnings("serial") class LockFrameEditor extends LockFrame implements MouseListener, DocumentListener { private static LockFrameEditor frame; protected static JTextPane textPane; private static boolean popupStarted = false; private CopyCutPastePopup popup; protected static UndoManager manager;// = new UndoManager(); protected static RTFEditorKit kit = null; private static boolean docChangeUnsaved = false; private boolean firstChange = true; protected static PswDialogEditor dialog; private LockFrameEditor(PswDialogEditor _dialog) { frame = this; dialog = _dialog;
this.setIconImage( PswDialogView.getImage() );
3
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/LocalIMEKeyboard.java
[ "public class WebReviewActivity extends AppCompatActivity {\n\n /**\n * This class is barely a container of all the strings that should match with the\n * WaniKani portal. Hopefully none of these will ever be changed, but in case\n * it does, here is where to look for.\n */\n public static class WKConfig {\n\n /** HTML id of the textbox the user types its answer in (reviews, client-side) */\n static final String ANSWER_BOX = \"user-response\";\n\n /** HTML id of the textbox the user types its answer in (lessons) */\n static final String LESSON_ANSWER_BOX_JP = \"translit\";\n\n /** HTML id of the textbox the user types its answer in (lessons) */\n static final String LESSON_ANSWER_BOX_EN = \"lesson_user_response\";\n\n /** HTML id of the submit button */\n static final String SUBMIT_BUTTON = \"option-submit\";\n\n /** HTML id of the lessons review form */\n static final String LESSONS_REVIEW_FORM = \"new_lesson\";\n\n /** HTML id of the lessons quiz */\n static final String QUIZ = \"quiz\";\n\n /** HTML id of the start quiz button (modal) */\n static final String QUIZ_BUTTON1 = \"quiz-ready-continue\";\n\n /** HTML id of the start quiz button (bottom green arrow) */\n static final String QUIZ_BUTTON2 = \"active-quiz\";\n\n /** Any object on the lesson pages */\n static final String LESSONS_OBJ = \"nav-lesson\";\n\n /** Reviews div */\n static final String REVIEWS_DIV = \"reviews\";\n\n /** HTML id of character div holding (kanji/radical/vocab) being reviewed. @Aralox **/\n static final String CHARACTER_DIV = \"character\";\n\n /** JQuery Element (kanji/radical/vocab) being reviewed. Assumed only 1 child span. @Aralox **/\n static final String CHARACTER_SPAN_JQ = \"#\"+CHARACTER_DIV+\">span\";\n\n /** HTML id of item-info panel. @Aralox **/\n static final String ITEM_INFO_DIV = \"item-info\";\n\n /** HTML id of item-info button. @Aralox **/\n static final String ITEM_INFO_LI = \"option-item-info\";\n };\n\n /**\n * The listener attached to the ignore button tip message.\n * When the user taps the ok button, we write on the property\n * that it has been acknowleged, so it won't show up any more.\n */\n private class OkListener implements DialogInterface.OnClickListener {\n\n @Override\n public void onClick (DialogInterface ifc, int which)\n {\n PrefManager.setIgnoreButtonMessage(false);\n }\n }\n\n /**\n * The listener attached to the hw accel tip message.\n * When the user taps the ok button, we write on the property\n * that it has been acknowleged, so it won't show up any more.\n */\n private class AccelOkListener implements DialogInterface.OnClickListener {\n\n @Override\n public void onClick (DialogInterface ifc, int which)\n {\n PrefManager.setHWAccelMessage(false);\n }\n }\n\n /**\n * The listener that receives events from the mute buttons.\n */\n private class MuteListener implements View.OnClickListener {\n\n @Override\n public void onClick (View w)\n {\n PrefManager.toggleMute();\n applyMuteSettings ();\n }\n }\n\n /**\n * The listener that receives events from the single buttons.\n */\n private class SingleListener implements View.OnClickListener {\n\n @Override\n public void onClick (View w)\n {\n single = !single;\n applySingleSettings ();\n }\n }\n\n /**\n * Web view controller. This class is used by @link WebView to tell whether\n * a link should be opened inside of it, or an external browser needs to be invoked.\n * Currently, I will let all the pages inside the <code>/review</code> namespace\n * to be opened here. Theoretically, it could even be stricter, and use\n * <code>/review/session</code>, but that would be prevent the final summary\n * from being shown. That page is useful, albeit not as integrated with the app as\n * the other pages.\n */\n private class WebViewClientImpl extends WebViewClient {\n\n /**\n * Called to check whether a link should be opened in the view or not.\n * We also display the progress bar.\n * \t@param view the web view\n * @url the URL to be opened\n */\n @Override\n public boolean shouldOverrideUrlLoading (WebView view, String url)\n {\n Intent intent;\n\n if (shouldOpenExternal (url)) {\n intent = new Intent (Intent.ACTION_VIEW);\n intent.setData (Uri.parse (url));\n startActivity (intent);\n\n return true;\n }\n\n return false;\n }\n\n /**\n * Tells if we should spawn an external browser\n * @param url the url we are opening\n * \t@return true if we should\n */\n public boolean shouldOpenExternal (String url)\n {\n String curl;\n\n if (!url.contains (\"wanikani.com\") && !download)\n return true;\n\n curl = wv.getUrl ();\n if (curl == null)\n return false;\n\n\t \t/* Seems the only portable way to do this */\n if (curl.contains (\"www.wanikani.com/lesson\") ||\n curl.contains (\"www.wanikani.com/review\")) {\n\n // @Aralox added 'vocabulary' so that vocab examples in lessons can be opened externally.\n if (url.contains (\"/kanji/\") || url.contains (\"/radicals/\") || url.contains (\"/vocabulary/\"))\n return true;\n\n }\n\n return false;\n }\n\n /**\n * Called when something bad happens while accessing the resource.\n * Show the splash screen and give some explanation (based on the <code>description</code>\n * string).\n * \t@param view the web view\n * @param errorCode HTTP error code\n * @param description an error description\n * @param failingUrl error\n */\n public void onReceivedError (WebView view, int errorCode, String description, String failingUrl)\n {\n String s;\n\n s = getResources ().getString (R.string.fmt_web_review_error, description);\n splashScreen (s);\n bar.setVisibility (View.GONE);\n }\n\n @Override\n public void onPageStarted (WebView view, String url, Bitmap favicon)\n {\n bar.setVisibility (View.VISIBLE);\n keyboard.reset ();\n }\n\n /**\n * Called when a page finishes to be loaded. We hide the progress bar\n * and run the initialization javascript that shows the keyboard, if needed.\n * In addition, if this is the initial page, we check whether Viet has\n * deployed the client-side review system\n */\n @Override\n public void onPageFinished (WebView view, String url)\n {\n ExternalFramePlacer.Dictionary dict;\n\n bar.setVisibility (View.GONE);\n\n if (url.startsWith (\"http\")) {\n\n wv.js (JS_INIT_KBD);\n if (PrefManager.getExternalFramePlacer()) {\n dict = PrefManager.getExternalFramePlacerDictionary();\n ExternalFramePlacer.run (wv, dict);\n }\n\n if (PrefManager.getPartOfSpeech())\n PartOfSpeech.enter(WebReviewActivity.this, wv, url);\n }\n }\n }\n\n /**\n * An additional webclient, that receives a few callbacks that a simple\n * {@link WebChromeClient} does not intecept.\n */\n private class WebChromeClientImpl extends WebChromeClient {\n\n /**\n * Called as the download progresses. We update the progress bar.\n * @param view the web view\n * @param progress progress percentage\n */\n @Override\n public void onProgressChanged (WebView view, int progress)\n {\n bar.setProgress (progress);\n }\n };\n\n /**\n * A small job that hides, shows or iconizes the keyboard. We need to implement this\n * here because {@link WebReviewActivity.WKNKeyboard} gets called from a\n * javascript thread, which is not necessarily an UI thread.\n * The constructor simply calls <code>runOnUIThread</code> to make sure\n * we hide/show the views from the correct context.\n */\n private class ShowHideKeyboard implements Runnable {\n\n /** New state to enter */\n KeyboardStatus kbstatus;\n\n /**\n * Constructor. It also takes care to schedule the invokation\n * on the UI thread, so all you have to do is just to create an\n * instance of this object\n * @param kbstatus the new keyboard status to enter\n */\n ShowHideKeyboard (KeyboardStatus kbstatus)\n {\n this.kbstatus = kbstatus;\n\n runOnUiThread (this);\n }\n\n /**\n * Hides/shows the keyboard. Invoked by the UI thread.\n */\n public void run ()\n {\n kbstatus.apply (WebReviewActivity.this);\n if (kbstatus.isRelevantPage ())\n reviewsSession ();\n }\n\n private void reviewsSession ()\n {\n CookieSyncManager.getInstance ().sync ();\n }\n\n }\n\n /**\n * This class implements the <code>wknKeyboard</code> javascript object.\n * It implements the @link {@link #show} and {@link #hide} methods.\n */\n private class WKNKeyboard {\n\n /**\n * Called by javascript when the keyboard should be shown.\n */\n @JavascriptInterface\n public void show ()\n {\n new ShowHideKeyboard (KeyboardStatus.REVIEWS_MAXIMIZED);\n }\n\n /**\n * Called by javascript when the keyboard should be shown, using\n * new lessons layout.\n */\n @JavascriptInterface\n public void showLessonsNew ()\n {\n new ShowHideKeyboard (KeyboardStatus.LESSONS_MAXIMIZED_NEW);\n }\n\n /**\n * Called by javascript when the keyboard should be hidden.\n */\n @JavascriptInterface\n public void hide ()\n {\n new ShowHideKeyboard (KeyboardStatus.INVISIBLE);\n }\n }\n\n /**\n * Keyboard visiblity status.\n */\n enum KeyboardStatus {\n\n /** Keyboard visible, all keys visible */\n REVIEWS_MAXIMIZED {\n public void apply (WebReviewActivity wav) { wav.show (this); }\n\n public PrefManager.Keyboard getKeyboard (WebReviewActivity wav)\n {\n return PrefManager.getReviewsKeyboard();\n }\n\n public boolean canMute ()\n {\n return true;\n }\n\n public boolean canDoSingle ()\n {\n return true;\n }\n },\n\n /** Keyboard visible, all keys but ENTER visible */\n LESSONS_MAXIMIZED_NEW {\n public void apply (WebReviewActivity wav) { wav.show (this); }\n\n public PrefManager.Keyboard getKeyboard (WebReviewActivity wav)\n {\n return PrefManager.getReviewsKeyboard();\n }\n\n public boolean canMute ()\n {\n return true;\n }\n },\n\n /** Keyboard invisible */\n INVISIBLE {\n public void apply (WebReviewActivity wav) { wav.hide (this); }\n\n public boolean isRelevantPage () { return false; }\n\n public PrefManager.Keyboard getKeyboard (WebReviewActivity wav)\n {\n return PrefManager.Keyboard.NATIVE;\n }\n\n public boolean backIsSafe () { return true; }\n };\n\n public abstract void apply (WebReviewActivity wav);\n\n public void maximize (WebReviewActivity wav)\n {\n /* empty */\n }\n\n public boolean isIconized ()\n {\n return false;\n }\n\n public abstract PrefManager.Keyboard getKeyboard (WebReviewActivity wav);\n\n public boolean isRelevantPage ()\n {\n return true;\n }\n\n public boolean canMute ()\n {\n return false;\n }\n\n public boolean canDoSingle ()\n {\n return false;\n }\n\n public boolean hasEnter (WebReviewActivity wav)\n {\n return false;\n }\n\n public boolean backIsSafe ()\n {\n return false;\n }\n };\n\n private class ReaperTaskListener implements TimerThreadsReaper.ReaperTaskListener {\n\n public void reaped (int count, int total)\n {\n\t\t\t/* Here we could keep some stats. Currently unused */\n }\n }\n\n private class IgnoreButtonListener implements View.OnClickListener {\n\n @Override\n public void onClick (View view)\n {\n ignore ();\n }\n\n }\n\n private class FileDownloader implements DownloadListener, FileDownloadTask.Listener {\n\n FileDownloadTask fdt;\n\n @Override\n public void onDownloadStart (String url, String userAgent, String contentDisposition,\n String mimetype, long contentLength)\n {\n dbar.setVisibility (View.VISIBLE);\n cancel ();\n fdt = new FileDownloadTask (WebReviewActivity.this, downloadPrefix, this);\n fdt.execute (url);\n }\n\n private void cancel ()\n {\n if (fdt != null)\n fdt.cancel ();\n }\n\n @Override\n public void setProgress (int percentage)\n {\n dbar.setProgress (percentage);\n }\n\n @Override\n public void done (File file)\n {\n Intent results;\n\n dbar.setVisibility (View.GONE);\n if (file != null) {\n results = new Intent ();\n results.putExtra (EXTRA_FILENAME, file.getAbsolutePath ());\n setResult (RESULT_OK, results);\n finish ();\n } else\n Toast.makeText (WebReviewActivity.this, getString (R.string.tag_download_failed),\n Toast.LENGTH_LONG).show ();\n }\n }\n\n /** The web view, where the web contents are rendered */\n FocusWebView wv;\n\n /** The view containing a splash screen. Visible when we want to display\n * some message to the user */\n View splashView;\n\n /**\n * The view contaning the ordinary content.\n */\n View contentView;\n\n /** A textview in the splash screen, where we can display some message */\n TextView msgw;\n\n /** The web progress bar */\n ProgressBar bar;\n\n /** The web download progress bar */\n ProgressBar dbar;\n\n /// Selected button color\n int selectedColor;\n\n /// Unselected button color\n int unselectedColor;\n\n /** The local prefix of this class */\n private static final String PREFIX = \"com.wanikani.androidnotifier.WebReviewActivity.\";\n\n /** Open action, invoked to start this action */\n public static final String OPEN_ACTION = PREFIX + \"OPEN\";\n\n /** Download action, invoked to download a file */\n public static final String DOWNLOAD_ACTION = PREFIX + \"DOWNLOAD\";\n\n public static final String EXTRA_DOWNLOAD_PREFIX = PREFIX + \"download_prefix\";\n\n public static final String EXTRA_FILENAME = PREFIX + \"filename\";\n\n /** Flush caches bundle key */\n private static final String KEY_FLUSH_CACHES = PREFIX + \"flushCaches\";\n\n /** Local preferences file. Need it because we access preferences from another file */\n private static final String PREFERENCES_FILE = \"webview.xml\";\n\n /** Javascript to be called each time an HTML page is loaded. It hides or shows the keyboard */\n private static final String JS_INIT_KBD =\n \"var textbox, lessobj, ltextbox, reviews, style;\" +\n \"textbox = document.getElementById (\\\"\" + WKConfig.ANSWER_BOX + \"\\\"); \" +\n \"reviews = document.getElementById (\\\"\" + WKConfig.REVIEWS_DIV + \"\\\");\" +\n \"quiz = document.getElementById (\\\"\" + WKConfig.QUIZ + \"\\\");\" +\n \"quiz_button = document.getElementById (\\\"\" + WKConfig.QUIZ_BUTTON1 + \"\\\");\" +\n \"function reload_quiz_arrow() { quiz_arrow = document.getElementsByClassName (\\\"\" + WKConfig.QUIZ_BUTTON2 + \"\\\")[0]; }; \" +\n\n\n// \"document.onclick = function(e) { \\n\" +\n// \" console.log('clicked: '+e.target.outerHTML);\" +\n// \"};\" +\n\n\n // Section added by @Aralox, to show the 'character' (kanji/radical/vocab under review) with a hyperlink\n // when the item-info panel is open, and to show a non-hyperlinked version when the panel is closed.\n // Events are hooked onto the item info panel button, and the new question event (see getHideLinkCode())\n \"var character_div, character_unlinked, character_linked, item_info_div, item_info_button;\" +\n \"character_div = $('#\"+WKConfig.CHARACTER_DIV +\"');\" +\n \"item_info_div = $('#\" + WKConfig.ITEM_INFO_DIV + \"');\" +\n \"item_info_button = $('#\" + WKConfig.ITEM_INFO_LI + \"');\" +\n\n \"function item_info_listener() {\" +\n \" if (item_info_div.css('display') == 'block' && !item_info_button.hasClass('disabled')) {\" +\n //\" console.log('clicked open item info panel.');\" +\n \" character_unlinked.css('display', 'none');\" +\n \" character_linked.css ('display', 'block');\" +\n \" } else {\" +\n //\" console.log('clicked close item info panel.');\" +\n \" character_unlinked.css('display', 'block');\" +\n \" character_linked.css ('display', 'none');\" +\n \" } \" +\n\n// // Added by @Aralox, use these lines to print the page HTML, for debugging.\n// \" console.log('document (panel): ');\" +\n// \" doclines = $('body').html().split('\\\\n');\" +\n// \" for (var di = 0; di < doclines.length; di++) { console.log(doclines[di]); }; \" +\n// //\" console.log('items actual href: ' + $('#\"+WKConfig.CHARACTER_DIV +\">a').attr(\\\"href\\\"));\" +\n\n \"};\" +\n\n \"if (quiz != null) {\" +\n \" wknKeyboard.showLessonsNew ();\" +\n \" quiz_button.addEventListener(\\\"click\\\", function(){ wknKeyboard.showLessonsNew (); });\" +\n \" var interval = setInterval(function() { reload_quiz_arrow(); if (quiz_arrow != undefined) { quiz_arrow.addEventListener(\\\"click\\\", function() { wknKeyboard.showLessonsNew (); }); clearInterval(interval); } }, 200); \" +\n \"} else if (textbox != null && !textbox.disabled) {\" +\n // Code for reviews (not lessons) happen in here\n \" wknKeyboard.show (); \" +\n\n // Code added for hyperlinking, as mentioned above. @Aralox\n \" item_info_button.on('click', item_info_listener);\" +\n\n \" $('\"+WKConfig.CHARACTER_SPAN_JQ +\"').clone().appendTo(character_div);\" + //\" character_div.append($('\"+WKConfig.CHARACTER_SPAN_JQ +\"').clone());\" +\n \" $('#\"+WKConfig.CHARACTER_DIV +\">span').first().wrap('<a href=\\\"\\\" \" +\n \"style=\\\"text-decoration:none;color:inherit\\\"></a>');\" +\n //\"style=\\\"text-decoration:none;\\\"></a>');\" + // to show blue hyperlinks\n\n \" character_linked = $('#\"+WKConfig.CHARACTER_DIV+\">a>span');\" +\n \" character_unlinked = $('\"+WKConfig.CHARACTER_SPAN_JQ +\"');\" +\n\n // Just some rough working to figure out how to sort out item longpress.\n //\" character_unlinked.attr('id', 'itemlink');\" +\n //\" character_unlinked.on('click', function(){ selectText('itemlink');});\" + // change to longpress event\n //\" character_unlinked.on('click', function(){ wknKeyboard.selectText();});\" +\n\n \"} else {\" +\n \"\twknKeyboard.hide ();\" +\n \"}\" +\n \"if (reviews != null) {\" +\n \" reviews.style.overflow = \\\"visible\\\";\" +\n \"}\" +\n \"window.trueRandom = Math.random;\" +\n \"window.fakeRandom = function() { return 0; };\" + // @Ikalou's fix\n\t\t\t/* This fixes a bug that makes SRS indication slow */\n \"style = document.createElement('style');\" +\n \"style.type = 'text/css';\" +\n \"style.innerHTML = '.animated { -webkit-animation-duration:0s; }';\" +\n \"document.getElementsByTagName('head')[0].appendChild(style);\";\n\n // Added by @Aralox to hook link hiding onto new question event in LocalIMEKeyboard.JS_INIT_TRIGGERS. Done in similar style as WaniKaniImprove.getCode().\n // Note that this event also happens when you tab back into the program e.g. after using your browser.\n public static String getHideLinkCode()\n {\n return LocalIMEKeyboard.ifReviews(\n // Update the hyperlink appropriately.\n \"character_div = $('#\"+WKConfig.CHARACTER_DIV+\"');\" +\n \"character_linked_a = character_div.find('a');\" +\n \"character_linked = character_linked_a.find('span');\" +\n\n \"curItem = $.jStorage.get('currentItem');\" +\n \"console.log('curItem: '+JSON.stringify(curItem));\" +\n\n // Link is obtained similarly to Browser.java\n \"itemLink = ' ';\" + // used in the hyperlink\n \"switch (character_div.attr('class')) {\" +\n \" case 'vocabulary':\" +\n \" itemLink = '/vocabulary/' + encodeURI(character_linked.text());\" +\n \" break;\" +\n \" case 'kanji':\" +\n \" itemLink = '/kanji/' + encodeURI(character_linked.text());\" +\n \" break;\" +\n \" case 'radical':\" +\n \" itemLink = '/radicals/' + String(curItem.en).toLowerCase();\" +\n \" break;\" +\n \"};\" +\n\n \"newHref = itemLink;\" + // 'https://www.wanikani.com' doesnt seem to be necessary\n\n \"console.log('new href: ' + newHref);\" +\n\n \"character_linked_a.attr('href', newHref);\" +\n\n // We need this because the user will often progress to the next question without clicking\n // on the item info panel button to close it, so the button listener which hides the linked element will not be called.\n // Since this event also fires on tab-back-in, we check to see if item-info panel is open before hiding hyperlink.\n \"item_info_div = $('#\" + WKConfig.ITEM_INFO_DIV + \"');\" +\n \"item_info_button = $('#\" + WKConfig.ITEM_INFO_LI + \"');\" +\n // same condition used in item_info_listener() above\n \"if (item_info_div.css('display') == 'block' && !item_info_button.hasClass('disabled')) {\" +\n \" console.log('Tabbed back in (item info panel open). Dont hide hyperlink.');\" +\n \"} else {\" +\n \" character_div.find('span').css('display', 'block');\" + // (character_unlinked)\n \" character_linked.css('display', 'none');\" +\n \"}\"\n\n// // Added by @Aralox, use these lines to print the page HTML, for debugging.\n// +\" console.log('document (next q): ');\" +\n// \" doclines = $('body').html().split('\\\\n');\" +\n// \" for (var di = 0; di < doclines.length; di++) { console.log(doclines[di]); }; \"\n );\n }\n\n // @Aralox added lines to help with debugging issue #27. Solution is in LocalIMEKeyboard.replace().\n // Run this through an unminifier to understand it better. Based on @jneapan's code\n //\"var note_meaning_textarea;\" +\n //\"function reload_note_elements() { note_meaning = document.getElementsByClassName (\\\"note-meaning\\\")[0]; }; \" +\n //\"function note_meaning_listener() { console.log('note meaning div listener'); setTimeout(function(){note_meaning_textarea = $('div.note-meaning>form>fieldset>textarea')[0]; console.log('textarea: '+note_meaning_textarea); \"+\n //\"note_meaning_textarea.addEventListener('click', note_meaning_textarea_listener); }, 1000); };\" +\n //\"function note_meaning_textarea_listener() {console.log('clicked textarea'); setTimeout(function(){console.log('refocusing on textarea: ' + note_meaning_textarea); \"+\n //\"wknKeyboard.show(); note_meaning_textarea.focus(); }, 1000);};\" +\n\n private static final String\n JS_BULK_MODE = \"if (window.trueRandom) Math.random=window.trueRandom;\";\n private static final String\n JS_SINGLE_MODE = \"if (window.fakeRandom) Math.random=window.fakeRandom;\";\n\n /** The threads reaper */\n TimerThreadsReaper reaper;\n\n /** Thread reaper task */\n TimerThreadsReaper.ReaperTask rtask;\n\n /** The current keyboard status */\n protected KeyboardStatus kbstatus;\n\n /** The mute drawable */\n private Drawable muteDrawable;\n\n /** The sound drawable */\n private Drawable notMutedDrawable;\n\n /** The ignore button */\n private Button ignbtn;\n\n /** Set if visible */\n public boolean visible;\n\n /** Is mute enabled */\n private boolean isMuted;\n\n /** The current keyboard */\n private Keyboard keyboard;\n\n /** The native keyboard */\n private Keyboard nativeKeyboard;\n\n /** The local IME keyboard */\n private Keyboard localIMEKeyboard;\n\n private CardView muteHolder;\n private CardView singleHolder;\n\n /** The mute button */\n private ImageButton muteH;\n\n /** The single button */\n private Button singleb;\n\n /** Single mode is on? */\n private boolean single = false;\n\n /** Shall we download a file? */\n private boolean download;\n\n /** Download prefix */\n private String downloadPrefix;\n\n /** The file downloader, if any */\n private FileDownloader fda;\n\n ActionBar mActionBar;\n\n /**\n * Called when the action is initially displayed. It initializes the objects\n * and starts loading the review page.\n * \t@param bundle the saved bundle\n */\n @Override\n public void onCreate (Bundle bundle)\n {\n super.onCreate (bundle);\n\n Resources res;\n\n CookieSyncManager.createInstance (this);\n setVolumeControlStream (AudioManager.STREAM_MUSIC);\n\n setContentView (R.layout.activity_web_view);\n\n Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(mToolbar);\n\n mActionBar = getSupportActionBar();\n mActionBar.setDisplayHomeAsUpEnabled(true);\n\n if (PrefManager.getReviewsLessonsFullscreen()) {\n mActionBar.hide();\n }\n\n String intentData = getIntent().getData().toString();\n if (intentData.contains(\"review\"))\n mActionBar.setTitle(getString(R.string.ab_title_reviews));\n else if (intentData.contains(\"lesson\"))\n mActionBar.setTitle(getString(R.string.ab_title_lessons));\n\n res = getResources ();\n\n selectedColor = res.getColor (R.color.apptheme_main);\n unselectedColor = res.getColor (R.color.text_gray_light);\n\n muteDrawable = res.getDrawable(R.drawable.ic_volume_off_black_24dp);\n notMutedDrawable = res.getDrawable(R.drawable.ic_volume_up_black_24dp);\n\n kbstatus = KeyboardStatus.INVISIBLE;\n\n bar = (ProgressBar) findViewById (R.id.pb_reviews);\n dbar = (ProgressBar) findViewById (R.id.pb_download);\n\n ignbtn = (Button) findViewById (R.id.btn_ignore);\n ignbtn.setOnClickListener (new IgnoreButtonListener ());\n\n\t\t/* First of all get references to views we'll need in the near future */\n splashView = findViewById (R.id.wv_splash);\n contentView = findViewById (R.id.wv_content);\n msgw = (TextView) findViewById (R.id.tv_message);\n wv = (FocusWebView) findViewById (R.id.wv_reviews);\n\n wv.getSettings ().setJavaScriptEnabled (true);\n wv.getSettings().setJavaScriptCanOpenWindowsAutomatically (true);\n wv.getSettings ().setSupportMultipleWindows (false);\n wv.getSettings ().setUseWideViewPort (false);\n wv.getSettings ().setDatabaseEnabled (true);\n wv.getSettings ().setDomStorageEnabled (true);\n wv.getSettings ().setDatabasePath (getFilesDir ().getPath () + \"/wv\");\n if (Build.VERSION.SDK_INT >= 17) {\n wv.getSettings().setMediaPlaybackRequiresUserGesture(false);\n }\n\n wv.addJavascriptInterface (new WKNKeyboard (), \"wknKeyboard\");\n wv.setScrollBarStyle (ScrollView.SCROLLBARS_OUTSIDE_OVERLAY);\n wv.setWebViewClient (new WebViewClientImpl ());\n wv.setWebChromeClient (new WebChromeClientImpl ());\n\n download = getIntent ().getAction ().equals (DOWNLOAD_ACTION);\n if (download) {\n downloadPrefix = getIntent ().getStringExtra (EXTRA_DOWNLOAD_PREFIX);\n wv.setDownloadListener (fda = new FileDownloader ());\n }\n\n wv.loadUrl (getIntent ().getData ().toString ());\n\n nativeKeyboard = new NativeKeyboard(this, wv);\n localIMEKeyboard = new LocalIMEKeyboard(this, wv);\n\n muteHolder = (CardView) findViewById(R.id.kb_mute_holder);\n singleHolder = (CardView) findViewById(R.id.kb_single_holder);\n\n muteH = (ImageButton) findViewById (R.id.kb_mute_h);\n muteH.setOnClickListener (new MuteListener ());\n\n singleb = (Button) findViewById (R.id.kb_single);\n singleb.setOnClickListener (new SingleListener ());\n\n reaper = new TimerThreadsReaper ();\n rtask = reaper.createTask (new Handler (), 2, 7000);\n rtask.setListener (new ReaperTaskListener ());\n\n // Added by @Aralox to keep the screen awake during reviews. Technique from http://stackoverflow.com/questions/8442079/keep-the-screen-awake-throughout-my-activity\n // TODO: Make this an option in the app's settings.\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n }\n\n @Override\n public void onNewIntent (Intent intent)\n {\n String curl, nurl;\n\n super.onNewIntent (intent);\n curl = wv.getOriginalUrl ();\n nurl = intent.getData ().toString ();\n if (curl == null || !curl.equals (nurl))\n wv.loadUrl (nurl);\n }\n\n @Override\n protected void onResume ()\n {\n// Window window;\n super.onResume ();\n/*\n These features won't be implemented as of now\n\n window = getWindow ();\n if (SettingsActivity.getLockScreen (this))\n window.addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n else\n window.clearFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n\n if (SettingsActivity.getResizeWebview (this))\n window.setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);\n else\n window.setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);\n*/\n\n visible = true;\n\n selectKeyboard ();\n\n applyMuteSettings ();\n applySingleSettings ();\n\n if (PrefManager.getHWAccel())\n showHWAccelMessage();\n\n wv.acquire ();\n\n kbstatus.apply (this);\n\n if (rtask != null)\n rtask.resume ();\n }\n\n @Override\n public void onDestroy ()\n {\n super.onDestroy ();\n\n if (reaper != null)\n reaper.stopAll ();\n\n if (fda != null)\n fda.cancel ();\n\n System.exit (0);\n }\n\n @Override\n protected void onSaveInstanceState (Bundle bundle)\n {\n /* empty */\n }\n\n @Override\n protected void onRestoreInstanceState (Bundle bundle)\n {\n /* empty */\n }\n\n @Override\n protected void onPause ()\n {\n visible = false;\n\n super.onPause();\n\n setMute (false);\n\n wv.release ();\n\n if (rtask != null)\n rtask.pause ();\n\n keyboard.hide ();\n }\n\n /**\n * Tells if calling {@link WebView#goBack()} is safe. On some WK pages we should not use it.\n * @return <tt>true</tt> if it is safe.\n */\n protected boolean backIsSafe ()\n {\n String lpage, rpage, url;\n\n url = wv.getUrl ();\n lpage = \"www.wanikani.com/lesson\";\n rpage = \"www.wanikani.com/review\";\n\n return kbstatus.backIsSafe () &&\n\t\t\t\t/* Need this because the reviews summary page is dangerous */\n !(url.contains (rpage) || rpage.contains (url)) &&\n !(url.contains (lpage) || lpage.contains (url));\n }\n\n @Override\n public boolean onSupportNavigateUp() {\n super.onBackPressed();\n return true;\n }\n\n @Override\n public void onBackPressed ()\n {\n String url;\n\n url = wv.getUrl ();\n\n if (url == null)\n super.onBackPressed ();\n else if (url.contains (\"http://www.wanikani.com/quickview\"))\n wv.loadUrl (Browser.LESSON_URL);\n else if (wv.canGoBack () && backIsSafe ())\n wv.goBack ();\n else {\n // Dialog box added by Aralox, based on http://stackoverflow.com/a/9901871/1072869\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setMessage(\"Are you sure you want to exit?\")\n .setCancelable(false)\n .setPositiveButton(\"Yes\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n WebReviewActivity.super.onBackPressed();\n }\n })\n .setNegativeButton(\"No\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.cancel();\n }\n });\n AlertDialog alert = builder.create();\n alert.show();\n }\n }\n\n protected void selectKeyboard ()\n {\n Keyboard oldk;\n\n oldk = keyboard;\n\n switch (kbstatus.getKeyboard (this)) {\n case LOCAL_IME:\n keyboard = localIMEKeyboard;\n break;\n\n case NATIVE:\n keyboard = nativeKeyboard;\n break;\n }\n\n if (keyboard != oldk && oldk != null)\n oldk.hide ();\n\n updateCanIgnore ();\n }\n\n private void applyMuteSettings ()\n {\n boolean show;\n\n show = kbstatus.canMute () && PrefManager.getMuteButton();\n muteH.setVisibility (show ? View.VISIBLE : View.GONE);\n muteHolder.setVisibility(show ? View.VISIBLE : View.GONE);\n\n setMute (show && PrefManager.getMute());\n }\n\n private void applySingleSettings ()\n {\n boolean show;\n\n show = kbstatus.canDoSingle () && PrefManager.getSingleButton();\n singleb.setVisibility (show ? View.VISIBLE : View.GONE);\n singleHolder.setVisibility(show ? View.VISIBLE : View.GONE);\n if (single) {\n singleb.setTextColor (selectedColor);\n singleb.setTypeface (null, Typeface.BOLD);\n wv.js (JS_SINGLE_MODE);\n } else {\n singleb.setTextColor (unselectedColor);\n singleb.setTypeface (null, Typeface.NORMAL);\n wv.js (JS_BULK_MODE);\n }\n }\n\n private void setMute (boolean m)\n {\n Drawable d;\n\n d = m ? muteDrawable : notMutedDrawable;\n muteH.setImageDrawable (d);\n\n if (isMuted != m && keyboard != null) {\n keyboard.setMute (m);\n isMuted = m;\n }\n }\n\n /**\n * Displays the splash screen, also providing a text message\n * @param msg the text message to display\n */\n protected void splashScreen (String msg)\n {\n msgw.setText (msg);\n contentView.setVisibility (View.GONE);\n splashView.setVisibility (View.VISIBLE);\n }\n\n /**\n * Hides the keyboard\n * @param kbstatus the new keyboard status\n */\n protected void hide (KeyboardStatus kbstatus)\n {\n this.kbstatus = kbstatus;\n\n applyMuteSettings ();\n applySingleSettings ();\n\n keyboard.hide ();\n }\n\n protected void show (KeyboardStatus kbstatus)\n {\n this.kbstatus = kbstatus;\n\n selectKeyboard ();\n\n applyMuteSettings ();\n applySingleSettings ();\n\n keyboard.show (kbstatus.hasEnter (this));\n }\n\n protected void iconize (KeyboardStatus kbs)\n {\n kbstatus = kbs;\n\n selectKeyboard ();\n\n applyMuteSettings ();\n applySingleSettings ();\n\n keyboard.iconize (kbstatus.hasEnter (this));\n }\n\n public void updateCanIgnore ()\n {\n ignbtn.setVisibility (keyboard.canIgnore () ? View.VISIBLE : View.GONE);\n }\n\n /**\n * Ignore button\n */\n public void ignore ()\n {\n showIgnoreButtonMessage ();\n keyboard.ignore ();\n }\n\n protected void showIgnoreButtonMessage ()\n {\n AlertDialog.Builder builder;\n Dialog dialog;\n\n if (visible && PrefManager.getIgnoreButtonMessage()) {\n builder = new AlertDialog.Builder(this);\n builder.setTitle(R.string.ignore_button_message_title);\n builder.setMessage(R.string.ignore_button_message_text);\n builder.setPositiveButton(R.string.ignore_button_message_ok, new OkListener());\n\n dialog = builder.create();\n PrefManager.setIgnoreButtonMessage(false);\n\n dialog.show();\n }\n }\n\n protected void showHWAccelMessage ()\n {\n AlertDialog.Builder builder;\n Dialog dialog;\n\n if (PrefManager.getHWAccelMessage()) {\n builder = new AlertDialog.Builder(this);\n builder.setTitle(R.string.hw_accel_message_title);\n builder.setMessage(R.string.hw_accel_message_text);\n builder.setPositiveButton(R.string.ok, new AccelOkListener());\n\n dialog = builder.create();\n PrefManager.setHWAccelMessage(false);\n\n dialog.show();\n }\n }\n}", "public class WaniKaniItem {\n\n public enum Type {\n\n RADICAL,\n KANJI,\n VOCABULARY;\n\n public static Type fromString(String type) {\n if (type.equals(\"radical\"))\n return RADICAL;\n else if (type.equals(\"kanji\"))\n return KANJI;\n else if (type.equals(\"vocabulary\"))\n return VOCABULARY;\n\n return null;\n }\n }\n}", "@SuppressLint(\"CommitPrefEdits\")\npublic abstract class PrefManager {\n public static final String PREF_API_KEY = \"pref_api_key\";\n private static final String PREF_DASHBOARD_RECENT_UNLOCKS_NUMBER = \"pref_dashboard_recent_unlock_number\";\n private static final String PREF_DASHBOARD_CRITICAL_ITEMS_PERCENTAGE = \"pref_dashboard_critical_items_percentage\";\n private static final String PREF_CRITICAL_ITEMS_NUMBER = \"pref_critical_items_number\";\n private static final String PREF_USE_CUSTOM_FONTS = \"pref_use_custom_fonts\";\n private static final String PREF_USE_SPECIFIC_DATES = \"pref_use_specific_dates\";\n private static final String PREF_REVIEWS_IMPROVEMENTS = \"pref_reviews_improvements\";\n private static final String PREF_IGNORE_BUTTON = \"pref_ignore_button\";\n private static final String PREF_SINGLE_BUTTON = \"pref_single_button\";\n private static final String PREF_PORTRAIT_MODE = \"pref_portrait_mode\";\n private static final String PREF_WANIKANI_IMPROVE = \"pref_wanikani_improve\";\n private static final String PREF_REVIEW_ORDER = \"pref_review_order\";\n private static final String PREF_LESSON_ORDER = \"pref_lesson_order\";\n private static final String PREF_EXTERNAL_FRAME_PLACER = \"pref_eternal_frame_placer\";\n private static final String PREF_EXTERNAL_FRAME_PLACER_DICTIONARY = \"pref_external_frame_placer_dictionary\";\n private static final String PREF_PART_OF_SPEECH = \"pref_part_of_speech\";\n private static final String PREF_AUTO_POPUP = \"pref_auto_popup\";\n private static final String PREF_MISTAKE_DELAY = \"pref_mistake_delay\";\n private static final String PREF_ROMAJI = \"pref_romaji\";\n private static final String PREF_NO_SUGGESTION = \"pref_no_suggestions\";\n private static final String PREF_MUTE_BUTTON = \"pref_mute_button\";\n private static final String PREF_SRS_INDCATION = \"pref_srs_indication\";\n private static final String PREF_IGNORE_BUTTON_MESSAGE = \"pref_ignore_button_message\";\n private static final String PREF_HW_ACCEL_MESSAGE = \"pref_hw_accel_message\";\n private static final String PREF_MUTE = \"pref_mute\";\n private static final String PREF_HW_ACCEL = \"pref_hw_accel\";\n private static final String PREF_REVIEWS_LESSONS_FULLSCREEN = \"pref_rev_les_fullscreen\";\n private static final String PREF_SHOW_NOTIFICATIONS = \"pref_show_notifications\";\n private static final String PREF_ENABLE_REMINDER_NOTIFICATION = \"pref_enable_reminder_notification\";\n private static final String PREF_REMINDER_NOTIFICATION_INTERVAL = \"pref_reminder_notification_interval\";\n\n private static SharedPreferences prefs;\n private static SharedPreferences reviewsPrefs;\n\n public static void init(Context context) {\n prefs = PreferenceManager.getDefaultSharedPreferences(context);\n reviewsPrefs = context.getSharedPreferences(\"review-lessons_prefs\", Context.MODE_PRIVATE);\n }\n\n public static String getApiKey() {\n return prefs.getString(\"api_key\", \"0\");\n }\n\n public static void setApiKey(String key) {\n prefs.edit().putString(\"api_key\", key).commit();\n }\n\n public static boolean isFirstLaunch() {\n return prefs.getBoolean(\"first_launch\", true);\n }\n\n public static void setFirstLaunch(boolean value) {\n prefs.edit().putBoolean(\"first_launch\", value).commit();\n }\n\n public static boolean isProfileFirstTime() {\n return prefs.getBoolean(\"first_time_profile\", true);\n }\n\n public static void setProfileFirstTime(boolean value) {\n prefs.edit().putBoolean(\"first_time_profile\", value).commit();\n }\n\n public static int getDashboardRecentUnlocksNumber() {\n return prefs.getInt(PREF_DASHBOARD_RECENT_UNLOCKS_NUMBER, 5);\n }\n\n public static void setDashboardRecentUnlocksNumber(int number) {\n prefs.edit().putInt(PREF_DASHBOARD_RECENT_UNLOCKS_NUMBER, number).commit();\n }\n\n public static int getDashboardCriticalItemsPercentage() {\n return prefs.getInt(PREF_DASHBOARD_CRITICAL_ITEMS_PERCENTAGE, 75);\n }\n\n public static void setDashboardCriticalItemsPercentage(int number) {\n prefs.edit().putInt(PREF_DASHBOARD_CRITICAL_ITEMS_PERCENTAGE, number).commit();\n }\n\n public static int getCriticalItemsNumber() {\n return prefs.getInt(PREF_CRITICAL_ITEMS_NUMBER, 5);\n }\n\n public static void setCriticalItemsNumber(int value) {\n prefs.edit().putInt(PREF_CRITICAL_ITEMS_NUMBER, value).commit();\n }\n\n public static boolean isLegendLearned() {\n return prefs.getBoolean(\"pref_legend_learned\", false);\n }\n\n public static void setLegendLearned(boolean value) {\n prefs.edit().putBoolean(\"pref_legend_learned\", value).commit();\n }\n\n public static void setDashboardLastUpdateDate(long date) {\n prefs.edit().putLong(\"pref_update_date_dashboard\", date).commit();\n }\n\n public static long getDashboardLastUpdateTime() {\n return prefs.getLong(\"pref_update_date_dashboard\", 0);\n }\n\n public static boolean isUseCustomFonts() {\n return prefs.getBoolean(PREF_USE_CUSTOM_FONTS, true);\n }\n\n public static void setUseCUstomFonts(boolean value) {\n prefs.edit().putBoolean(PREF_USE_CUSTOM_FONTS, value).commit();\n }\n\n public static boolean isUseSpecificDates() {\n return prefs.getBoolean(PREF_USE_SPECIFIC_DATES, false);\n }\n\n public static void setUseSpecificDates(boolean value) {\n prefs.edit().putBoolean(PREF_USE_SPECIFIC_DATES, value).commit();\n }\n\n public static boolean getReviewsImprovements() {\n return prefs.getBoolean(PREF_REVIEWS_IMPROVEMENTS, true);\n }\n\n public static void setReviewsImprovements(boolean value) {\n prefs.edit().putBoolean(PREF_REVIEWS_IMPROVEMENTS, value).commit();\n }\n\n public static boolean getIgnoreButton() {\n return prefs.getBoolean(PREF_IGNORE_BUTTON, true);\n }\n\n public static void setIgnoreButton(boolean value) {\n prefs.edit().putBoolean(PREF_IGNORE_BUTTON, value).commit();\n }\n\n public static boolean getSingleButton() {\n return prefs.getBoolean(PREF_SINGLE_BUTTON, true);\n }\n\n public static void setSingleButton(boolean value) {\n prefs.edit().putBoolean(PREF_SINGLE_BUTTON, value).commit();\n }\n\n public static boolean getPortraitMode() {\n return prefs.getBoolean(PREF_PORTRAIT_MODE, true);\n }\n\n public static void setPortraitMode(boolean value) {\n prefs.edit().putBoolean(PREF_PORTRAIT_MODE, value).commit();\n }\n\n public static boolean getWaniKaniImprove() {\n return prefs.getBoolean(PREF_WANIKANI_IMPROVE, false);\n }\n\n public static void setWaniKaniImprove(boolean value) {\n prefs.edit().putBoolean(PREF_WANIKANI_IMPROVE, value).commit();\n }\n\n public static boolean getReviewOrder() {\n return prefs.getBoolean(PREF_REVIEW_ORDER, false);\n }\n\n public static void setReviewOrder(boolean value) {\n prefs.edit().putBoolean(PREF_REVIEW_ORDER, value).commit();\n }\n\n public static boolean getLessonOrder() {\n return prefs.getBoolean(PREF_LESSON_ORDER, false);\n }\n\n public static void setLessonOrder(boolean value) {\n prefs.edit().putBoolean(PREF_LESSON_ORDER, value).commit();\n }\n\n public static boolean getExternalFramePlacer() {\n return prefs.getBoolean(PREF_EXTERNAL_FRAME_PLACER, false);\n }\n\n public static void setExternalFramePlacer(boolean value) {\n prefs.edit().putBoolean(PREF_EXTERNAL_FRAME_PLACER, value).commit();\n }\n\n public static ExternalFramePlacer.Dictionary getExternalFramePlacerDictionary() {\n ExternalFramePlacer.Dictionary dict;\n String tag = prefs.getString(PREF_EXTERNAL_FRAME_PLACER_DICTIONARY,\n ExternalFramePlacer.Dictionary.JISHO.name());\n dict = ExternalFramePlacer.Dictionary.valueOf(tag);\n dict = ExternalFramePlacer.Dictionary.JISHO;\n return dict;\n }\n\n public static void setExternalFramePlacerDictionary(String value) {\n prefs.edit().putString(PREF_EXTERNAL_FRAME_PLACER_DICTIONARY, value).commit();\n }\n\n public static boolean getPartOfSpeech() {\n return prefs.getBoolean(PREF_PART_OF_SPEECH, false); // TODO - Make true after integration\n }\n\n public static void setPartOfSpeech(boolean value) {\n prefs.edit().putBoolean(PREF_PART_OF_SPEECH, value).commit();\n }\n\n public static boolean getAutoPopup() {\n return prefs.getBoolean(PREF_AUTO_POPUP, false);\n }\n\n public static void setAutoPopup(boolean value) {\n prefs.edit().putBoolean(PREF_AUTO_POPUP, value).commit();\n }\n\n public static boolean getMistakeDelay() {\n return prefs.getBoolean(PREF_MISTAKE_DELAY, false);\n }\n\n public static void setMistakeDelay(boolean value) {\n prefs.edit().putBoolean(PREF_MISTAKE_DELAY, value).commit();\n }\n\n public static boolean getRomaji() {\n return prefs.getBoolean(PREF_ROMAJI, false);\n }\n\n public static void setRomaji(boolean value) {\n prefs.edit().putBoolean(PREF_ROMAJI, value).commit();\n }\n\n public static boolean getNoSuggestion() {\n return prefs.getBoolean(PREF_NO_SUGGESTION, true);\n }\n\n public static void setNoSuggestion(boolean value) {\n prefs.edit().putBoolean(PREF_NO_SUGGESTION, value).commit();\n }\n\n public static boolean getMuteButton() {\n return prefs.getBoolean(PREF_MUTE_BUTTON, true);\n }\n\n public static void setMuteButton(boolean value) {\n prefs.edit().putBoolean(PREF_MUTE_BUTTON, value).commit();\n }\n\n public static boolean getSRSIndication() {\n return prefs.getBoolean(PREF_SRS_INDCATION, true);\n }\n\n public static void setSRSIndication(boolean value) {\n prefs.edit().putBoolean(PREF_SRS_INDCATION, value).commit();\n }\n\n public static Keyboard getReviewsKeyboard() {\n return getReviewsImprovements() ? Keyboard.LOCAL_IME : Keyboard.NATIVE;\n }\n\n public static Intent getWebViewIntent(Context context) {\n boolean accel = getHWAccel();\n return new Intent(context, accel ? WebReviewActivity.class : SWWebReviewActivity.class);\n }\n\n public static boolean getIgnoreButtonMessage() {\n return reviewsPrefs.getBoolean(PREF_IGNORE_BUTTON_MESSAGE, true);\n }\n\n public static void setIgnoreButtonMessage(boolean value) {\n reviewsPrefs.edit().putBoolean(PREF_IGNORE_BUTTON_MESSAGE, value).commit();\n }\n\n public static boolean getHWAccelMessage() {\n return reviewsPrefs.getBoolean(PREF_HW_ACCEL_MESSAGE, true);\n }\n\n public static void setHWAccelMessage(boolean value) {\n reviewsPrefs.edit().putBoolean(PREF_HW_ACCEL_MESSAGE, value).commit();\n }\n\n public static boolean getHWAccel() {\n return prefs.getBoolean(PREF_HW_ACCEL, true);\n }\n\n public static void setHWAccel(boolean value) {\n prefs.edit().putBoolean(PREF_HW_ACCEL, value).commit();\n }\n\n public static boolean toggleMute() {\n boolean mute = !getMute();\n setMute(mute);\n return mute;\n }\n\n public static boolean getMute() {\n return prefs.getBoolean(PREF_MUTE, false);\n }\n\n public static void setMute(boolean value) {\n prefs.edit().putBoolean(PREF_MUTE, value).commit();\n }\n\n public static boolean getReviewsLessonsFullscreen() {\n return prefs.getBoolean(PREF_REVIEWS_LESSONS_FULLSCREEN, false);\n }\n\n public static void setReviewsLessonsFullscreen(boolean value) {\n prefs.edit().putBoolean(PREF_REVIEWS_LESSONS_FULLSCREEN, value).commit();\n }\n\n public static void setNotificationsEnabled(Context context, boolean value) {\n prefs.edit().putBoolean(PREF_SHOW_NOTIFICATIONS, value).commit();\n if (!value) {\n new NotificationScheduler(context).cancelNotifications();\n }\n }\n\n public static boolean notificationsEnabled() {\n return prefs.getBoolean(PREF_SHOW_NOTIFICATIONS, true);\n }\n\n public static boolean reminderNotificationEnabled() {\n return prefs.getBoolean(PREF_ENABLE_REMINDER_NOTIFICATION, true);\n }\n\n public static void setReminderNotificationEnabled(boolean value) {\n prefs.edit().putBoolean(PREF_ENABLE_REMINDER_NOTIFICATION, value).commit();\n }\n\n public static long getReminderNotificationInterval() {\n return prefs.getLong(PREF_REMINDER_NOTIFICATION_INTERVAL, 7200000); // 2 hours by default\n }\n\n public static void setReminderNotificationInterval(long milliseconds) {\n prefs.edit().putLong(PREF_REMINDER_NOTIFICATION_INTERVAL, milliseconds).commit();\n }\n\n public static void logout(Context context) {\n prefs.edit().clear().commit();\n reviewsPrefs.edit().clear().commit();\n\n File offlineData = new File(Environment.getDataDirectory() + \"/data/\" + context.getPackageName() + \"/shared_prefs/offline_data.xml\");\n File cacheDir = new File(Environment.getDataDirectory() + \"/data/\" + context.getPackageName() + \"/cache\");\n File webviewCacheDir = new File(Environment.getDataDirectory() + \"/data/\" + context.getPackageName() + \"/app_webview\");\n\n try {\n if (offlineData.exists()) {\n offlineData.delete();\n }\n FileUtils.deleteDirectory(cacheDir);\n FileUtils.deleteDirectory(webviewCacheDir);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n // Cancel the notification alarm...\n Intent notificationIntent = new Intent(context, NotificationPublisher.class);\n PendingIntent pendingIntent = PendingIntent.getBroadcast(\n context,\n NotificationPublisher.REQUEST_CODE,\n notificationIntent,\n PendingIntent.FLAG_UPDATE_CURRENT\n );\n AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n alarmManager.cancel(pendingIntent);\n }\n\n public enum Keyboard {\n LOCAL_IME, NATIVE\n }\n}", "public class WaniKaniImprove {\n\n /**\n * The current state.\n */\n private class State implements Runnable {\n\n /// Last item\n private String item;\n\n /// Last item type\n private String type;\n\n /// In case this is a radical, this is its name\n private String jstoreEn [];\n\n /**\n * Constrcutor\n * @param item last item\n * @param type last item type\n * @param jstoreEn in case this is a radical, its name\n */\n public State (String item, String type, String jstoreEn [])\n {\n this.item = item;\n this.type = type;\n this.jstoreEn = jstoreEn;\n }\n\n /**\n * Called when we should display the last item info dialog.\n * This method can be safely called from any thread.\n */\n public void publish ()\n {\n activity.runOnUiThread (this);\n }\n\n /**\n * Returns the quickview URL for the current item\n * @return the URL\n */\n public String getURL ()\n {\n StringBuffer sb;\n\n\t\t\t/* This is obsolete: will be fixed as soon as I integrate version WKI 2.0 */\n sb = new StringBuffer (\"https://www.wanikani.com/\");\n\n if (type.equals (\"kanji\"))\n sb.append (\"kanji/\").append (item).append ('/');\n else if (type.equals (\"vocabulary\"))\n sb.append (\"vocabulary/\").append (item).append ('/');\n else\n sb.append (\"radicals/\").\n append (jstoreEn [0].toLowerCase ().replace (' ', '-')).\n append ('/');\n\n return sb.toString ();\n }\n\n /**\n * Shows the dialog. To be called inside the UI thread.\n */\n public void run ()\n {\n showDialog (this);\n }\n }\n\n /**\n * WebViewClient implementation for the intergrated browser inside the item info dialog.\n */\n private class WebViewClientImpl extends WebViewClient {\n\n /// The dialog owning the webview\n Dialog dialog;\n\n /// Progress bar, to show how the download is going\n ProgressBar pb;\n\n /// A text view that can display error messages, if something goes wrong\n TextView tv;\n\n /// The dialog title\n String title;\n\n /// This code comes from WKI 2.2.12\n private static final String JS_TAILOR =\n \"var wki_iframe_content = $('body');\\r\\n\" +\n \"wki_iframe_content.append('<style>.footer-adjustment, footer {display: none !important} body {margin: 10px !important;} section {margin: 0 !important; } .container {margin: 0 !important; } .level-icon { min-height: 52px; float: left;} .vocabulary-icon, .kanji-icon, .radical-icon {float: right; width: 83%; height: auto; padding-left: 0 !important; padding-right: 0 !important; min-height: 52px;} .wki_iframe_header {font-weight: bold; text-align: center; line-height: 55px} .wki_iframe_section {margin: 30px 0 0 !important} .wki_iframe_section:after {clear: both; } .wki_iframe_section h2 {border-bottom: 1px solid rgb(212, 212, 212) !important; margin: 15px 0 7px !important;} .wki_iframe_header .enlarge-hover { display: none !important; } </style>');\\r\\n\" +\n \"\\r\\n\" +\n \"var wki_iframe_item = wki_iframe_content.find('header>h1');\\r\\n\" +\n \"var wki_iframe_item_progress = wki_iframe_content.find('#progress').addClass('wki_iframe_section').wrap('<div></div>').parent().html();\\r\\n\" +\n \"var wki_iframe_item_alternative_meaning = wki_iframe_content.find('#information').addClass('individual-item').wrap('<div></div>').parent();\\r\\n\" +\n \"{\\r\\n\" +\n \" var wki_iframe_item_reading = wki_iframe_content.find('h2:contains(\\\"Reading\\\")').parent('section').addClass('wki_iframe_section');\\r\\n\" +\n \"\\r\\n\" +\n \" $('<h2>', {'class' : 'wki_iframe_header'}).appendTo(wki_iframe_content).append(wki_iframe_item.children()).append('<br style=\\\"clear: both;\\\" />');\\r\\n\" +\n \" wki_iframe_content.append(wki_iframe_item_reading);\\r\\n\" +\n \"}\\r\\n\" +\n \"{\\r\\n\" +\n \" if(document.URL.indexOf ('radical') >= 0)\\r\\n\" +\n \" {\\r\\n\" +\n \" var wki_iframe_item_meaning = wki_iframe_content.find('h2:contains(\\\"Name\\\")').parent('section').addClass('wki_iframe_section');\\r\\n\" +\n \" }\\r\\n\" +\n \" else\\r\\n\" +\n \" {\\r\\n\" +\n \" var wki_iframe_item_meaning = wki_iframe_content.find('h2:contains(\\\"Meaning\\\")').parent('section').addClass('wki_iframe_section');\\r\\n\" +\n \" }\\r\\n\" +\n \" wki_iframe_content.append('<h2 class=\\\"wki_iframe_header\\\">' + wki_iframe_item.html() + '</h2>');\\r\\n\" +\n \" wki_iframe_content.append(wki_iframe_item_alternative_meaning);\\r\\n\" +\n \" wki_iframe_content.append(wki_iframe_item_meaning);\\r\\n\" +\n \"}\\r\\n\" +\n \"wki_iframe_content.append(wki_iframe_item_progress);\\r\\n\";\n\n\n /**\n * Constructor\n * @param dialog the enclosing dialog\n * @param title its title\n */\n WebViewClientImpl (Dialog dialog, String title)\n {\n this.dialog = dialog;\n this.title = title;\n\n pb = (ProgressBar) dialog.findViewById (R.id.pb_lastitem);\n tv = (TextView) dialog.findViewById (R.id.tv_lastitem_message);\n }\n\n @Override\n public void onPageStarted (WebView view, String url, Bitmap favicon)\n {\n pb.setVisibility (View.VISIBLE);\n }\n\n @Override\n public void onReceivedError (WebView view, int errorCode, String description, String failingUrl)\n {\n dialog.setTitle (title);\n pb.setVisibility (View.GONE);\n tv.setText (activity.getResources ().getString (R.string.error_no_connection));\n tv.setVisibility (View.VISIBLE);\n view.setVisibility (View.GONE);\n }\n\n @Override\n public void onPageFinished (WebView view, String url)\n {\n dialog.setTitle (title);\n pb.setVisibility (View.GONE);\n\n view.loadUrl (\"javascript:(function() { \" + JS_TAILOR + \"})()\");\n }\n }\n\n /// This code must be run when the page is initially shown, to show the info button\n private static final String JS_INIT_PAGE =\n\n// Original script\n \"\\r\\n\" +\n \"$('<li id=\\\"option-show-previous\\\"><span title=\\\"Check previous item\\\" lang=\\\"ja\\\"><i class=\\\"icon-question-sign\\\"></i></span></li>').insertAfter('#option-last-items').addClass('disabled');\\r\\n\" +\n \"$('<style type=\\\"text/css\\\"> .qtip{ max-width: 380px !important; } #additional-content ul li { width: 16% !important; } #additional-content {text-align: center;} #option-show-previous img { max-width: 12px; background-color: #00A2F3; padding: 2px 3px; }</style>').appendTo('head');\\r\\n\" +\n \"\\r\\n\" +\n\n// Glue code, to bind the button to the JS bridge\n \"$('#option-show-previous').on('click', function (event)\" +\n \"{\" +\n \"\twknWanikaniImprove.show ();\" +\n \"});\";\n\n private static final String JS_UNINIT_PAGE =\n \"$('#option-show-previous').remove ()\";\n\n /// This code must be run when the \"next\" button is pressed.\n private static final String JS_CODE =\n// Original script\n \"function checkAnswer()\\r\\n\" +\n \"{\\r\\n\" +\n \" answerException = $.trim($('#answer-exception').text());\\r\\n\" +\n\n // Added by @Aralox, use these lines to print the page HTML, for debugging.\n// \" console.log('answer message: '+answerException);\" +\n// \" console.log('document: ');\" +\n// \" doclines = $('body').html().split('\\\\n');\" +\n// \" for (var di = 0; di < doclines.length; di++) { console.log(doclines[di]); } \" +\n\n \" if(answerException)\\r\\n\" +\n \" {\\r\\n\" +\n \" if(answerException.indexOf('answer was a bit off') !== -1)\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('answerException: your answer was a bit off');\\r\\n\" +\n \" $('#option-show-previous span').css('background-color', '#F5F7AB').attr('title', 'Your answer was a bit off');\\r\\n\" +\n \" }\\r\\n\" +\n \" else if(answerException.indexOf('possible readings') !== -1)\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('answerException: other possible readings');\\r\\n\" +\n \" $('#option-show-previous span').css('background-color', '#CDE0F7').attr('title', 'There are other possible readings');\\r\\n\" +\n \" }\\r\\n\" +\n \" else if(answerException.indexOf('possible meanings') !== -1)\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('answerException: other possible meanings');\\r\\n\" +\n \" $('#option-show-previous span').css('background-color', '#CDE0F7').attr('title', 'There are other possible meanings');\\r\\n\" +\n \" }\\r\\n\" +\n \" else if(answerException.indexOf('View the correct') !== -1)\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('answerException: wrong answer');\\r\\n\" +\n \" }\\r\\n\" +\n \" else\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('answerException: ' + answerException);\\r\\n\" +\n \" $('#option-show-previous span').css('background-color', '#FBFBFB');\\r\\n\" +\n \" }\\r\\n\" +\n \" }\\r\\n\" +\n \" else\\r\\n\" +\n \" {\\r\\n\" +\n \" $('#option-show-previous span').css('background-color', '#FBFBFB');\\r\\n\" +\n \" }\\r\\n\" +\n \" \\r\\n\" +\n \" if ($('#answer-form form fieldset').hasClass('correct'))\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('Correct answer');\\r\\n\" +\n \" moveNext();\\r\\n\" +\n \"\\r\\n\" +\n \" }\\r\\n\" +\n \" else if ($('#answer-form form fieldset').hasClass('incorrect'))\\r\\n\" +\n \" {\\r\\n\" +\n \" console.log('Wrong answer');\\r\\n\" +\n \" }\\r\\n\" +\n \"}\\r\\n\" +\n \"\\r\\n\" +\n \"function moveNext()\\r\\n\" +\n \"{\\r\\n\" +\n \" console.log('Moving to next question');\\r\\n\" +\n \" $('#answer-form button').click();\\r\\n\" +\n \"}\" +\n\n// Glue code, pushing status info and triggering checkAnswer()\n \"\t jstored_currentItem = $.jStorage.get('currentItem');\" +\n \" $('#option-show-previous').removeClass('disabled');\" +\n \" currentItem = $.trim($('#character span').html());\" +\n \" currentType = $('#character').attr('class');\" +\n \" currentQuestionType = $.trim($('#question-type').text());\" +\n \" wknWanikaniImprove.save (currentItem, currentType, currentQuestionType, jstored_currentItem.en);\" +\n\n\n // @Aralox introduced the delay, to allow enough time for the javascript to update the html so that this\n // script works properly after the 'info-panel' is opened. (https://github.com/xiprox/WaniKani-for-Android/issues/46)\n \" setTimeout(checkAnswer, 300);\";\n //\" checkAnswer();\"; // old\n\n /// The current state\n private State currentState;\n\n /// The main activity\n private WebReviewActivity activity;\n\n /// The main WebView\n private FocusWebView wv;\n\n /**\n * Constructor.\n * @param activity the main actibity\n * @param wv the webview\n */\n public WaniKaniImprove (WebReviewActivity activity, FocusWebView wv)\n {\n this.activity = activity;\n this.wv = wv;\n\n wv.addJavascriptInterface (this, \"wknWanikaniImprove\");\n }\n\n /**\n * Initializes the page. Must be called when the reviews page is entered\n */\n public void initPage ()\n {\n currentState = null;\n wv.js (LocalIMEKeyboard.ifReviews(JS_INIT_PAGE));\n }\n\n /**\n * Deinitializes the page.\n */\n public void uninitPage ()\n {\n wv.js (JS_UNINIT_PAGE);\n }\n\n /**\n * Save state.\n * @param currentItem current item name\n * @param currentType current item type\n * @param currentQuestionType current question tyoe\n * @param jstoreEn radical name\n */\n @JavascriptInterface\n public void save (String currentItem, String currentType, String currentQuestionType, String jstoreEn [])\n {\n currentState = new State (currentItem, currentType, jstoreEn);\n }\n\n /**\n * Shows the dialog. Must be bound to the \"last item info\" button.\n */\n @JavascriptInterface\n public void show ()\n {\n if (currentState != null)\n currentState.publish ();\n }\n\n /**\n * Shows the dialog. Must be run on the main UI thread\n * @param state the state to be published\n */\n private void showDialog (State state)\n {\n Resources res;\n WebView webview;\n Dialog dialog;\n String title;\n\n if (!activity.visible)\n return;\n\n res = activity.getResources ();\n\n dialog = new Dialog (activity);\n dialog.setTitle (res.getString (R.string.fmt_last_item_wait));\n dialog.setContentView (R.layout.lastitem);\n webview = (WebView) dialog.findViewById (R.id.wv_lastitem);\n webview.getSettings ().setJavaScriptEnabled (true);\n title = res.getString (R.string.fmt_last_item, state.type);\n webview.setWebViewClient (new WebViewClientImpl (dialog, title));\n webview.loadUrl (state.getURL ());\n\n dialog.show ();\n }\n\n public static String getCode ()\n {\n return LocalIMEKeyboard.ifReviews (JS_CODE);\n }\n\n}", "public class WaniKaniKunOn {\n\n public static final String JS_CODE =\n /* Removed debug code. --ed\n \"var debugLogEnabled = false;\\r\\n\" +\n \"var scriptShortName = \\\"WKKO\\\";\\r\\n\" +\n \"scriptLog = debugLogEnabled ? function(msg) { if(typeof msg === 'string'){ console.log(scriptShortName + \\\": \\\" + msg); }else{ console.log(msg); } } : function() {};\\r\\n\" +\n \"\\r\\n\" +\n */\n \"function updateReadingText() {\" +\n \"var curItem = $.jStorage.get(\\\"currentItem\\\");\" +\n \"var questionType = $.jStorage.get(\\\"questionType\\\");\" +\n \"if(questionType == \\\"reading\\\" && \\\"kan\\\" in curItem) {\" +\n \"var readingType = \\\"Reading\\\";\" +\n \"if(curItem.emph == \\\"onyomi\\\") readingType = \\\"On'yomi\\\";\" +\n \"else readingType = \\\"Kun'yomi\\\";\" +\n \"$('#question-type').html('<h1>Kanji <strong>' + readingType + '</strong></h1>');\" +\n \"}\" +\n \"}\" +\n \"updateReadingText();\";\n\n}", "public class Fonts {\n private static Typeface custom = null;\n private static Typeface normal = Typeface.create(\"sans-serif\", Typeface.NORMAL);\n\n public Typeface getKanjiFont(Context context) {\n if (PrefManager.isUseCustomFonts()) {\n if (custom == null)\n custom = Typeface.createFromAsset(context.getAssets(), \"fonts/MTLmr3m.ttf\");\n return custom;\n } else {\n return normal;\n }\n }\n}", "public class Utils {\n Context context;\n\n public Utils(Context context) {\n this.context = context;\n }\n\n private static double removeMinusFromLong(double time) {\n if (time < 0) {\n String timeString = time + \"\";\n timeString = timeString.substring(1, timeString.length());\n return Double.parseDouble(timeString);\n } else return time;\n }\n\n public static Date getCurrentDate() {\n return new Date(System.currentTimeMillis());\n }\n\n public boolean isNetworkAvailable() {\n ConnectivityManager connectivityManager\n = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\n return activeNetworkInfo != null;\n }\n\n public float pxFromDp(float dp) {\n return dp * context.getResources().getDisplayMetrics().density;\n }\n\n /**\n * I hate myself for doing this but I really don't feel like looking at LevelPickerDialogFragment.\n * Who the hell keeps an int array as comma-delimited string! Someone kill me pls. ugh\n */\n public static int[] convertStringArrayToIntArray(String[] strings) {\n int[] ints = new int[strings.length];\n for (int i = 0; i < strings.length; i++) {\n ints[i] = Integer.parseInt(strings[i]);\n }\n return ints;\n }\n}" ]
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.media.AudioManager; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.DisplayMetrics; import android.util.TypedValue; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.JavascriptInterface; import android.webkit.ValueCallback; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import java.lang.reflect.Method; import java.util.EnumMap; import java.util.Hashtable; import java.util.Map; import tr.xip.wanikani.app.activity.FocusWebView; import tr.xip.wanikani.app.activity.WebReviewActivity; import tr.xip.wanikani.models.WaniKaniItem; import tr.xip.wanikani.managers.PrefManager; import tr.xip.wanikani.userscripts.IgnoreButton; import tr.xip.wanikani.userscripts.LessonOrder; import tr.xip.wanikani.userscripts.MistakeDelay; import tr.xip.wanikani.userscripts.ReviewOrder; import tr.xip.wanikani.userscripts.WaniKaniImprove; import tr.xip.wanikani.userscripts.WaniKaniKunOn; import tr.xip.wanikani.utils.Fonts; import tr.xip.wanikani.utils.Utils;
* Called when the text box should be shown */ @JavascriptInterface public void showKeyboard () { bpos.visible = true; new JSHideShow (bpos.shallShow ()); } /** * Called when the text box should be hidden */ @JavascriptInterface public void hideKeyboard () { bpos.visible = false; new JSHideShow (bpos.shallShow ()); } /** * Called when the timeout div is shown or hidden. Need to catch this event to hide * and show the windows as well. * @param enabled if the div is shown */ @JavascriptInterface public void timeout (boolean enabled) { bpos.timeout = enabled; new JSHideShow (bpos.shallShow ()); } /** * Re-enables the edit box, because the event has been delivered. */ @JavascriptInterface () public void unfreeze () { frozen = false; } @JavascriptInterface () public void refreshWKLO () { if (PrefManager.getLessonOrder()) wv.js (ifLessons (LessonOrder.JS_REFRESH_CODE)); } /** * Called by LocalIMEKeyboard.replace(), to appropriately call ew.requestFocus() if we are not editing a note/synonym. Added by @Aralox. * @param noteBeingEdited return value of javascript which checks if note/synonym being edited (true/false). */ @JavascriptInterface public void requestFocusIfSafe (String noteBeingEdited) { //Log.d("aralox", "received " + noteBeingEdited); if (noteBeingEdited.equals("false")) { //Log.d("aralox", "note not being edited. calling ew.requestFocus()"); // Need to run EditText.requestFocus() on main thread, not UI thread. Technique from https://stackoverflow.com/a/11125271/1072869 Handler mainHandler = new Handler(Looper.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { //Log.d("aralox", "calling EditText.requestFocus()"); ew.requestFocus(); } }; mainHandler.post(myRunnable); } //else Log.d("aralox", "note being edited. not calling ew.requestFocus()"); } } /** * A JS condition that evaluates to true if we are reviewing, false if we are in the lessons module */ private static final String JS_REVIEWS_P = "(document.getElementById (\"quiz\") == null)"; /** * The javascript triggers. They are installed when the keyboard is shown. */ private static final String JS_INIT_TRIGGERS = "window.wknSequence = 1;" + "window.wknReplace = function () {" + " var form, frect, txt, trect, button, brect;" + " form = document.getElementById (\"answer-form\");" + " txt = document.getElementById (\"user-response\");" + " button = form.getElementsByTagName (\"button\") [0];" + " frect = form.getBoundingClientRect ();" + " trect = txt.getBoundingClientRect ();" + " brect = button.getBoundingClientRect ();" + " wknJSListener.replace (window.wknSequence, frect.left, frect.top, frect.right, frect.bottom," + " trect.left, trect.top, brect.left, trect.bottom);" + " window.wknSequence++;" + "};" + "window.wknOverrideQuestion = function () {" + " var item, question, rect, style;" + " item = $.jStorage.get (\"currentItem\");" + " question = document.getElementById (\"character\");" + " if (question.getElementsByTagName (\"span\").length > 0)" + " question = question.getElementsByTagName (\"span\") [0];" + " rect = question.getBoundingClientRect ();" + " style = window.getComputedStyle (question, null);" + " wknJSListener.overrideQuestion (window.wknSequence," + " item.rad ? item.rad : null," + " item.kan ? item.kan : null," + " item.voc ? item.voc : null, " + " rect.left, rect.top, rect.right, rect.bottom," + " style.getPropertyValue(\"font-size\"));" + " window.wknSequence++;" + "};" + "window.wknNewQuestion = function (entry, type) {" +
WebReviewActivity.getHideLinkCode() + // Added by @Aralox, to hook onto new question event.
0
FAOSTAT/faostat-api
faostat-api-web/src/main/java/org/fao/faostat/api/legacy/V10Methodology.java
[ "public class DatasourceBean {\n\n private String driver;\n\n private String url;\n\n private String dbName;\n\n private String username;\n\n private String password;\n\n private static final Logger LOGGER = Logger.getLogger(DatasourceBean.class);\n\n private static Properties properties = null;\n\n public DatasourceBean(DATASOURCE datasource) {\n\n try {\n\n if (properties == null) {\n LOGGER.info(\"DATASOURCE.properties are null! \" + properties);\n ClassLoader classloader = Thread.currentThread().getContextClassLoader();\n properties = new Properties();\n InputStream input = classloader.getResourceAsStream(\"datasources.properties\");\n properties.load(input);\n if (input != null) {\n try {\n input.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }else{\n LOGGER.info(\"DATASOURCE.properties already set \" + properties);\n }\n\n LOGGER.info(\"DATASOURCE: \" + datasource);\n LOGGER.info(\"properties.getProperty(datasource + \\\".url\\\")\" + properties.getProperty(datasource + \".url\"));\n\n this.setDbName(properties.getProperty(datasource + \".dbname\"));\n this.setDriver(properties.getProperty(datasource + \".driver\"));\n this.setPassword(properties.getProperty(datasource + \".pwd\"));\n this.setUrl(properties.getProperty(datasource + \".url\"));\n this.setUsername(properties.getProperty(datasource + \".user\"));\n\n } catch (IOException ex) {\n ex.printStackTrace();\n } finally {\n }\n }\n\n public String getDriver() {\n return driver;\n }\n\n public void setDriver(String driver) {\n this.driver = driver;\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 getDbName() {\n return dbName;\n }\n\n public void setDbName(String dbName) {\n this.dbName = dbName;\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 getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public String toString() {\n return \"DatasourceBean{\" +\n \"driver='\" + driver + '\\'' +\n \", url='\" + url + '\\'' +\n \", dbName='\" + dbName + '\\'' +\n \", username='\" + username + '\\'' +\n \", password='\" + password + '\\'' +\n '}';\n }\n\n}", "public class MetadataBean {\n\n private DATASOURCE datasource;\n\n private String apiKey;\n\n private String clientKey;\n\n private OUTPUTTYPE outputType;\n\n private List<String> blackList;\n\n private List<String> whiteList;\n\n private Map<String, Object> procedureParameters;\n\n private List<Map<String, Object>> dsd;\n\n private Boolean pivot = false;\n\n private Boolean full = false;\n\n private Long processingTime;\n\n public MetadataBean() {\n this.setDatasource(DATASOURCE.PRODUCTION);\n this.setApiKey(null);\n this.setClientKey(null);\n this.setOutputType(OUTPUTTYPE.OBJECTS);\n this.setProcedureParameters(new HashMap<String, Object>());\n this.setDsd(new ArrayList<Map<String, Object>>());\n this.setClientKey(null);\n }\n\n public MetadataBean(String datasource, String apiKey, String clientKey, String outputType) {\n this.storeUserOptions(datasource, apiKey, clientKey, outputType);\n }\n\n public void storeUserOptions(String datasource, String apiKey, String clientKey, String outputType) {\n this.setDatasource(datasource != null ? DATASOURCE.valueOf(datasource.toUpperCase()) : DATASOURCE.PRODUCTION);\n this.setApiKey(apiKey != null ? apiKey : this.getApiKey());\n this.setClientKey(clientKey != null ? clientKey : this.getClientKey());\n this.setOutputType(outputType != null ? OUTPUTTYPE.valueOf(outputType.toUpperCase()) : OUTPUTTYPE.OBJECTS);\n this.setProcedureParameters(new HashMap<String, Object>());\n this.setDsd(new ArrayList<Map<String, Object>>());\n }\n\n public List<String> getBlackList() {\n return blackList;\n }\n\n public void setBlackList(List<String> blackList) {\n this.blackList = blackList;\n }\n\n public List<String> getWhiteList() {\n return whiteList;\n }\n\n public void setWhiteList(List<String> whiteList) {\n this.whiteList = whiteList;\n }\n\n public void addParameter(String key, Object value) {\n this.getProcedureParameters().put(key, value);\n }\n\n public void addParameters(Map<String, Object> params) {\n this.getProcedureParameters().putAll(params);\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 getApiKey() {\n return apiKey;\n }\n\n public void setApiKey(String apiKey) {\n this.apiKey = apiKey;\n }\n\n public String getClientKey() {\n return clientKey;\n }\n\n public void setClientKey(String clientKey) {\n this.clientKey = clientKey;\n }\n\n public OUTPUTTYPE getOutputType() {\n return outputType;\n }\n\n public void setOutputType(OUTPUTTYPE outputType) {\n this.outputType = outputType;\n }\n\n public Map<String, Object> getProcedureParameters() {\n return procedureParameters;\n }\n\n public void setProcedureParameters(Map<String, Object> procedureParameters) {\n this.procedureParameters = procedureParameters;\n }\n\n public Boolean getPivot() {\n return pivot;\n }\n\n public void setPivot(Boolean pivot) {\n this.pivot = pivot;\n }\n\n public List<Map<String, Object>> getDsd() {\n return dsd;\n }\n\n public void setDsd(List<Map<String, Object>> dsd) {\n this.dsd = dsd;\n }\n\n public Long getProcessingTime() {\n return processingTime;\n }\n\n public void setProcessingTime(Long processingTime) {\n this.processingTime = processingTime;\n }\n\n public Boolean getFull() { return full; }\n\n public void setFull(Boolean full) {\n if (full != null ) {\n this.full = full;\n }\n }\n\n @Override\n public String toString() {\n return \"MetadataBean{\" +\n \"datasource='\" + datasource + '\\'' +\n \", apiKey='\" + apiKey + '\\'' +\n \", clientKey='\" + clientKey + '\\'' +\n \", outputType=\" + outputType +\n \", blackList=\" + blackList +\n \", whiteList=\" + whiteList +\n \", procedureParameters=\" + procedureParameters +\n \", pivot=\" + pivot +\n \", full=\" + full +\n \", dsd=\" + dsd +\n \", processingTime=\" + processingTime +\n '}';\n }\n\n}", "public class FAOSTATAPICore {\n\n private static final Logger LOGGER = Logger.getLogger(FAOSTATAPICore.class);\n\n private QUERIES queries;\n\n public FAOSTATAPICore() {\n this.setQueries(new QUERIES());\n }\n\n public OutputBean query(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n try {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate output. */\n OutputBean out = new OutputBean();\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n /* Query the DB. */\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, metadataBean);\n\n /* Add column names. */\n out.setColumnNames(i.getColumnNames());\n\n /* Get column names */\n while (i.hasNext()) {\n switch (metadataBean.getOutputType()) {\n case ARRAYS:\n out.getData().addList(i.next());\n break;\n case CSV:\n out.getData().addList(i.next());\n break;\n default:\n out.getData().add(i.nextMap());\n break;\n }\n }\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n return out;\n\n } catch (Exception e) {\n throw new Exception(e);\n }\n\n }\n\n public OutputBean querySearch(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n try {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate output. */\n OutputBean out = new OutputBean();\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n\n /* Query the DB. */\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, metadataBean);\n\n /* Add column names. */\n out.setColumnNames(i.getColumnNames());\n\n while (i.hasNext()) {\n Map<String, Object> dbRow = i.nextMap();\n Map<String, Object> o = new LinkedHashMap<String, Object>();\n o.put(\"id\", dbRow.get(\"id\"));\n o.put(\"domain_code\", dbRow.get(\"DomainCode\"));\n o.put(\"code\", dbRow.get(\"Code\"));\n o.put(\"label\", dbRow.get(\"Label\"));\n o.put(\"rank\", dbRow.get(\"rank\"));\n out.getData().add(o);\n }\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n return out;\n\n } catch (Exception e) {\n //throw new Exception(log.toString());\n LOGGER.error(e.getMessage());\n throw new Exception(e.getMessage());\n }\n\n }\n\n public OutputBean queryRankings(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n try {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate output. */\n OutputBean out = new OutputBean();\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n\n /* Query the DB. */\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, metadataBean);\n /* Add column names. */\n out.setColumnNames(i.getColumnNames());\n\n /* Add data to the output. */\n while (i.hasNext()) {\n switch (metadataBean.getOutputType()) {\n case ARRAYS:\n out.getData().addList(i.next());\n break;\n case CSV:\n out.getData().addList(i.next());\n break;\n default:\n out.getData().add(i.nextMap());\n break;\n }\n }\n\n /* Add DSD. */\n out.getMetadata().setDsd(createDSD(datasourceBean, metadataBean));\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n /* Return output. */\n return out;\n\n } catch (Exception e) {\n //throw new Exception(log.toString());\n LOGGER.error(e.getMessage());\n throw new Exception(e.getMessage());\n }\n\n }\n\n public OutputBean queryDimensions(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n // full version\n boolean isFull = (metadataBean.getFull() != null)? metadataBean.getFull(): false;\n\n try {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate variables. */\n List<List<Map<String, Object>>> dimensions = getDomainDimensions(queryCode, datasourceBean, metadataBean);\n //LOGGER.info(\"dimensions? \" + dimensions.size());\n List<Map<String, Object>> tmp = new ArrayList<>();\n for (List<Map<String, Object>> l : dimensions) {\n tmp.addAll(l);\n }\n //LOGGER.info(\"tmp? \" + tmp.size());\n //LOGGER.info(\"Dimensions: \" + dimensions);\n\n /* Group Dimensions. */\n List<Map<String, Object>> output = new ArrayList<>();\n String currentList = tmp.get(0).get(\"ListBoxNo\").toString();\n //LOGGER.info(\"currentList: \" + currentList);\n Map<String, Object> group = new LinkedHashMap<>();\n //group.put(\"ord\", Integer.parseInt(currentList));\n //group.put(\"parameter\", \"List\" + currentList + \"Codes\");\n if ( isFull ) {\n // TODO: the parameter should come from a constant or better from the DB!\n group.put(\"parameter\", \"List\" + currentList + \"Codes\");\n }\n //LOGGER.info(\"isFull: \" + isFull);\n group.put(\"id\", tmp.get(0).get(\"VarType\").toString());\n group.put(\"href\", \"/codes/\" + tmp.get(0).get(\"VarType\").toString() + \"/\");\n group.put(\"subdimensions\", new ArrayList<Map<String, Object>>());\n for (int i = 0; i < tmp.size(); i += 1) {\n\n //LOGGER.info(tmp.get(i));\n\n if (tmp.get(i).get(\"ListBoxNo\").toString().equalsIgnoreCase(currentList)) {\n\n //LOGGER.info(\"IF\");\n\n Map<String, Object> m = new LinkedHashMap<>();\n m.put(\"id\", tmp.get(i).get(\"id\").toString());\n m.put(\"label\", tmp.get(i).get(\"TabName\").toString());\n //m.put(\"description\", tmp.get(i).get(\"TabName\").toString());\n m.put(\"href\", \"/codes/\" + tmp.get(i).get(\"id\").toString() + \"/\");\n //m.put(\"ord\", Integer.parseInt(tmp.get(i).get(\"TabOrder\").toString()));\n //m.put(\"parameter\", \"List\" + currentList + \"Codes\");\n\n //LOGGER.info(m);\n\n // options\n Map<String, Object> o = new LinkedHashMap<>();\n o.put(\"selectType\", tmp.get(i).get(\"ListBoxSelectType\").toString());\n o.put(\"type\", tmp.get(i).get(\"ListBoxFormat\").toString());\n\n //LOGGER.info(o);\n\n if ( isFull ) {\n // TODO: the parameter should come from a constant or better from the DB!\n m.put(\"parameter\", \"List\" + currentList + \"Codes\");\n m.put(\"options\", o);\n }\n\n /* Add available coding systems. */\n String[] codingSystems = tmp.get(i).get(\"CodingSystems\").toString().split(\";\");\n m.put(\"coding_systems\", new ArrayList<String>());\n for (String cs : codingSystems) {\n if (cs.length() > 0) {\n ((ArrayList<String>) m.get(\"coding_systems\")).add(cs);\n }\n }\n\n //LOGGER.info(\"coding_systems\");\n\n ((ArrayList<Map<String, Object>>) group.get(\"subdimensions\")).add(m);\n } else {\n\n //LOGGER.info(\"ELSE\");\n\n output.add(group);\n currentList = tmp.get(i).get(\"ListBoxNo\").toString();\n group = new LinkedHashMap<>();\n //group.put(\"ord\", Integer.parseInt(currentList));\n\n // TODO: the parameter should come from a constant or better from the DB!\n //group.put(\"parameter\", \"List\" + currentList + \"Codes\");\n\n group.put(\"id\", tmp.get(i).get(\"VarType\").toString());\n group.put(\"href\", \"/codes/\" + tmp.get(i).get(\"VarType\").toString() + \"/\");\n group.put(\"subdimensions\", new ArrayList<Map<String, Object>>());\n\n Map<String, Object> m = new LinkedHashMap<>();\n m.put(\"id\", tmp.get(i).get(\"id\").toString());\n m.put(\"label\", tmp.get(i).get(\"TabName\").toString());\n //m.put(\"description\", tmp.get(i).get(\"TabName\").toString());\n m.put(\"href\", \"/codes/\" + tmp.get(i).get(\"id\").toString() + \"/\");\n //m.put(\"ord\", Integer.parseInt(tmp.get(i).get(\"TabOrder\").toString()));\n\n // options\n Map<String, Object> o = new LinkedHashMap<>();\n o.put(\"selectType\", tmp.get(i).get(\"ListBoxSelectType\").toString());\n o.put(\"type\", tmp.get(i).get(\"ListBoxFormat\").toString());\n\n if ( isFull ) {\n // TODO: the parameter should come from a constant or better from the DB!\n m.put(\"parameter\", \"List\" + currentList + \"Codes\");\n m.put(\"options\", o);\n\n // TODO: the parameter should come from a constant or better from the DB!\n group.put(\"parameter\", \"List\" + currentList + \"Codes\");\n }\n\n /* Add available coding systems. */\n String[] codingSystems = tmp.get(i).get(\"CodingSystems\").toString().split(\";\");\n m.put(\"coding_systems\", new ArrayList<String>());\n for (String cs : codingSystems) {\n if (cs.length() > 0) {\n ((ArrayList<String>) m.get(\"coding_systems\")).add(cs);\n }\n }\n ((ArrayList<Map<String, Object>>)group.get(\"subdimensions\")).add(m);\n }\n }\n output.add(group);\n\n /* Initiate output. */\n OutputBean out = new OutputBean(new FAOSTATIterable(output));\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n /* Return output. */\n return out;\n\n } catch (Exception e) {\n LOGGER.error(e);\n throw new Exception(e.getMessage());\n }\n\n }\n\n public OutputBean queryDefinitions(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate output. */\n OutputBean out = new OutputBean();\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n\n /* Query the DB. */\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, metadataBean);\n\n /* Add column names. */\n out.setColumnNames(i.getColumnNames());\n\n /* Add data to the output. */\n while (i.hasNext()) {\n\n Map<String, Object> dbRow = i.nextMap();\n\n Map<String, Object> o = new LinkedHashMap<String, Object>();\n o.put(\"code\", dbRow.get(\"code\"));\n o.put(\"label\", dbRow.get(\"label\"));\n o.put(\"id\", dbRow.get(\"VarType\"));\n o.put(\"subdimension_id\", dbRow.get(\"VarSubType\"));\n\n/* if (!String.valueOf(dbRow.get(\"VarType\")).equals(\"\")) {\n o.put(\"id\", dbRow.get(\"VarType\"));\n }\n if (!String.valueOf(dbRow.get(\"VarSubType\")).equals(\"\")) {\n o.put(\"subdimension_id\", dbRow.get(\"VarSubType\"));\n }*/\n\n out.getData().add(o);\n }\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n /* Return output. */\n return out;\n\n }\n\n public OutputBean queryDomains(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n try {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate output. */\n OutputBean out = new OutputBean();\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n\n /* Query the DB. */\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, metadataBean);\n\n /* Add column names. */\n out.setColumnNames(i.getColumnNames());\n\n /* Add data to the output. */\n\n while (i.hasNext()) {\n\n Map<String, Object> dbRow = i.nextMap();\n\n Map<String, Object> o = new LinkedHashMap<String, Object>();\n o.put(\"code\", dbRow.get(\"domain_code\"));\n o.put(\"label\", dbRow.get(\"domain_name\"));\n o.put(\"date_update\", dbRow.get(\"date_update\"));\n o.put(\"note_update\", dbRow.get(\"note_update\"));\n o.put(\"note\", dbRow.get(\"note\"));\n o.put(\"release_current\", dbRow.get(\"release_current\"));\n o.put(\"state_current\", dbRow.get(\"state_current\"));\n o.put(\"year_current\", dbRow.get(\"year_current\"));\n o.put(\"release_next\", dbRow.get(\"release_next\"));\n o.put(\"state_next\", dbRow.get(\"state_next\"));\n o.put(\"year_next\", dbRow.get(\"year_next\"));\n\n /* No Group (filter) selected */\n if ( metadataBean.getProcedureParameters().get(\"group_code\") == null) {\n\n // TODO: in theory should not be needed\n if (isAdmissibleDBRow(o, out.getMetadata())) {\n out.getData().add(o);\n }\n\n }else {\n\n /* Filter by a Group codes */\n if ( metadataBean.getProcedureParameters().get(\"group_code\").toString().equals(String.valueOf(dbRow.get(\"group_code\")))) {\n\n // TODO: in theory should not be needed\n if (isAdmissibleDBRow(o, out.getMetadata())) {\n out.getData().add(o);\n }\n }\n\n }\n\n }\n\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n return out;\n\n } catch (Exception e) {\n throw new Exception(log.toString());\n }\n\n }\n\n public OutputBean queryGroups(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n try {\n\n /* Statistics. */\n long t0 = System.currentTimeMillis();\n\n /* Initiate output. */\n OutputBean out = new OutputBean();\n\n /* Add metadata. */\n out.setMetadata(metadataBean);\n\n /* Query the DB. */\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, metadataBean);\n\n /* Add column names. */\n out.setColumnNames(i.getColumnNames());\n\n Set<Object> tmp = new HashSet<>();\n\n while (i.hasNext()) {\n Map<String, Object> dbRow = i.nextMap();\n\n if (!tmp.contains(dbRow.get(\"group_code\"))) {\n\n tmp.add(dbRow.get(\"group_code\"));\n\n Map<String, Object> o = new LinkedHashMap<String, Object>();\n o.put(\"code\", dbRow.get(\"group_code\"));\n o.put(\"label\", dbRow.get(\"group_name\"));\n //o.put(\"ord\", dbRow.get(\"ord\"));\n\n // TODO: in theory should not be needed\n if (isAdmissibleDBRow(o, out.getMetadata())) {\n out.getData().add(o);\n }\n\n }\n\n }\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n out.getMetadata().setProcessingTime(tf - t0);\n\n return out;\n\n } catch (Exception e) {\n throw new Exception(log.toString());\n }\n\n }\n\n public OutputBean queryCodes(DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Logs. */\n StringBuilder log = new StringBuilder();\n\n try {\n\n long t0 = System.currentTimeMillis();\n\n /* Get domain's dimensions. */\n List<List<Map<String, Object>>> dimensions = getDomainDimensions(\"dimensions\", datasourceBean, metadataBean);\n\n /* Organize data in an object. */\n final List<Map<String, Object>> structuredDimensions = organizeDomainDimensions(dimensions);\n\n /* Get the dimension of interest. */\n Map<String, Object> dimension = null;\n String dimensionCode = metadataBean.getProcedureParameters().get(\"id\").toString();\n for (Map<String, Object> d : structuredDimensions) {\n /* checking if is at dimension level */\n if (d.get(\"id\").toString().equalsIgnoreCase(dimensionCode)) {\n //LOGGER.info(d.get(\"id\").toString());\n dimension = d;\n break;\n }\n /* checking if is at subdimension level */\n ArrayList<Map<String, Object>> subdimensions = (ArrayList<Map<String, Object>>) d.get(\"subdimensions\");\n for (Map<String, Object> subd : subdimensions) {\n if (subd.get(\"id\").toString().equalsIgnoreCase(dimensionCode)) {\n //LOGGER.info(subd.get(\"id\").toString());\n dimension = subd;\n break;\n }\n }\n }\n\n //LOGGER.info(\"DimensionCode: \" + dimensionCode);\n //LOGGER.info(\"Dimension: \" + dimension);\n\n /* Prepare output. */\n List<Map<String, Object>> codes = new ArrayList<>();\n Map<String, Object> row;\n\n /* Get subdimensions. */\n ArrayList<Map<String, Object>> subDimensions = (ArrayList<Map<String, Object>>) dimension.get(\"subdimensions\");\n\n //LOGGER.info(\"subDimensions: \" + subDimensions);\n\n if (subDimensions != null) {\n\n /* Fetch codes for each sub-dimension. */\n for (Map<String, Object> m : subDimensions) {\n\n /* Define options to fetch codes. */\n MetadataBean subDimensionOptions = new MetadataBean();\n subDimensionOptions.addParameter(\"domain_code\", metadataBean.getProcedureParameters().get(\"domain_code\"));\n subDimensionOptions.addParameter(\"report_code\", metadataBean.getProcedureParameters().get(\"report_code\"));\n subDimensionOptions.addParameter(\"lang\", metadataBean.getProcedureParameters().get(\"lang\"));\n subDimensionOptions.addParameter(\"dimension\", m.get(\"ListBoxNo\").toString());\n subDimensionOptions.addParameter(\"subdimension\", m.get(\"TabOrder\").toString());\n\n /* Query codes */\n JDBCIterable subDimensionIterable = getJDBCIterable(\"codes\", datasourceBean, subDimensionOptions);\n\n /* Iterate over codes. */\n while (subDimensionIterable.hasNext()) {\n row = createCode(subDimensionIterable.nextMap());\n\n if (isAdmissibleCode(row, metadataBean)) {\n //row.remove(\"aggregate_type\");\n codes.add(row);\n }\n }\n\n }\n\n } else {\n\n /* Fetch codes. */\n MetadataBean subDimensionOptions = new MetadataBean();\n subDimensionOptions.addParameter(\"domain_code\", metadataBean.getProcedureParameters().get(\"domain_code\"));\n subDimensionOptions.addParameter(\"report_code\", metadataBean.getProcedureParameters().get(\"report_code\"));\n subDimensionOptions.addParameter(\"lang\", metadataBean.getProcedureParameters().get(\"lang\"));\n subDimensionOptions.addParameter(\"dimension\", dimension.get(\"ListBoxNo\").toString());\n subDimensionOptions.addParameter(\"subdimension\", dimension.get(\"TabOrder\").toString());\n\n /* Query codes. */\n JDBCIterable subDimensionIterable = getJDBCIterable(\"codes\", datasourceBean, subDimensionOptions);\n\n LOGGER.info(\"subDimensionIterable: \" + subDimensionIterable);\n\n while (subDimensionIterable.hasNext()) {\n /* Create code. */\n row = createCode(subDimensionIterable.nextMap());\n if (isAdmissibleCode(row, metadataBean)) {\n //row.remove(\"aggregate_type\");\n codes.add(row);\n }\n }\n\n }\n\n LOGGER.info(\"---Codes\");\n LOGGER.info(codes);\n\n /* Add children. */\n // TODO: verify is this condition is right. should work on EA/ODA\n /*List<Map<String, Object>> remove = new ArrayList<>();\n for (Map<String, Object> c1 : codes) {\n LOGGER.info(c1);\n if (c1.get(\"parent\") != null && c1.get(\"parent\") != \"0\") {\n for (Map<String, Object> c2 : codes) {\n if (c2.get(\"code\").toString().equalsIgnoreCase(c1.get(\"parent\").toString())) {\n // TODO: probably should be added children\n ((ArrayList<Map<String, Object>>) c2.get(\"children\")).add(c1);\n remove.add(c1);\n }\n }\n }\n }\n for (Map<String, Object> c : remove) {\n codes.remove(c);\n }*/\n\n LOGGER.info(\"--finished\");\n\n /* Group subdimensions, if required and if subdimensions exists. */\n final List<Map<String, Object>> output = new ArrayList<>();\n output.addAll(codes);\n\n /* Initiate output. */\n LOGGER.info(\"initiate out...\");\n OutputBean out = new OutputBean(new FAOSTATIterable(output));\n LOGGER.info(\"initiate out: done\");\n\n /* Add metadata. */\n LOGGER.info(\"add metadata...\");\n LOGGER.info(\"metadataBean != null? \" + (metadataBean != null));\n LOGGER.info(\"metadataBean.getProcedureParameters() != null? \" + (metadataBean.getProcedureParameters() != null));\n for (String key : dimension.keySet()) {\n LOGGER.info(\"dimension: \" + key + \" = \" + dimension.get(key));\n }\n LOGGER.info(\"parameter: \" + dimension.get(\"ListBoxNo\"));\n\n /* TODO: the 'parameter' for data procedure is fundamental */\n if (dimension.get(\"ListBoxNo\") != null) {\n metadataBean.getProcedureParameters().put(\"parameter\", \"List\" + dimension.get(\"ListBoxNo\").toString() + \"Codes\");\n } else {\n metadataBean.getProcedureParameters().put(\"parameter\", dimension.get(\"parameter\"));\n }\n\n out.setMetadata(metadataBean);\n LOGGER.info(\"add metadata... DONE\");\n\n /* Statistics. */\n long tf = System.currentTimeMillis();\n LOGGER.info(\"set statistics...\");\n out.getMetadata().setProcessingTime(tf - t0);\n\n /* Return output. */\n LOGGER.info(\"return output...\");\n return out;\n\n } catch (Exception e) {\n LOGGER.error(e.getMessage());\n //throw new Exception(log.toString());\n throw new Exception(e.getMessage());\n }\n\n }\n\n// public OutputBean queryCodes(DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n//\n// /* Logs. */\n// StringBuilder log = new StringBuilder();\n//\n// try {\n//\n// /* Statistics. */\n// LOGGER.info(\"initiate statistics...\");\n// long t0 = System.currentTimeMillis();\n//\n// /* Get domain's dimensions. */\n// List<List<Map<String, Object>>> dimensions = getDomainDimensions(\"dimensions\", datasourceBean, metadataBean);\n//\n// LOGGER.info(dimensions);\n//\n// /* Organize data in an object. */\n// final List<Map<String, Object>> structuredDimensions = organizeDomainDimensions(dimensions);\n//\n// LOGGER.info(structuredDimensions);\n//\n// /* Get the dimension of interest. */\n// Map<String, Object> dimension = null;\n// String dimensionCode = metadataBean.getProcedureParameters().get(\"id\").toString();\n// for (Map<String, Object> d : structuredDimensions) {\n// /* checking if is at dimension level */\n// if (d.get(\"id\").toString().equalsIgnoreCase(dimensionCode)) {\n// LOGGER.info(d.get(\"id\").toString());\n// dimension = d;\n// break;\n// }\n// /* checking if is at subdimension level */\n// ArrayList<Map<String, Object>> subdimensions = (ArrayList<Map<String, Object>>) d.get(\"subdimensions\");\n// for (Map<String, Object> subd : subdimensions) {\n// if (subd.get(\"id\").toString().equalsIgnoreCase(dimensionCode)) {\n// LOGGER.info(subd.get(\"id\").toString());\n// dimension = subd;\n// break;\n// }\n// }\n// }\n//\n// LOGGER.info(\"DimensionCode: \" + dimensionCode);\n// LOGGER.info(\"Dimension: \" + dimension);\n//\n// /* Prepare output. */\n// List<Map<String, Object>> codes = new ArrayList<>();\n// Map<String, Object> row;\n//\n// /* Get subdimensions. */\n// ArrayList<Map<String, Object>> subDimensions = (ArrayList<Map<String, Object>>) dimension.get(\"subdimensions\");\n//\n// LOGGER.info(\"subDimensions: \" + subDimensions);\n//\n// if (subDimensions != null) {\n//\n// /* Fetch codes for each sub-dimension. */\n// for (Map<String, Object> m : subDimensions) {\n//\n// LOGGER.info(\"subDimension: \" + m);\n//\n// /* Define options to fetch codes. */\n// MetadataBean subDimensionOptions = new MetadataBean();\n// subDimensionOptions.addParameter(\"domain_code\", metadataBean.getProcedureParameters().get(\"domain_code\"));\n// subDimensionOptions.addParameter(\"report_code\", metadataBean.getProcedureParameters().get(\"report_code\"));\n// subDimensionOptions.addParameter(\"lang\", metadataBean.getProcedureParameters().get(\"lang\"));\n// subDimensionOptions.addParameter(\"dimension\", m.get(\"ListBoxNo\").toString());\n// subDimensionOptions.addParameter(\"subdimension\", m.get(\"TabOrder\").toString());\n//\n// /* Query codes */\n// JDBCIterable subDimensionIterable = getJDBCIterable(\"codes\", datasourceBean, subDimensionOptions);\n//\n// /* Iterate over codes. */\n// while (subDimensionIterable.hasNext()) {\n// row = createCode(subDimensionIterable.nextMap());\n//\n// LOGGER.info(\"row: \" + row);\n//\n// //row.put(\"subdimension_id\", m.get(\"TabName\").toString().replace(\" \", \"\").toLowerCase());\n// //row.put(\"subdimension_ord\", m.get(\"TabOrder\").toString());\n// //row.put(\"subdimension_label\", m.get(\"TabName\").toString());\n//// log.append(\"\\t\\tcontains \").append(row.get(\"code\").toString().toUpperCase()).append(\"? \").append(Arrays.asList(metadataBean.getBlackList()).contains(row.get(\"code\").toString().toUpperCase()));\n// if (isAdmissibleCode(row, metadataBean)) {\n// //row.remove(\"aggregate_type\");\n// row.remove(\"children\");\n// codes.add(row);\n// }\n// }\n//\n// }\n//\n// } else {\n//\n// /* Fetch codes. */\n// MetadataBean subDimensionOptions = new MetadataBean();\n// subDimensionOptions.addParameter(\"domain_code\", metadataBean.getProcedureParameters().get(\"domain_code\"));\n// subDimensionOptions.addParameter(\"report_code\", metadataBean.getProcedureParameters().get(\"report_code\"));\n// subDimensionOptions.addParameter(\"lang\", metadataBean.getProcedureParameters().get(\"lang\"));\n// subDimensionOptions.addParameter(\"dimension\", dimension.get(\"ListBoxNo\").toString());\n// subDimensionOptions.addParameter(\"subdimension\", dimension.get(\"TabOrder\").toString());\n//\n// /* Query codes. */\n// JDBCIterable subDimensionIterable = getJDBCIterable(\"codes\", datasourceBean, subDimensionOptions);\n//\n//\n// LOGGER.info(\"subDimensionIterable: \" + subDimensionIterable);\n//\n// while (subDimensionIterable.hasNext()) {\n// /* Create code. */\n// row = createCode(subDimensionIterable.nextMap());\n// if (isAdmissibleCode(row, metadataBean)) {\n// codes.add(row);\n// }\n// }\n//\n// }\n//\n// LOGGER.info(\"---Codes\");\n// LOGGER.info(codes);\n//\n// /* Add children. */\n// // TODO: verify is this condition is right. should work on EA/ODA\n// for (Map<String, Object> c1 : codes) {\n// if (c1.get(\"parent\") != null && c1.get(\"parent\") != \"0\") {\n// for (Map<String, Object> c2 : codes) {\n// if (c2.get(\"code\").toString().equalsIgnoreCase(c1.get(\"parent\").toString())) {\n// // TODO: probably should be added children\n// ((ArrayList<Map<String, Object>>) c2.get(\"children\")).add(c1);\n// }\n// }\n// }\n// }\n//\n// /* Group subdimensions, if required and if subdimensions exists. */\n// final List<Map<String, Object>> output = new ArrayList<>();\n// if (subDimensions != null && Boolean.parseBoolean(metadataBean.getProcedureParameters().get(\"group_subdimensions\").toString())) {\n//\n// /* Prepare output. */\n// for (Map<String, Object> m : subDimensions) {\n// Map<String, Object> subdimension = new HashMap<>();\n// subdimension.put(\"metadata\", new HashMap<String, Object>());\n// subdimension.put(\"data\", new ArrayList<HashMap<String, Object>>());\n// output.add(subdimension);\n// }\n//\n// /* Group codes. */\n// String current_id = codes.get(0).get(\"subdimension_id\").toString();\n// String current_ord = codes.get(0).get(\"subdimension_ord\").toString();\n// String current_label = codes.get(0).get(\"subdimension_label\").toString();\n// int current_idx = 0;\n// for (int i = 0; i < codes.size(); i += 1) {\n//\n// /* Current code. */\n// Map<String, Object> c = codes.get(i);\n//\n// if (c.get(\"subdimension_id\").toString().equalsIgnoreCase(current_id)) {\n// ((ArrayList<Map<String, Object>>) output.get(current_idx).get(\"data\")).add(c);\n// } else {\n//\n// /* Write metadata. */\n// ((HashMap<String, Object>) output.get(current_idx).get(\"metadata\")).put(\"id\", current_id);\n// ((HashMap<String, Object>) output.get(current_idx).get(\"metadata\")).put(\"ord\", current_ord);\n// ((HashMap<String, Object>) output.get(current_idx).get(\"metadata\")).put(\"label\", current_label);\n//\n// /* Reset parameters. */\n// current_id = codes.get(i).get(\"subdimension_id\").toString();\n// current_ord = codes.get(i).get(\"subdimension_ord\").toString();\n// current_label = codes.get(i).get(\"subdimension_label\").toString();\n// current_idx += 1;\n// ((ArrayList<Map<String, Object>>) output.get(current_idx).get(\"data\")).add(c);\n//\n// }\n// }\n//\n// /* Write metadata for the last iteration. */\n// ((HashMap<String, Object>) output.get(current_idx).get(\"metadata\")).put(\"id\", current_id);\n// ((HashMap<String, Object>) output.get(current_idx).get(\"metadata\")).put(\"ord\", current_ord);\n// ((HashMap<String, Object>) output.get(current_idx).get(\"metadata\")).put(\"label\", current_label);\n//\n// }\n// /* Add all codes if no grouping required */\n// else {\n// output.addAll(codes);\n// }\n//\n// /* Initiate output. */\n// LOGGER.info(\"initiate out...\");\n// OutputBean out = new OutputBean(new FAOSTATIterable(output));\n// LOGGER.info(\"initiate out: done\");\n//\n// /* TODO: If CSV works only without grouping at the moment */\n// if (!Boolean.parseBoolean(metadataBean.getProcedureParameters().get(\"group_subdimensions\").toString())) {\n// switch (metadataBean.getOutputType()) {\n// case CSV:\n// for (int i = 0; i < output.size(); i += 1) {\n// List<String> l = new ArrayList<>();\n// l.add(output.get(i).get(\"code\").toString());\n// l.add(output.get(i).get(\"label\").toString());\n// l.add(output.get(i).get(\"ord\").toString());\n// l.add(output.get(i).get(\"description\").toString());\n// l.add(output.get(i).get(\"aggregate_type\").toString());\n// out.getData().addList(l);\n// }\n// out.setColumnNames(new ArrayList<String>());\n// /* TODO: Why hardcoded column names? */\n// out.getColumnNames().add(\"Code\");\n// out.getColumnNames().add(\"Label\");\n// out.getColumnNames().add(\"Order\");\n// out.getColumnNames().add(\"Description\");\n// out.getColumnNames().add(\"Aggregate Type\");\n// break;\n// }\n// }\n//\n// /* Add metadata. */\n// LOGGER.info(\"add metadata...\");\n// LOGGER.info(\"metadataBean != null? \" + (metadataBean != null));\n// LOGGER.info(\"metadataBean.getProcedureParameters() != null? \" + (metadataBean.getProcedureParameters() != null));\n// for (String key : dimension.keySet()) {\n// LOGGER.info(\"dimension: \" + key + \" = \" + dimension.get(key));\n// }\n// LOGGER.info(\"parameter: \" + dimension.get(\"ListBoxNo\"));\n//\n// /* TODO: the 'parameter' for data procedure is fundamental */\n// if (dimension.get(\"ListBoxNo\") != null) {\n// metadataBean.getProcedureParameters().put(\"parameter\", \"List\" + dimension.get(\"ListBoxNo\").toString() + \"Codes\");\n// } else {\n// metadataBean.getProcedureParameters().put(\"parameter\", dimension.get(\"parameter\"));\n// }\n//\n// out.setMetadata(metadataBean);\n// LOGGER.info(\"add metadata... DONE\");\n//\n// /* Statistics. */\n// long tf = System.currentTimeMillis();\n// LOGGER.info(\"set statistics...\");\n// out.getMetadata().setProcessingTime(tf - t0);\n//\n// /* Return output. */\n// LOGGER.info(\"return output...\");\n// return out;\n//\n// } catch (Exception e) {\n// throw new Exception(log.toString());\n// }\n//\n// }\n\n /**\n * Creates a code Object\n */\n private Map<String, Object> createCode(Map<String, Object> row) {\n Map<String, Object> code = new LinkedHashMap<>();\n\n\n code.put(\"code\", row.get(\"Code\"));\n code.put(\"label\", row.get(\"Label\"));\n //code.put(\"ord\", dbRow.get(\"Order\"));\n\n if (row.get(\"Parent\") != null ) {\n String parent = row.get(\"Parent\").toString();\n if (parent.equals(\"0\")) {\n code.put(\"parent\", \"#\");\n } else {\n code.put(\"parent\", parent);\n }\n }\n\n //code.put(\"description\", \"TODO\");\n code.put(\"aggregate_type\", row.get(\"AggregateType\"));\n //code.put(\"children\", new ArrayList<Map<String, Object>>());\n\n return code;\n }\n\n private boolean isAdmissibleCode(Map<String, Object> row, MetadataBean o) {\n\n /* Check wheater the code is a list. */\n // alter aggregate code\n if (row.get(\"aggregate_type\").equals(\">\")) {\n\n /* Overwrite of the code if is an aggregate_type \">\". */\n // TODO: the code should be already formatted from the DB. In theory should be consistent with the check on the code.\n if (!row.get(\"code\").toString().contains(\">\")) {\n row.put(\"code\", row.get(\"code\").toString() + row.get(\"aggregate_type\").toString());\n }\n\n }\n\n if (o.getBlackList() != null && o.getBlackList().size() > 0) {\n if (o.getBlackList().contains(row.get(\"code\").toString())) {\n return false;\n }\n }\n\n if (o.getWhiteList() != null && o.getWhiteList().size() > 0) {\n if (!o.getWhiteList().contains(row.get(\"code\").toString())) {\n return false;\n }\n }\n\n if (row.get(\"aggregate_type\").equals(\">\")) {\n return Boolean.parseBoolean(o.getProcedureParameters().get(\"show_lists\").toString());\n }\n\n return true;\n }\n\n private List<List<Map<String, Object>>> getDomainDimensions(String queryCode, DatasourceBean datasourceBean, MetadataBean o) throws Exception {\n\n //System.out.println(\"getDomainDimensions: \" + queryCode + \" \" + o);\n\n /* Query the DB. */\n try {\n JDBCIterable i = getJDBCIterable(queryCode, datasourceBean, o);\n\n /* Store the original result. */\n List<Map<String, Object>> l = new ArrayList<>();\n while (i.hasNext()) {\n Map<String, Object> m = i.nextMap();\n l.add(m);\n }\n\n /* Initiate variables. */\n List<List<Map<String, Object>>> dimensions = new ArrayList<>();\n\n /* Create groups. */\n List<Map<String, Object>> groups = new ArrayList<>();\n String current = \"1\";\n for (Map<String, Object> m : l) {\n // m.put(\"id\", m.get(\"TabName\").toString().replaceAll(\" \", \"\").toLowerCase());\n\n // TODO: based on the TabID and ListBoxNo?\n //m.put(\"id\", m.get(\"TabID\").toString().replaceAll(\" \", \"\").toLowerCase());\n m.put(\"id\", m.get(\"VarSubType\"));\n if (m.get(\"ListBoxNo\").toString().equalsIgnoreCase(current)) {\n groups.add(m);\n } else {\n dimensions.add(groups);\n current = m.get(\"ListBoxNo\").toString();\n groups = new ArrayList<>();\n groups.add(m);\n }\n }\n dimensions.add(groups);\n\n //LOGGER.info(\"DIMENSIONS:\" + dimensions);\n\n /* Return output. */\n return dimensions;\n\n }catch (Exception e) {\n throw new Exception(e);\n }\n\n }\n\n private List<Map<String, Object>> organizeDomainDimensions(List<List<Map<String, Object>>> dimensions) {\n List<Map<String, Object>> out = new ArrayList<>();\n// List<String> idsBuffer = new ArrayList<>();\n for (List<Map<String, Object>> dimension : dimensions) {\n Map<String, Object> tmp = new HashMap<>();\n/* if (!idsBuffer.contains(dimension.get(0).get(\"VarType\"))) {\n idsBuffer.add(dimension.get(0).get(\"VarType\").toString());\n tmp.put(\"id\", dimension.get(0).get(\"VarType\"));\n } else {\n tmp.put(\"id\", dimension.get(0).get(\"VarType\"));\n }*/\n\n tmp.put(\"id\", dimension.get(0).get(\"VarType\"));\n tmp.put(\"ord\", dimension.get(0).get(\"ListBoxNo\"));\n tmp.put(\"label\", \"TODO\");\n tmp.put(\"description\", \"TODO\");\n tmp.put(\"parameter\", \"List\" + dimension.get(0).get(\"ListBoxNo\") + \"Codes\");\n tmp.put(\"href\", \"/codes/\" + dimension.get(0).get(\"VarType\") + \"/\");\n tmp.put(\"subdimensions\", new ArrayList<Map<String, Object>>());\n for (Map<String, Object> subdimension : dimension) {\n LOGGER.info(subdimension);\n ((ArrayList)tmp.get(\"subdimensions\")).add(subdimension);\n }\n out.add(tmp);\n }\n LOGGER.info(out);\n return out;\n }\n\n private boolean isAdmissibleDBRow(Map<String, Object> row, MetadataBean o) {\n\n LOGGER.info(row);\n LOGGER.info(o);\n /* Check the blacklist. */\n if (o.getBlackList() != null && o.getBlackList().size() > 0) {\n if (o.getBlackList().contains(row.get(\"code\").toString().toUpperCase())) {\n return false;\n }\n }\n\n /* Check the whitelist. */\n if (o.getWhiteList() != null && o.getWhiteList().size() > 0) {\n if (!o.getWhiteList().contains(row.get(\"code\").toString().toUpperCase())) {\n return false;\n }\n }\n\n /* Return. */\n return true;\n\n }\n\n public List<Map<String, Object>> createDSD(DatasourceBean datasourceBean, MetadataBean o) {\n\n LOGGER.info(\"DSD\");\n\n /* Initiate DSD. */\n List<Map<String, Object>> dsd = new ArrayList<Map<String, Object>>();\n JDBCIterable i;\n\n /* Store original result. */\n Map<String, Object> original = new LinkedHashMap<String, Object>();\n original.put(\"original\", new ArrayList<Map<String, Object>>());\n\n /* Get the first domain code from the metadata bean. */\n // TODO: check if domain_code or domain_codes\n String domain_code = \"\";\n if (o.getProcedureParameters().containsKey(\"domain_codes\")) {\n domain_code = ((List<String>)o.getProcedureParameters().get(\"domain_codes\")).get(0);\n }\n else if (o.getProcedureParameters().containsKey(\"domain_code\")) {\n domain_code = String.valueOf(o.getProcedureParameters().get(\"domain_code\"));\n }\n else{\n LOGGER.error(\"No domain_code or domain_codes found: \" + o.getProcedureParameters());\n throw new Error(\"createDSD. Mo domain_code or domain_codes found:\");\n }\n\n o.addParameter(\"domain_code\", domain_code);\n\n\n Boolean addCodes = true;\n if ( o.getProcedureParameters().get(\"show_codes\") != null) {\n addCodes = o.getProcedureParameters().get(\"show_codes\").equals(1);\n }\n Boolean addFlags = true;\n if ( o.getProcedureParameters().get(\"show_flags\") != null) {\n addFlags = o.getProcedureParameters().get(\"show_flags\").equals(1);\n }\n\n Boolean addUnit = true;\n if ( o.getProcedureParameters().get(\"show_unit\") != null) {\n addUnit = o.getProcedureParameters().get(\"show_unit\").equals(1);\n }\n Boolean addPivot = false;\n if (o.getPivot() != null) {\n addPivot = o.getPivot();\n }\n\n // TODO: use an enumeration\n LOGGER.info(\"Show Codes: \" + addCodes);\n LOGGER.info(\"Show Flags: \" + addFlags);\n LOGGER.info(\"Show Units: \" + addUnit);\n LOGGER.info(\"Pivot: \" + addPivot);\n\n try {\n\n /* Query DB. */\n i = getJDBCIterable(\"data_structure\", datasourceBean, o);\n\n /* Iterate over results. */\n while (i.hasNext()) {\n\n LinkedHashMap<String, Object> row = (LinkedHashMap<String, Object>) i.nextMap();\n ((ArrayList<Map<String, Object>>)original.get(\"original\")).add(row);\n\n //LOGGER.info(row);\n\n /* Create descriptors for code and label columns. */\n if (!row.get(\"Col\").toString().equalsIgnoreCase(\"Unit\") && !row.get(\"Col\").toString().equalsIgnoreCase(\"Flag\") && !row.get(\"Col\").toString().equalsIgnoreCase(\"Value\")) {\n\n // if show_codes\n if(addCodes.equals(true)) {\n LinkedHashMap<String, Object> codeCol = new LinkedHashMap<>();\n //codeCol.put(\"index\", Integer.parseInt(row.get(\"CodeIndex\").toString()));\n codeCol.put(\"label\", row.get(\"CodeName\"));\n codeCol.put(\"type\", \"code\");\n codeCol.put(\"key\", row.get(\"CodeName\"));\n if (addPivot.equals(true)) {\n codeCol.put(\"pivot\", row.get(\"Pivot\"));\n }\n if (row.get(\"VarType\") != null && row.get(\"VarType\").toString().length() > 0) {\n codeCol.put(\"dimension_id\", row.get(\"VarType\"));\n }\n dsd.add(codeCol);\n }\n\n // adding label\n LinkedHashMap<String, Object> labelCol = new LinkedHashMap<>();\n //labelCol.put(\"index\", Integer.parseInt(row.get(\"NameIndex\").toString()));\n labelCol.put(\"label\", row.get(\"ColName\"));\n labelCol.put(\"type\", \"label\");\n labelCol.put(\"key\", row.get(\"ColName\"));\n if (addPivot.equals(true)) {\n labelCol.put(\"pivot\", row.get(\"Pivot\"));\n }\n if (row.get(\"VarType\") != null && row.get(\"VarType\").toString().length() > 0) {\n labelCol.put(\"dimension_id\", row.get(\"VarType\"));\n }\n dsd.add(labelCol);\n }\n\n /* Create descriptor for the unit. */\n if(addUnit.equals(true)) {\n if (row.get(\"Col\").toString().equalsIgnoreCase(\"Unit\")) {\n LinkedHashMap<String, Object> unitCol = new LinkedHashMap<>();\n //unitCol.put(\"index\", Integer.parseInt(row.get(\"NameIndex\").toString()));\n switch (o.getProcedureParameters().get(\"lang\").toString()) {\n case \"E\":\n unitCol.put(\"label\", \"Unit\");\n unitCol.put(\"key\", \"Unit\");\n break;\n case \"F\":\n unitCol.put(\"label\", \"Unité\");\n unitCol.put(\"key\", \"Unité\");\n break;\n case \"S\":\n unitCol.put(\"label\", \"Unidad\");\n unitCol.put(\"key\", \"Unidad\");\n break;\n }\n unitCol.put(\"type\", \"unit\");\n unitCol.put(\"dimension_id\", \"unit\");\n if (addPivot.equals(true)) {\n unitCol.put(\"pivot\", row.get(\"Pivot\"));\n }\n dsd.add(unitCol);\n }\n }\n\n /* Create descriptor for the flag. */\n if(addFlags.equals(true)) {\n if (row.get(\"Col\").toString().equalsIgnoreCase(\"Flag\")) {\n LinkedHashMap<String, Object> flagCol = new LinkedHashMap<>();\n\n if(addCodes.equals(true)) {\n //flagCol.put(\"index\", Integer.parseInt(row.get(\"CodeIndex\").toString()));\n }\n switch (o.getProcedureParameters().get(\"lang\").toString()) {\n case \"E\":\n flagCol.put(\"label\", \"Flag\");\n flagCol.put(\"key\", \"Flag\");\n break;\n case \"F\":\n flagCol.put(\"label\", \"Symbole\");\n flagCol.put(\"key\", \"Symbole\");\n break;\n case \"S\":\n flagCol.put(\"label\", \"Símbolo\");\n flagCol.put(\"key\", \"Símbolo\");\n break;\n }\n flagCol.put(\"type\", \"flag\");\n flagCol.put(\"dimension_id\", \"flag\");\n if (addPivot.equals(true)) {\n flagCol.put(\"pivot\", row.get(\"Pivot\"));\n }\n dsd.add(flagCol);\n\n LinkedHashMap<String, Object> labelCol = new LinkedHashMap<>();\n //labelCol.put(\"index\", Integer.parseInt(row.get(\"NameIndex\").toString()));\n labelCol.put(\"label\", row.get(\"ColName\"));\n // labelCol.put(\"type\", \"flag\");\n // labelCol.put(\"type\", \"label\");\n labelCol.put(\"type\", \"flag_label\");\n labelCol.put(\"key\", row.get(\"ColName\"));\n labelCol.put(\"dimension_id\", \"flag\");\n if (addPivot.equals(true)) {\n labelCol.put(\"pivot\", row.get(\"Pivot\"));\n }\n dsd.add(labelCol);\n }\n }\n\n /* Create descriptor for the value. */\n if (row.get(\"Col\").toString().equalsIgnoreCase(\"Value\")) {\n// LOGGER.info(row);\n LinkedHashMap<String, Object> valueCol = new LinkedHashMap<>();\n //valueCol.put(\"index\", Integer.parseInt(row.get(\"NameIndex\").toString()));\n valueCol.put(\"label\", row.get(\"ColName\").toString());\n valueCol.put(\"type\", \"value\");\n valueCol.put(\"key\", row.get(\"ColName\").toString());\n valueCol.put(\"dimension_id\", \"value\");\n if (addPivot.equals(true)) {\n valueCol.put(\"pivot\", row.get(\"Pivot\"));\n }\n dsd.add(valueCol);\n }\n\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n /* Add original. */\n// dsd.add(original);\n\n /* Return DSD. */\n return dsd;\n\n }\n\n private JDBCIterable getJDBCIterable(String queryCode, DatasourceBean datasourceBean, MetadataBean o) throws Exception {\n\n\n long t0 = System.currentTimeMillis();\n\n LOGGER.info(\"getJDBCIterable.queryCode: \" + queryCode);\n LOGGER.info(\"getJDBCIterable.getJDBCIterable: \" + o.getProcedureParameters());\n\n String query = this.getQueries().getQuery(queryCode, o.getProcedureParameters());\n\n LOGGER.info(\"getJDBCIterable.QUERY: \" + query);\n JDBCIterable i = new JDBCIterable();\n try {\n i.query(datasourceBean, query);\n }catch (Exception e) {\n throw new Exception(e);\n }\n\n long tf = System.currentTimeMillis();\n // LOGGER.info(\"Query time: \" + (tf - t0));\n\n return i;\n }\n\n public String iso2faostat(String lang) {\n switch (lang.toLowerCase()) {\n case \"fr\": return \"F\";\n case \"es\": return \"S\";\n case \"ar\": return \"A\";\n case \"zh\": return \"C\";\n case \"ru\": return \"R\";\n default: return \"E\";\n }\n }\n\n public void setQueries(QUERIES queries) {\n this.queries = queries;\n }\n\n public QUERIES getQueries() {\n return queries;\n }\n\n}", "public class StreamBuilder {\n\n private static final Logger LOGGER = Logger.getLogger(StreamBuilder.class);\n\n\n public StreamingOutput createOutputStream(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws WebApplicationException {\n\n /* Log. */\n final StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n try {\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.query(queryCode, datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n public StreamingOutput createOutputSearch(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws WebApplicationException {\n\n /* Log. */\n final StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n try {\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.querySearch(queryCode, datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n public StreamingOutput createOutputStreamRankings(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws WebApplicationException {\n\n /* Log. */\n final StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n try {\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.queryRankings(queryCode, datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n // TODO: make it more generic\n private StreamingOutput exceptionHandler(final Exception e, final StringBuilder log) {\n LOGGER.error(e + \" \" + log);\n throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);\n /* return new StreamingOutput() {\n @Override\n public void write(OutputStream os) throws IOException, WebApplicationException {\n Writer writer = new BufferedWriter(new OutputStreamWriter(os));\n writer.write(log.toString());\n if (e.getMessage() != null) {\n writer.write(e.getMessage());\n }\n writer.flush();\n writer.close();\n }\n };*/\n }\n\n private StreamingOutput createOutputStreamCSV(final OutputBean out) throws Exception {\n\n /* Initiate the output stream. */\n return new StreamingOutput() {\n\n @Override\n public void write(OutputStream os) throws IOException, WebApplicationException {\n\n /* Initiate the buffer writer. */\n Writer writer = new BufferedWriter(new OutputStreamWriter(os));\n\n /* Add column names, from DSD (if any)... */\n for (int i = 0; i < out.getColumnNames().size(); i += 1) {\n writer.write(\"\\\"\" + out.getColumnNames().get(i) + \"\\\"\");\n if (i < out.getColumnNames().size() - 1) {\n writer.write(\",\");\n }\n else {\n writer.write(\"\\n\");\n }\n }\n\n /* Add data. */\n while (out.getData().hasNextList()) {\n List<String> l = out.getData().nextList();\n for (int i = 0; i < l.size(); i += 1) {\n writer.write(\"\\\"\" + l.get(i) + \"\\\"\");\n if (i < l.size() - 1) {\n writer.write(\",\");\n }\n else {\n writer.write(\"\\n\");\n }\n }\n }\n\n /* Flush the writer. */\n writer.flush();\n\n /* Close the writer. */\n writer.close();\n\n }\n\n };\n\n }\n\n private StreamingOutput createOutputStreamJSON(final OutputBean out) throws Exception {\n\n /* Initiate the output stream. */\n return new StreamingOutput() {\n\n @Override\n public void write(OutputStream os) throws IOException, WebApplicationException {\n\n /* Initiate the buffer writer. */\n Writer writer = new BufferedWriter(new OutputStreamWriter(os));\n\n /* Initiate the output. */\n writer.write(\"{\");\n\n /* Add metadata. */\n writer.write(createMetadata(out.getMetadata()));\n\n /* Initiate the array. */\n writer.write(\"\\\"data\\\": [\");\n\n /* Generate an array of objects of arrays. */\n switch (out.getMetadata().getOutputType()) {\n\n case ARRAYS:\n while (out.getData().hasNext()) {\n writer.write(out.getData().nextJSONList());\n if (out.getData().hasNext()) {\n writer.write(\",\");\n }\n }\n break;\n default:\n while (out.getData().hasNext()) {\n writer.write(out.getData().nextJSON());\n if (out.getData().hasNext()) {\n writer.write(\",\");\n }\n }\n break;\n\n }\n\n /* Close the array. */\n writer.write(\"]\");\n\n /* Close the object. */\n writer.write(\"}\");\n\n /* Flush the writer. */\n writer.flush();\n\n /* Close the writer. */\n writer.close();\n\n }\n\n };\n\n }\n\n public StreamingOutput createDomainsOutputStream(String queryCode, DatasourceBean datasourceBean, final MetadataBean metadataBean) throws Exception {\n\n /* Log. */\n final StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n try {\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.queryDomains(queryCode, datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n public StreamingOutput createGroupsOutputStream(String queryCode, DatasourceBean datasourceBean, final MetadataBean metadataBean) throws Exception {\n\n /* Log. */\n final StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n log.append(\"StreamBuilder\\t\").append(\"initiate api...\").append(\"\\n\");\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n log.append(\"StreamBuilder\\t\").append(\"initiate api: done\").append(\"\\n\");\n\n try {\n\n /* Query FAOSTAT. */\n log.append(\"StreamBuilder\\t\").append(\"initiate output...\").append(\"\\n\");\n final OutputBean out = faostatapiCore.queryGroups(queryCode, datasourceBean, metadataBean);\n log.append(\"StreamBuilder\\t\").append(\"initiate output: done\").append(\"\\n\");\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n public StreamingOutput createCodesOutputStream(final DatasourceBean datasourceBean, final MetadataBean metadataBean) throws Exception {\n\n /* Log. */\n final StringBuilder log = new StringBuilder();\n\n try {\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.queryCodes(datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n public StreamingOutput createDimensionOutputStream(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Log. */\n StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n try {\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.queryDimensions(queryCode, datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n public StreamingOutput createDefinitionsDomainOutputStream(String queryCode, DatasourceBean datasourceBean, MetadataBean metadataBean) throws Exception {\n\n /* Log. */\n StringBuilder log = new StringBuilder();\n\n /* Initiate core library. */\n FAOSTATAPICore faostatapiCore = new FAOSTATAPICore();\n\n try {\n\n /* Query FAOSTAT. */\n final OutputBean out = faostatapiCore.queryDefinitions(queryCode, datasourceBean, metadataBean);\n\n /* Switch the output format. */\n return formatOutput(out);\n\n } catch (final Exception e) {\n return exceptionHandler(e, log);\n }\n\n }\n\n private StreamingOutput formatOutput(OutputBean out) throws Exception {\n switch (out.getMetadata().getOutputType()) {\n case JSON:\n return createOutputStreamJSON(out);\n case OBJECTS:\n return createOutputStreamJSON(out);\n case ARRAYS:\n return createOutputStreamJSON(out);\n case CSV:\n return createOutputStreamCSV(out);\n default:\n throw new WebApplicationException(400);\n }\n }\n\n public String createMetadata(MetadataBean o) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"\\\"metadata\\\": {\");\n if (o.getProcessingTime() != null) {\n sb.append(\"\\\"processing_time\\\": \").append(o.getProcessingTime()).append(\",\");\n }\n\n if (o.getDsd() != null && o.getDsd().size() > 0) {\n sb.append(\"\\\"dsd\\\": [\");\n for (int a = 0; a < o.getDsd().size(); a += 1) {\n sb.append(\"{\");\n LinkedHashMap<String, Object> col = (LinkedHashMap<String, Object>)o.getDsd().get(a);\n int counter = 0;\n for (String key : col.keySet()) {\n sb.append(\"\\\"\").append(key).append(\"\\\": \\\"\").append(col.get(key)).append(\"\\\"\");\n if (counter < col.keySet().size() - 1) {\n sb.append(\",\");\n }\n counter += 1;\n }\n sb.append(\"}\");\n if (a < o.getDsd().size() - 1)\n sb.append(\",\");\n }\n sb.append(\"],\");\n }\n //sb.append(\"\\\"datasource\\\": \\\"\").append(o.getDatasource()).append(\"\\\",\");\n sb.append(\"\\\"output_type\\\": \\\"\").append(o.getOutputType()).append(\"\\\"\");\n //sb.append(\"\\\"api_key\\\": \\\"\").append(o.getApiKey()).append(\"\\\",\");\n //sb.append(\"\\\"client_key\\\": \\\"\").append(o.getClientKey());\n //sb.append(\"\\\"client_key\\\": \\\"\").append(o.getClientKey()).append(\"\\\",\");\n /*sb.append(\"\\\"parameters\\\": {\");\n int count = 0;\n for (String key : o.getProcedureParameters().keySet()) {\n sb.append(\"\\\"\").append(key).append(\"\\\": \\\"\").append(o.getProcedureParameters().get(key)).append(\"\\\"\");\n if (count < o.getProcedureParameters().keySet().size() - 1) {\n sb.append(\",\");\n count++;\n }\n }*/\n// sb.append(\"}\");\n sb.append(\"},\");\n return sb.toString();\n }\n\n public String createMetadataBackup(MetadataBean o) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"\\\"metadata\\\": {\");\n if (o.getProcessingTime() != null) {\n sb.append(\"\\\"processing_time\\\": \").append(o.getProcessingTime()).append(\",\");\n }\n\n if (o.getDsd() != null && o.getDsd().size() > 0) {\n sb.append(\"\\\"dsd\\\": [\");\n for (int a = 0; a < o.getDsd().size(); a += 1) {\n sb.append(\"{\");\n HashMap<String, Object> col = (HashMap<String, Object>)o.getDsd().get(a);\n int counter = 0;\n for (String key : col.keySet()) {\n sb.append(\"\\\"\").append(key).append(\"\\\": \\\"\").append(col.get(key)).append(\"\\\"\");\n if (counter < col.keySet().size() - 1) {\n sb.append(\",\");\n }\n counter += 1;\n }\n sb.append(\"}\");\n if (a < o.getDsd().size() - 1)\n sb.append(\",\");\n }\n sb.append(\"],\");\n }\n\n sb.append(\"\\\"datasource\\\": \\\"\").append(o.getDatasource()).append(\"\\\",\");\n sb.append(\"\\\"output_type\\\": \\\"\").append(o.getOutputType()).append(\"\\\",\");\n sb.append(\"\\\"api_key\\\": \\\"\").append(o.getApiKey()).append(\"\\\",\");\n sb.append(\"\\\"client_key\\\": \\\"\").append(o.getClientKey());\n sb.append(\"\\\"client_key\\\": \\\"\").append(o.getClientKey()).append(\"\\\",\");\n sb.append(\"\\\"parameters\\\": {\");\n int count = 0;\n for (String key : o.getProcedureParameters().keySet()) {\n sb.append(\"\\\"\").append(key).append(\"\\\": \\\"\").append(o.getProcedureParameters().get(key)).append(\"\\\"\");\n if (count < o.getProcedureParameters().keySet().size() - 1) {\n sb.append(\",\");\n count++;\n }\n }\n sb.append(\"}\");\n sb.append(\"},\");\n return sb.toString();\n }\n\n}", "public enum OUTPUTTYPE {\n\n ARRAYS, CSV, JSON, OBJECTS;\n\n}" ]
import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import org.fao.faostat.api.core.beans.DatasourceBean; import org.fao.faostat.api.core.beans.MetadataBean; import org.fao.faostat.api.core.FAOSTATAPICore; import org.fao.faostat.api.core.StreamBuilder; import org.fao.faostat.api.core.constants.OUTPUTTYPE; import org.springframework.stereotype.Component; import javax.ws.rs.*; import javax.ws.rs.core.MediaType;
/** * GNU GENERAL PUBLIC LICENSE * Version 2, June 1991 * <p/> * Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/> * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * Everyone is permitted to copy and distribute verbatim copies * of this license document, but changing it is not allowed. * <p/> * Preamble * <p/> * The licenses for most software are designed to take away your * freedom to share and change it. By contrast, the GNU General Public * License is intended to guarantee your freedom to share and change free * software--to make sure the software is free for all its users. This * General Public License applies to most of the Free Software * Foundation's software and to any other program whose authors commit to * using it. (Some other Free Software Foundation software is covered by * the GNU Lesser General Public License instead.) You can apply it to * your programs, too. * <p/> * When we speak of free software, we are referring to freedom, not * price. Our General Public Licenses are designed to make sure that you * have the freedom to distribute copies of free software (and charge for * this service if you wish), that you receive source code or can get it * if you want it, that you can change the software or use pieces of it * in new free programs; and that you know you can do these things. * <p/> * To protect your rights, we need to make restrictions that forbid * anyone to deny you these rights or to ask you to surrender the rights. * These restrictions translate to certain responsibilities for you if you * distribute copies of the software, or if you modify it. * <p/> * For example, if you distribute copies of such a program, whether * gratis or for a fee, you must give the recipients all the rights that * you have. You must make sure that they, too, receive or can get the * source code. And you must show them these terms so they know their * rights. * <p/> * We protect your rights with two steps: (1) copyright the software, and * (2) offer you this license which gives you legal permission to copy, * distribute and/or modify the software. * <p/> * Also, for each author's protection and ours, we want to make certain * that everyone understands that there is no warranty for this free * software. If the software is modified by someone else and passed on, we * want its recipients to know that what they have is not the original, so * that any problems introduced by others will not reflect on the original * authors' reputations. * <p/> * Finally, any free program is threatened constantly by software * patents. We wish to avoid the danger that redistributors of a free * program will individually obtain patent licenses, in effect making the * program proprietary. To prevent this, we have made it clear that any * patent must be licensed for everyone's free use or not licensed at all. * <p/> * The precise terms and conditions for copying, distribution and * modification follow. * <p/> * GNU GENERAL PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * <p/> * 0. This License applies to any program or other work which contains * a notice placed by the copyright holder saying it may be distributed * under the terms of this General Public License. The "Program", below, * refers to any such program or work, and a "work based on the Program" * means either the Program or any derivative work under copyright law: * that is to say, a work containing the Program or a portion of it, * either verbatim or with modifications and/or translated into another * language. (Hereinafter, translation is included without limitation in * the term "modification".) Each licensee is addressed as "you". * <p/> * Activities other than copying, distribution and modification are not * covered by this License; they are outside its scope. The act of * running the Program is not restricted, and the output from the Program * is covered only if its contents constitute a work based on the * Program (independent of having been made by running the Program). * Whether that is true depends on what the Program does. * <p/> * 1. You may copy and distribute verbatim copies of the Program's * source code as you receive it, in any medium, provided that you * conspicuously and appropriately publish on each copy an appropriate * copyright notice and disclaimer of warranty; keep intact all the * notices that refer to this License and to the absence of any warranty; * and give any other recipients of the Program a copy of this License * along with the Program. * <p/> * You may charge a fee for the physical act of transferring a copy, and * you may at your option offer warranty protection in exchange for a fee. * <p/> * 2. You may modify your copy or copies of the Program or any portion * of it, thus forming a work based on the Program, and copy and * distribute such modifications or work under the terms of Section 1 * above, provided that you also meet all of these conditions: * <p/> * a) You must cause the modified files to carry prominent notices * stating that you changed the files and the date of any change. * <p/> * b) You must cause any work that you distribute or publish, that in * whole or in part contains or is derived from the Program or any * part thereof, to be licensed as a whole at no charge to all third * parties under the terms of this License. * <p/> * c) If the modified program normally reads commands interactively * when run, you must cause it, when started running for such * interactive use in the most ordinary way, to print or display an * announcement including an appropriate copyright notice and a * notice that there is no warranty (or else, saying that you provide * a warranty) and that users may redistribute the program under * these conditions, and telling the user how to view a copy of this * License. (Exception: if the Program itself is interactive but * does not normally print such an announcement, your work based on * the Program is not required to print an announcement.) * <p/> * These requirements apply to the modified work as a whole. If * identifiable sections of that work are not derived from the Program, * and can be reasonably considered independent and separate works in * themselves, then this License, and its terms, do not apply to those * sections when you distribute them as separate works. But when you * distribute the same sections as part of a whole which is a work based * on the Program, the distribution of the whole must be on the terms of * this License, whose permissions for other licensees extend to the * entire whole, and thus to each and every part regardless of who wrote it. * <p/> * Thus, it is not the intent of this section to claim rights or contest * your rights to work written entirely by you; rather, the intent is to * exercise the right to control the distribution of derivative or * collective works based on the Program. * <p/> * In addition, mere aggregation of another work not based on the Program * with the Program (or with a work based on the Program) on a volume of * a storage or distribution medium does not bring the other work under * the scope of this License. * <p/> * 3. You may copy and distribute the Program (or a work based on it, * under Section 2) in object code or executable form under the terms of * Sections 1 and 2 above provided that you also do one of the following: * <p/> * a) Accompany it with the complete corresponding machine-readable * source code, which must be distributed under the terms of Sections * 1 and 2 above on a medium customarily used for software interchange; or, * <p/> * b) Accompany it with a written offer, valid for at least three * years, to give any third party, for a charge no more than your * cost of physically performing source distribution, a complete * machine-readable copy of the corresponding source code, to be * distributed under the terms of Sections 1 and 2 above on a medium * customarily used for software interchange; or, * <p/> * c) Accompany it with the information you received as to the offer * to distribute corresponding source code. (This alternative is * allowed only for noncommercial distribution and only if you * received the program in object code or executable form with such * an offer, in accord with Subsection b above.) * <p/> * The source code for a work means the preferred form of the work for * making modifications to it. For an executable work, complete source * code means all the source code for all modules it contains, plus any * associated interface definition files, plus the scripts used to * control compilation and installation of the executable. However, as a * special exception, the source code distributed need not include * anything that is normally distributed (in either source or binary * form) with the major components (compiler, kernel, and so on) of the * operating system on which the executable runs, unless that component * itself accompanies the executable. * <p/> * If distribution of executable or object code is made by offering * access to copy from a designated place, then offering equivalent * access to copy the source code from the same place counts as * distribution of the source code, even though third parties are not * compelled to copy the source along with the object code. * <p/> * 4. You may not copy, modify, sublicense, or distribute the Program * except as expressly provided under this License. Any attempt * otherwise to copy, modify, sublicense or distribute the Program is * void, and will automatically terminate your rights under this License. * However, parties who have received copies, or rights, from you under * this License will not have their licenses terminated so long as such * parties remain in full compliance. * <p/> * 5. You are not required to accept this License, since you have not * signed it. However, nothing else grants you permission to modify or * distribute the Program or its derivative works. These actions are * prohibited by law if you do not accept this License. Therefore, by * modifying or distributing the Program (or any work based on the * Program), you indicate your acceptance of this License to do so, and * all its terms and conditions for copying, distributing or modifying * the Program or works based on it. * <p/> * 6. Each time you redistribute the Program (or any work based on the * Program), the recipient automatically receives a license from the * original licensor to copy, distribute or modify the Program subject to * these terms and conditions. You may not impose any further * restrictions on the recipients' exercise of the rights granted herein. * You are not responsible for enforcing compliance by third parties to * this License. * <p/> * 7. If, as a consequence of a court judgment or allegation of patent * infringement or for any other reason (not limited to patent issues), * conditions are imposed on you (whether by court order, agreement or * otherwise) that contradict the conditions of this License, they do not * excuse you from the conditions of this License. If you cannot * distribute so as to satisfy simultaneously your obligations under this * License and any other pertinent obligations, then as a consequence you * may not distribute the Program at all. For example, if a patent * license would not permit royalty-free redistribution of the Program by * all those who receive copies directly or indirectly through you, then * the only way you could satisfy both it and this License would be to * refrain entirely from distribution of the Program. * <p/> * If any portion of this section is held invalid or unenforceable under * any particular circumstance, the balance of the section is intended to * apply and the section as a whole is intended to apply in other * circumstances. * <p/> * It is not the purpose of this section to induce you to infringe any * patents or other property right claims or to contest validity of any * such claims; this section has the sole purpose of protecting the * integrity of the free software distribution system, which is * implemented by public license practices. Many people have made * generous contributions to the wide range of software distributed * through that system in reliance on consistent application of that * system; it is up to the author/donor to decide if he or she is willing * to distribute software through any other system and a licensee cannot * impose that choice. * <p/> * This section is intended to make thoroughly clear what is believed to * be a consequence of the rest of this License. * <p/> * 8. If the distribution and/or use of the Program is restricted in * certain countries either by patents or by copyrighted interfaces, the * original copyright holder who places the Program under this License * may add an explicit geographical distribution limitation excluding * those countries, so that distribution is permitted only in or among * countries not thus excluded. In such case, this License incorporates * the limitation as if written in the body of this License. * <p/> * 9. The Free Software Foundation may publish revised and/or new versions * of the General Public License from time to time. Such new versions will * be similar in spirit to the present version, but may differ in detail to * address new problems or concerns. * <p/> * Each version is given a distinguishing version number. If the Program * specifies a version number of this License which applies to it and "any * later version", you have the option of following the terms and conditions * either of that version or of any later version published by the Free * Software Foundation. If the Program does not specify a version number of * this License, you may choose any version ever published by the Free Software * Foundation. * <p/> * 10. If you wish to incorporate parts of the Program into other free * programs whose distribution conditions are different, write to the author * to ask for permission. For software which is copyrighted by the Free * Software Foundation, write to the Free Software Foundation; we sometimes * make exceptions for this. Our decision will be guided by the two goals * of preserving the free status of all derivatives of our free software and * of promoting the sharing and reuse of software generally. * <p/> * NO WARRANTY * <p/> * 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY * FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN * OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES * PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED * OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS * TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE * PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, * REPAIR OR CORRECTION. * <p/> * 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING * WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR * REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING * OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED * TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY * YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * <p/> * END OF TERMS AND CONDITIONS * <p/> * How to Apply These Terms to Your New Programs * <p/> * If you develop a new program, and you want it to be of the greatest * possible use to the public, the best way to achieve this is to make it * free software which everyone can redistribute and change under these terms. * <p/> * To do so, attach the following notices to the program. It is safest * to attach them to the start of each source file to most effectively * convey the exclusion of warranty; and each file should have at least * the "copyright" line and a pointer to where the full notice is found. * <p/> * {description} * Copyright (C) {year} {fullname} * <p/> * 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. * <p/> * 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. * <p/> * 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. * <p/> * Also add information on how to contact you by electronic and paper mail. * <p/> * If the program is interactive, make it output a short notice like this * when it starts in an interactive mode: * <p/> * Gnomovision version 69, Copyright (C) year name of author * Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * <p/> * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, the commands you use may * be called something other than `show w' and `show c'; they could even be * mouse-clicks or menu items--whatever suits your program. * <p/> * You should also get your employer (if you work as a programmer) or your * school, if any, to sign a "copyright disclaimer" for the program, if * necessary. Here is a sample; alter the names: * <p/> * Yoyodyne, Inc., hereby disclaims all copyright interest in the program * `Gnomovision' (which makes passes at compilers) written by James Hacker. * <p/> * {signature of Ty Coon}, 1 April 1989 * Ty Coon, President of Vice * <p/> * 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 org.fao.faostat.api.legacy; /** * @author <a href="mailto:[email protected]">Guido Barbaglia</a> * */ @Component @Path("/{lang}/methodologies/{methodology_code}/") //@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") public class V10Methodology { @GET public Response getMethodology(@PathParam("lang") String lang, @PathParam("methodology_code") String methodology_code, @QueryParam("datasource") String datasource, @QueryParam("api_key") String api_key, @QueryParam("client_key") String client_key, @QueryParam("output_type") String output_type) { /* Init Core library. */ FAOSTATAPICore faostatapiCore = new FAOSTATAPICore(); /* Store user preferences. */ MetadataBean metadataBean = new MetadataBean(); metadataBean.storeUserOptions(datasource, api_key, client_key, output_type); /* Store procedure parameters. */ metadataBean.addParameter("lang", faostatapiCore.iso2faostat(lang)); metadataBean.addParameter("methodology_code", methodology_code.toUpperCase()); String produceType = MediaType.APPLICATION_JSON + ";charset=utf-8";
if (metadataBean.getOutputType().equals(OUTPUTTYPE.CSV)) {
4
stephanrauh/BootsFaces-Examples
BootsFacesChess/src/main/java/de/beyondjava/bootsfaces/chess/jsf/Board.java
[ "public interface ChessConstants {\n public static final boolean s_WHITE = true;\n public static final boolean s_BLACK = false;\n public static final int B_EMPTY = 0;\n public static final int W_EMPTY = 1;\n public static final int B_PAWN = 2;\n public static final int W_PAWN = 4;\n public static final int B_ROOK = 6;\n public static final int W_ROOK = 8;\n public static final int B_KNIGHT = 10;\n public static final int W_KNIGHT = 12;\n public static final int B_BISHOP = 14;\n public static final int W_BISHOP = 16;\n public static final int B_QUEEN = 18;\n public static final int W_QUEEN = 20;\n public static final int B_KING = 22;\n public static final int W_KING = 24;\n public static final int[][] INITIAL_BOARD = {{6, 10, 14, 18, 22, 14, 10, 6},\n {2, 2, 2, 2, 2, 2, 2, 2},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {4, 4, 4, 4, 4, 4, 4, 4},\n {8, 12, 16, 20, 24, 16, 12, 8}\n };\n public static final int[] s_MATERIAL_VALUE = {0, 0, // empty fields\n 100, 100, 100, 100, // pawns\n 500, 500, 500, 500, // rooks,\n 275, 275, 275, 275, // knights (Springer)\n 325, 325, 325, 325, // bishops (Läufer)\n 1000, 1000, 1000, 1000, // queens\n 9999, 9999, 9999, 9999 // kings\n };\n public static final String[] COLUMNS = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"};\n public static final String[] ROWS = {\"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\", \"1\"};\n public static final String[] PIECE_NAME = {\"E\" /* en passant */,\n \" \", \" \", \"P\", \"P\", \"P\", \"P\",\n \"R\", \"R\", \"R\", \"R\",\n \"N\", \"N\", \"N\", \"N\",\n \"B\", \"B\", \"B\", \"B\",\n \"Q\", \"Q\", \"Q\", \"Q\",\n \"K\", \"K\", \"K\", \"K\"};\n\n\n public static final int[][] POSITIONAL_VALUES =\n {{0, 10, 20, 30, 30, 20, 10, 0},\n {10, 20, 30, 40, 40, 30, 20, 10},\n {15, 30, 60, 80, 80, 60, 30, 15},\n {20, 40, 70, 100, 100, 70, 40, 20},\n {20, 40, 70, 100, 100, 70, 40, 20},\n {15, 30, 40, 80, 80, 40, 30, 15},\n {10, 20, 30, 40, 40, 30, 20, 10},\n { 0, 10, 20, 30, 30, 20, 10, 0},\n };\n public static final int[][] WHITE_PAWN_POSITION_VALUES =\n {{200, 200, 200, 200, 200, 200, 200, 200},\n {55, 70, 110, 180, 180, 110, 70, 55},\n {45, 60, 90, 160, 160, 90, 60, 45},\n {35, 50, 70, 130, 130, 70, 50, 35},\n {20, 40, 50, 110, 110, 50, 40, 20},\n {15, 30, 40, 50, 50, 40, 30, 15},\n {20, 30, 60, 40, 40, 60, 40, 30},\n {0, 0, 0, 0, 0, 0, 0, 0},\n };\n\n public static final int[] DOUBLE_PAWN_BONUS = {50 /* n/a */,50 /* A+B */,\n 60 /* B+C */,\n 70 /* C+D */,\n 80 /* D+E */,\n 70 /* E + F */,\n 60 /* F + G */,\n 50 /* G + H */};\n}", "public class Move implements Comparable<Move> {\n public int fromColumn;\n public int fromRow;\n public int toColumn;\n public int toRow;\n public int materialValueAfterMove;\n public boolean opponentInCheck;\n public int positionalValue = 0;\n public boolean capture;\n public int piece;\n public int capturedPiece;\n public int boardAfterMove; // used by PrimitiveMoveGenerator\n public int moveValue; // value of the board after the move, according to the possible moves\n\n public Move(int piece, int fromRow, int fromColumn, int toRow, int toColumn, int materialValueAfterMove, boolean opponentInCheck, boolean capture, int capturedPiece) {\n this.piece = piece;\n this.fromColumn = fromColumn;\n this.fromRow = fromRow;\n this.toRow = toRow;\n this.toColumn = toColumn;\n this.materialValueAfterMove = materialValueAfterMove;\n this.opponentInCheck = opponentInCheck;\n this.capture = capture;\n this.capturedPiece = capturedPiece;\n }\n\n @Override\n public int compareTo(Move o) {\n if (null == o) return -1;\n int m = o.materialValueAfterMove - materialValueAfterMove;\n int p = o.positionalValue - positionalValue;\n return -(m + p);\n }\n\n public String getNotation() {\n return getNotation(false);\n }\n\n public String getNotation(boolean enPassant) {\n String check = opponentInCheck ? \"+\" : \" \";\n String s = capture ? \"x\" : \"-\";\n s += PIECE_NAME[capturedPiece + 1];\n if (piece==W_KING && fromRow==7 && toRow==7 && fromColumn==4 && toColumn==6)\n {\n return \"0-0\";\n }\n if (piece==W_KING && fromRow==7 && toRow==7 && fromColumn==4 && toColumn==2)\n {\n return \"0-0-0\";\n }\n if (piece==B_KING && fromRow==0 && toRow==0 && fromColumn==4 && toColumn==6)\n {\n return \"0-0\";\n }\n if (piece==B_KING && fromRow==0 && toRow==0 && fromColumn==4 && toColumn==2)\n {\n return \"0-0-0\";\n }\n String ep=enPassant?\"e.p.\":\"\";\n\n return PIECE_NAME[piece + 1] + COLUMNS[fromColumn] + ROWS[fromRow] + s + COLUMNS[toColumn] + ROWS[toRow] + ep + check;\n }\n\n public String toString() {\n String m = String.format(\"%5d\", materialValueAfterMove);\n String p = String.format(\"%5d\", positionalValue);\n String mv = String.format(\"%5d\", moveValue);\n String s = String.format(\"%5d\", materialValueAfterMove + positionalValue + moveValue);\n return getNotation() + \" Value: M: \" + m + \" P: \" + p + \" Mv:\" + mv + \" Sum: \" + s;\n }\n}", "@ManagedBean\n@SessionScoped\npublic class Settings {\n\tprivate static int lookAhead = 4;\n\tprivate static int movesToConsider = 5;\n\tprivate static boolean multithreading = false;\n\n\tprivate boolean economyMode = true;\n\n\tpublic void unlockPowerMode() {\n\t\tsetEconomyMode(false);\n\t}\n\n\tpublic int getLookAhead() {\n\t\treturn lookAhead;\n\t}\n\n\tpublic void setLookAhead(int lookAhead) {\n\t\tif (isEconomyMode())\n\t\t\tif (lookAhead > 4) {\n\t\t\t\tlookAhead = 4;\n\t\t\t\tFacesContext.getCurrentInstance().addMessage(null,\n\t\t\t\t\t\tnew FacesMessage(\"Maximum look-ahead is 4 in economy mode. Run this application on your own PC to unlock the full power of the chess engine.\"));\n\t\t\t}\n\t\tSettings.lookAhead = lookAhead;\n\t}\n\n\tpublic int getMovesToConsider() {\n\t\treturn movesToConsider;\n\t}\n\n\tpublic void setMovesToConsider(int movesToConsider) {\n\t\tif (isEconomyMode())\n\t\t\tif (movesToConsider > 5) {\n\t\t\t\tmovesToConsider = 5;\n\t\t\t\tFacesContext.getCurrentInstance().addMessage(null,\n\t\t\t\t\t\tnew FacesMessage(\"Maximum value is 5 in economy mode. Run this application on your own PC to unlock the full power of the chess engine.\"));\n\t\t\t}\n\t\tSettings.movesToConsider = movesToConsider;\n\t}\n\n\tpublic boolean isMultithreading() {\n\t\treturn multithreading;\n\t}\n\n\tpublic void setMultithreading(boolean multithreading) {\n\t\tif (isEconomyMode()) {\n\t\t\tif (multithreading) {\n\t\t\t\tmultithreading = false;\n\t\t\t\tFacesContext.getCurrentInstance().addMessage(null,\n\t\t\t\t\t\tnew FacesMessage(\"Can't activate multithreading in economy mode. Run this application on your own PC to unlock the full power of the chess engine.\"));\n\t\t\t}\n\t\t}\n\t\tSettings.multithreading = multithreading;\n\t}\n\n\tpublic boolean isEconomyMode() {\n\t\treturn economyMode;\n\t}\n\n\tpublic void setEconomyMode(boolean economyMode) {\n\t\tthis.economyMode = economyMode;\n\t}\n}", "public class BlackIsCheckMateException extends CheckMateException {\n\n\tprivate static final long serialVersionUID = 1L;\n}", "public class EndOfGameException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n}", "public class StaleMateException extends EndOfGameException {\n\tprivate static final long serialVersionUID = 1L;\n}", "public class WhiteIsCheckMateException extends CheckMateException {\n\tprivate static final long serialVersionUID = 1L;\n}", "public class Chessboard extends ChessboardBasis {\n\n\tpublic Chessboard() {\n super();\n }\n\n public Chessboard(boolean activePlayerIsWhite, ChessboardBasis board) {\n super(activePlayerIsWhite, board);\n }\n\n public Chessboard(boolean activePlayerIsWhite, Piece... pieces) {\n super(activePlayerIsWhite, pieces);\n }\n\n\n public Chessboard(ChessboardBasis oldBoard, int fromRow, int fromColumn, int toRow, int toColumn, int promotedPiece) {\n super(oldBoard, fromRow, fromColumn, toRow, toColumn, promotedPiece);\n }\n\n public Move findBestMove() throws EndOfGameException {\n Chessboard.evaluatedPositions = 0;\n Chessboard.totalTime = 0;\n Settings settings = new Settings();\n long start = System.nanoTime();\n\t\tint[] bestMoves = activePlayerIsWhite ? findBestWhiteMoves(settings.getLookAhead(), settings.getMovesToConsider(), settings.isMultithreading()) \n\t\t\t\t: findBestBlackMoves(settings.getLookAhead(), settings.getMovesToConsider(), settings.isMultithreading());\n Chessboard.realTimeOfCalculation = System.nanoTime() - start;\n// System.out.println(\"Calculation took \" + ((Chessboard.realTimeOfCalculation / 1000) / 1000.0d) + \"ms Evalutated POSITIONAL_VALUES:\" + NumberFormat.getInstance().format( Chessboard.evaluatedPositions));\n// System.out.println(\"evaluation took \" + ((Chessboard.totalTime/1000)/1000) + \" ms\");\n// System.out.println(\"Average evaluation: \" + Chessboard.totalTime/evaluatedPositions + \" ns\") ;\n int move = bestMoves[0];\n int fromRow = (move >> 12) & 0x000F;\n int fromColumn = (move >> 8) & 0x000F;\n int toRow = (move >> 4) & 0x000F;\n int toColumn = move & 0x000F;\n int promotion = (move >> 16) & 0x00FF;\n int capturedValue = (move >> 24);\n\n return new Move(getChessPiece(fromColumn, fromRow), fromRow, fromColumn, toRow, toColumn, 0, false, false, 0);\n }\n\n public int[] findBestBlackMoves(int lookAhead, int movesToConsider, boolean multithreading) throws EndOfGameException {\n Comparator moveComparator = new BlackMoveComparator();\n int[] moves = Arrays.copyOf(blackMoves, numberOfBlackMoves);\n try {\n List<XMove> evaluatedMoves = findBestMovesWithoutRecursion(moves, s_BLACK);\n if (evaluatedMoves.size() == 0) {\n if (isBlackKingThreatened)\n {\n throw new BlackIsCheckMateException();\n }\n if (isWhiteKingThreatened)\n {\n throw new WhiteIsCheckMateException();\n }\n throw new StaleMateException();\n }\n // eliminate silly moves\n if (lookAhead >= 0) {\n evaluatedMoves = findBestBlackMovesRecursively(0, evaluatedMoves.size(), moveComparator, evaluatedMoves, multithreading);\n }\n List<XMove> bestEvaluatedMoves = new ArrayList<>();\n\n if (lookAhead > 0) {\n bestEvaluatedMoves = findBestBlackMovesRecursively(lookAhead, movesToConsider - 1, moveComparator, evaluatedMoves, multithreading);\n } else {\n for (int i = 0; i < evaluatedMoves.size() && bestEvaluatedMoves.size() < movesToConsider; i++) {\n XMove e = (XMove) evaluatedMoves.get(i);\n bestEvaluatedMoves.add(e);\n }\n }\n int size = bestEvaluatedMoves.size();\n// if (size == 0) {\n// System.err.println(\"No possible move left?\");\n// }\n int[] bestMoves = new int[size];\n for (int i = 0; i < movesToConsider && i < size; i++) {\n bestMoves[i] = bestEvaluatedMoves.get(i).move;\n }\n return bestMoves;\n } catch (KingLostException p_checkmate) {\n throw new WhiteIsCheckMateException();\n }\n }\n\n private List<XMove> findBestBlackMovesRecursively(int lookAhead, int movesToConsider, Comparator moveComparator, List<XMove> evaluatedMoves, boolean multithreading) throws EndOfGameException {\n List<XMove> bestEvaluatedMoves;\n if (multithreading)\n bestEvaluatedMoves = findBestBlackMovesRecursivelyMultiThreaded(lookAhead, movesToConsider, evaluatedMoves);\n else\n\n bestEvaluatedMoves = findBestBlackMovesRecursivelySingleThreaded(lookAhead, movesToConsider, evaluatedMoves);\n Collections.sort(bestEvaluatedMoves, moveComparator);\n return bestEvaluatedMoves;\n }\n\n private List<XMove> findBestBlackMovesRecursivelyMultiThreaded(final int lookAhead, final int movesToConsider, final List<XMove> evaluatedMoves) throws EndOfGameException {\n\n final List<XMove> bestEvaluatedMoves = new ArrayList<>();\n int proc = Runtime.getRuntime().availableProcessors();\n int mtc = 0;\n while (mtc<=movesToConsider)\n {\n mtc += proc;\n }\n ExecutorService executor = Executors.newFixedThreadPool(evaluatedMoves.size());\n try {\n List<Future<Object>> list = new ArrayList<Future<Object>>();\n for (int i = 0; i < evaluatedMoves.size() && i < mtc; i++) {\n// for (int i = 0; i < evaluatedMoves.size() && bestEvaluatedMoves.size() < movesToConsider; i++) {\n final XMove e = (XMove) evaluatedMoves.get(i);\n\n Callable<Object> worker = new Callable<Object>() {\n public Object call() throws EndOfGameException {\n try {\n int opponentsMoveToConsider = movesToConsider;\n if (lookAhead <= 0) {\n opponentsMoveToConsider = 1;\n }\n int[] whiteMoves = e.boardAfterMove.findBestWhiteMoves(lookAhead - 1, opponentsMoveToConsider, false);\n convertFirstMoveToXMove(e, whiteMoves);\n synchronized (bestEvaluatedMoves) {\n bestEvaluatedMoves.add(e);\n }\n } catch (BlackIsCheckMateException p_impossibleMove) {\n e.checkmate = true;\n e.whiteTotalValue = 1000000;\n e.blackTotalValue = -1000000;\n bestEvaluatedMoves.add(e);\n } catch (WhiteIsCheckMateException p_winningMove) {\n e.checkmate = true;\n e.whiteTotalValue = -1000000;\n e.blackTotalValue = 1000000;\n bestEvaluatedMoves.add(e);\n // break; // no need to look at the other moves\n }\n catch (EndOfGameException p_stalemate)\n {\n e.stalemate = true;\n e.whiteTotalValue = 0;\n e.blackTotalValue = 0;\n bestEvaluatedMoves.add(e);\n }\n return null;\n }\n };\n Future<Object> submit = executor.submit(worker);\n list.add(submit);\n\n }\n for (Future<Object> future : list) {\n try {\n future.get();\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (ExecutionException e) {\n e.printStackTrace();\n }\n }\n } finally {\n executor.shutdown();\n }\n return bestEvaluatedMoves;\n }\n\n private List<XMove> findBestBlackMovesRecursivelySingleThreaded(int lookAhead, int movesToConsider, List<XMove> evaluatedMoves) throws EndOfGameException {\n List<XMove> bestEvaluatedMoves = new ArrayList<>();\n for (int i = 0; i < evaluatedMoves.size() && bestEvaluatedMoves.size() < movesToConsider; i++) {\n XMove e = (XMove) evaluatedMoves.get(i);\n try {\n int opponentsMoveToConsider = movesToConsider;\n if (lookAhead <= 0) {\n opponentsMoveToConsider = 1;\n }\n int[] whiteMoves = e.boardAfterMove.findBestWhiteMoves(lookAhead - 1, opponentsMoveToConsider, false);\n convertFirstMoveToXMove(e, whiteMoves);\n bestEvaluatedMoves.add(e);\n } catch (BlackIsCheckMateException p_impossibleMove) {\n e.checkmate = true;\n e.whiteTotalValue = 1000000;\n e.blackTotalValue = -1000000;\n bestEvaluatedMoves.add(e);\n } catch (WhiteIsCheckMateException p_winningMove) {\n e.checkmate = true;\n e.whiteTotalValue = -1000000;\n e.blackTotalValue = 1000000;\n bestEvaluatedMoves.add(e);\n // break; // no need to look at the other moves\n }\n catch (EndOfGameException p_stalemate)\n {\n e.stalemate = true;\n e.whiteTotalValue = 0;\n e.blackTotalValue = 0;\n bestEvaluatedMoves.add(e);\n }\n }\n return bestEvaluatedMoves;\n }\n\n public int[] findBestWhiteMoves(int lookAhead, int movesToConsider, boolean multithreading) throws EndOfGameException {\n Comparator moveComparator = new WhiteMoveComparator();\n int[] moves = Arrays.copyOf(whiteMoves, numberOfWhiteMoves);\n try {\n List<XMove> evaluatedMoves = findBestMovesWithoutRecursion(moves, s_WHITE);\n if (evaluatedMoves.size() == 0) {\n if (isBlackKingThreatened)\n {\n throw new BlackIsCheckMateException();\n }\n if (isWhiteKingThreatened)\n {\n \tthrow new WhiteIsCheckMateException();\n }\n \n throw new StaleMateException();\n }\n // elimitate silly moves\n if (lookAhead >= 0) {\n evaluatedMoves = findBestWhiteMovesRecursively(0, evaluatedMoves.size(), moveComparator, evaluatedMoves, multithreading);\n }\n List<XMove> bestEvaluatedMoves = new ArrayList<>();\n\n if (lookAhead > 0) {\n bestEvaluatedMoves = findBestWhiteMovesRecursively(lookAhead, movesToConsider - 1, moveComparator, evaluatedMoves, multithreading);\n } else {\n for (int i = 0; i < evaluatedMoves.size() && bestEvaluatedMoves.size() < movesToConsider; i++) {\n XMove e = (XMove) evaluatedMoves.get(i);\n bestEvaluatedMoves.add(e);\n }\n }\n int size = bestEvaluatedMoves.size();\n// if (0 == size)\n// {\n// System.err.println(\"No possible move left?\");\n// }\n\n int[] bestMoves = new int[size];\n for (int i = 0; i < movesToConsider && i < size; i++) {\n bestMoves[i] = bestEvaluatedMoves.get(i).move;\n }\n return bestMoves;\n } catch (KingLostException p_checkmate) {\n throw new BlackIsCheckMateException();\n }\n }\n\n private List<XMove> findBestWhiteMovesRecursively(int lookAhead, int movesToConsider, Comparator moveComparator, List<XMove> evaluatedMoves, boolean multithreading) throws EndOfGameException {\n List<XMove> bestEvaluatedMoves;\n if (multithreading)\n {\n bestEvaluatedMoves = findBestWhiteMovesRecursivelyMultiThreaded(lookAhead, movesToConsider, evaluatedMoves);\n }\n else {\n bestEvaluatedMoves = findBestWhiteMovesRecursivelySingleThreaded(lookAhead, movesToConsider, evaluatedMoves);\n }\n Collections.sort(bestEvaluatedMoves, moveComparator);\n return bestEvaluatedMoves;\n }\n\n private List<XMove> findBestWhiteMovesRecursivelyMultiThreaded(final int lookAhead, final int movesToConsider, final List<XMove> evaluatedMoves) throws EndOfGameException {\n\n final List<XMove> bestEvaluatedMoves = new ArrayList<>();\n int proc = Runtime.getRuntime().availableProcessors();\n int mtc = 0;\n while (mtc<=movesToConsider)\n {\n mtc += proc;\n }\n ExecutorService executor = Executors.newFixedThreadPool(evaluatedMoves.size());\n try {\n List<Future<Object>> list = new ArrayList<Future<Object>>();\n for (int i = 0; i < evaluatedMoves.size() && i < mtc; i++) {\n// for (int i = 0; i < evaluatedMoves.size() && bestEvaluatedMoves.size() < movesToConsider; i++) {\n final XMove e = (XMove) evaluatedMoves.get(i);\n\n Callable<Object> worker = new Callable<Object>() {\n public Object call() throws EndOfGameException {\n try {\n int opponentsMoveToConsider = movesToConsider;\n if (lookAhead <= 0) {\n opponentsMoveToConsider = 1;\n }\n int[] blackMoves = e.boardAfterMove.findBestBlackMoves(lookAhead - 1, opponentsMoveToConsider, false);\n convertFirstMoveToXMove(e, whiteMoves);\n synchronized (bestEvaluatedMoves) {\n bestEvaluatedMoves.add(e);\n }\n } catch (WhiteIsCheckMateException p_impossibleMove) {\n e.checkmate = true;\n e.whiteTotalValue = -1000000;\n e.blackTotalValue = 1000000;\n bestEvaluatedMoves.add(e);\n } catch (BlackIsCheckMateException p_winningMove) {\n e.checkmate = true;\n e.whiteTotalValue = 1000000;\n e.blackTotalValue = -1000000;\n bestEvaluatedMoves.add(e);\n } catch (EndOfGameException p_stalemate) {\n e.stalemate = true;\n e.whiteTotalValue = 0;\n e.blackTotalValue = 0;\n bestEvaluatedMoves.add(e);\n }\n return null;\n }\n };\n Future<Object> submit = executor.submit(worker);\n list.add(submit);\n\n }\n for (Future<Object> future : list) {\n try {\n future.get();\n } catch (InterruptedException e) {\n e.printStackTrace();\n } catch (ExecutionException e) {\n e.printStackTrace();\n }\n }\n } finally {\n executor.shutdown();\n }\n return bestEvaluatedMoves;\n }\n\n\n private List<XMove> findBestWhiteMovesRecursivelySingleThreaded(int lookAhead, int movesToConsider, List<XMove> evaluatedMoves) throws EndOfGameException {\n List<XMove> bestEvaluatedMoves = new ArrayList<>();\n for (int i = 0; i < evaluatedMoves.size() && bestEvaluatedMoves.size() < movesToConsider; i++) {\n XMove e = (XMove) evaluatedMoves.get(i);\n try {\n int opponentsMoveToConsider = movesToConsider;\n if (lookAhead <= 0) {\n opponentsMoveToConsider = 1;\n }\n int[] blackMoves = e.boardAfterMove.findBestBlackMoves(lookAhead - 1, opponentsMoveToConsider, false);\n convertFirstMoveToXMove(e, blackMoves);\n bestEvaluatedMoves.add(e);\n } catch (WhiteIsCheckMateException p_impossibleMove) {\n e.checkmate = true;\n e.whiteTotalValue = -1000000;\n e.blackTotalValue = 1000000;\n bestEvaluatedMoves.add(e);\n } catch (BlackIsCheckMateException p_winningMove) {\n e.checkmate = true;\n e.whiteTotalValue = 1000000;\n e.blackTotalValue = -1000000;\n bestEvaluatedMoves.add(e);\n } catch (EndOfGameException p_stalemate) {\n e.stalemate = true;\n e.whiteTotalValue = 0;\n e.blackTotalValue = 0;\n bestEvaluatedMoves.add(e);\n }\n }\n return bestEvaluatedMoves;\n }\n\n private void convertFirstMoveToXMove(XMove e, int[] whiteMoves) {\n if (null != whiteMoves && whiteMoves.length > 0) {\n int whiteMove = whiteMoves[0];\n int fromRow = (whiteMove >> 12) & 0x000F;\n int fromColumn = (whiteMove >> 8) & 0x000F;\n int toRow = (whiteMove >> 4) & 0x000F;\n int toColumn = whiteMove & 0x000F;\n int promotedPiece = (whiteMove >> 16) & 0x00FF;\n Chessboard afterWhiteMove = e.boardAfterMove.moveChessPiece(fromRow, fromColumn, toRow, toColumn, promotedPiece);\n e.whiteMaterialValue = afterWhiteMove.whiteMaterialValue;\n e.blackMaterialValue = afterWhiteMove.blackMaterialValue;\n e.whitePotentialMaterialValue = afterWhiteMove.whitePotentialMaterialValue;\n e.blackPotentialMaterialValue = afterWhiteMove.blackPotentialMaterialValue;\n e.whiteFieldPositionValue = afterWhiteMove.whiteFieldPositionValue;\n e.blackFieldPositionValue = afterWhiteMove.blackFieldPositionValue;\n e.whiteMoveValue = afterWhiteMove.whiteMoveValue;\n e.blackMoveValue = afterWhiteMove.blackMoveValue;\n e.whiteCoverageValue = afterWhiteMove.whiteCoverageValue;\n e.blackCoverageValue = afterWhiteMove.blackCoverageValue;\n e.isWhiteKingThreatened = afterWhiteMove.isWhiteKingThreatened;\n e.isBlackKingThreatened = afterWhiteMove.isBlackKingThreatened;\n e.whiteTotalValue = afterWhiteMove.whiteTotalValue;\n e.blackTotalValue = afterWhiteMove.blackTotalValue;\n e.numberOfWhiteMoves = afterWhiteMove.numberOfWhiteMoves;\n e.numberOfBlackMoves = afterWhiteMove.numberOfBlackMoves;\n// e.boardAfterMove = afterWhiteMove;\n }\n }\n\n protected List<XMove> findBestMovesWithoutRecursion(int[] moves, boolean p_activePlayerIsWhite) throws KingLostException {\n List<XMove> evaluatedMoves = new ArrayList<>(moves.length);\n for (int i = 0; i < moves.length; i++) {\n int move = moves[i];\n// int capturedValue = (move >> 24);\n int promotion = (move >> 16) & 0x00FF;\n int fromRow = (move >> 12) & 0x000F;\n int fromColumn = (move >> 8) & 0x000F;\n int toRow = (move >> 4) & 0x000F;\n int toColumn = move & 0x000F;\n Chessboard afterMove = new Chessboard(this, fromRow, fromColumn, toRow, toColumn, promotion);\n XMove e = new XMove();\n e.move = move;\n e.piece = getChessPiece(fromRow, fromColumn);\n e.whiteMaterialValue = afterMove.whiteMaterialValue;\n e.blackMaterialValue = afterMove.blackMaterialValue;\n e.whiteFieldPositionValue = afterMove.whiteFieldPositionValue;\n e.blackFieldPositionValue = afterMove.blackFieldPositionValue;\n e.whiteMoveValue = afterMove.whiteMoveValue;\n e.blackMoveValue = afterMove.blackMoveValue;\n e.whiteCoverageValue = afterMove.whiteCoverageValue;\n e.blackCoverageValue = afterMove.blackCoverageValue;\n e.isWhiteKingThreatened = afterMove.isWhiteKingThreatened;\n e.isBlackKingThreatened = afterMove.isBlackKingThreatened;\n e.whiteTotalValue = afterMove.whiteTotalValue;\n e.blackTotalValue = afterMove.blackTotalValue;\n e.numberOfWhiteMoves = afterMove.numberOfWhiteMoves;\n e.numberOfBlackMoves = afterMove.numberOfBlackMoves;\n e.boardAfterMove = afterMove;\n if (activePlayerIsWhite) {\n if (!afterMove.isWhiteKingThreatened) {\n evaluatedMoves.add(e);\n }\n } else if (!afterMove.isBlackKingThreatened) {\n evaluatedMoves.add(e);\n }\n if ((e.whiteMaterialValue <= -9999) || (e.blackMaterialValue <= -9999)) {\n throw new KingLostException();\n }\n\n }\n if (p_activePlayerIsWhite)\n Collections.sort(evaluatedMoves, new WhiteMoveComparator());\n else\n Collections.sort(evaluatedMoves, new BlackMoveComparator());\n return evaluatedMoves;\n }\n\n}" ]
import java.io.Serializable; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import de.beyondjava.bootsfaces.chess.common.ChessConstants; import de.beyondjava.bootsfaces.chess.common.Move; import de.beyondjava.bootsfaces.chess.common.Settings; import de.beyondjava.bootsfaces.chess.exceptions.BlackIsCheckMateException; import de.beyondjava.bootsfaces.chess.exceptions.EndOfGameException; import de.beyondjava.bootsfaces.chess.exceptions.StaleMateException; import de.beyondjava.bootsfaces.chess.exceptions.WhiteIsCheckMateException; import de.beyondjava.bootsfaces.chess.objectOrientedEngine.Chessboard;
package de.beyondjava.bootsfaces.chess.jsf; @ManagedBean @ViewScoped public class Board implements Serializable { private static final long serialVersionUID = 1L; private String averageEvaluation;
private Chessboard chessboard = new Chessboard();
7
GoodGrind/ghostwriter
ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/collector/MethodDeclarationCollector.java
[ "public interface JavaCompiler {\n\n /**\n * Returns an expression which evaluates to the default value (Java spec.) of a given type.\n *\n * @param type Type of the default value\n * @return Expression representing a default value\n */\n JCTree.JCExpression defaultValueForType(JCTree.JCExpression type);\n\n /**\n * Tests whether a javac AST expression resolves to a primitive type.\n *\n * @param type expression to check\n * @return true if the passed expression resolves to a primitive type\n */\n boolean isPrimitiveType(JCExpression type);\n\n /**\n * Returns the wrapper class representation for a javac finalVariable declaration type expression.\n *\n * @param type primitive type to wrap\n * @return the wrapper representation for a give primitive type\n */\n Class<?> wrapperType(JCPrimitiveTypeTree type);\n\n /**\n * Returns the fully qualified type of the return parameter.\n * In case of procedures, this will be java.lang.Void.\n *\n * @param method used for introspection\n * @return fully qualified type of the return parameter.\n */\n JCExpression methodReturnType(JCMethodDecl method);\n\n /**\n * Extract the name of the method based on the javac representation.\n * The symbol is returned as a java.lang.String\n *\n * @param method used for introspection\n * @return name of the method.\n */\n String methodName(JCMethodDecl method);\n\n /**\n * In javac, dotted access of any kind, from {@code java.lang.String} to\n * {@code var.methodName} is represented by a fold-left of {@code Select}\n * nodes with the leftmost string represented by a {@code Ident} node. This\n * method generates such an expression.\n * \n * For example, maker.Select(maker.Select(maker.Ident(NAME[java]),\n * NAME[lang]), NAME[String]).\n *\n * @see com.sun.tools.javac.tree.JCTree.JCIdent\n * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess\n *\n * @param expr Java expression to be built into an AST\n * @return AST representation of the passed expression\n */\n JCExpression expression(String expr);\n\n /**\n * Returns an abstraction for internal compiler strings. They are stored in\n * UTF8 format. Names are stored in a Name.Table, and are unique within\n * that table.\n *\n * @see com.sun.tools.javac.util.Name\n * @see com.sun.tools.javac.util.Name.Table\n *\n * @param identifierName identifier name\n * @return internal representation for an identifier\n */\n Name name(String identifierName);\n\n /**\n * Construct an array of specified type\n *\n * @param type fully qualified name of the type, such as java.lang.Object\n * @return expression representing the array declaration\n */\n JCNewArray array(JCExpression type);\n\n /**\n * Return a \"constant\" value expression for a given value.\n * The type of the value is deduced base on the value itself.\n *\n * In case of null, a NullPointerException will be thrown\n *\n * @param value the value to be represented as a constant\n * @return AST representation of the constant\n *\n */\n JCLiteral literal(Object value);\n\n\n /**\n * @param name name of the identifier to be constructed\n * @return compiler representation of the identifier\n */\n JCIdent identifier(String name);\n\n /**\n * Create a finalVariable declaration\n *\n * @param type type of the finalVariable\n * @param name name of the finalVariable\n * @param value right side part of the finalVariable declaration\n * @param parent scope that the variable should belong to\n * @return compiler representation of the finalVariable declaration\n */\n JCVariableDecl finalVariable(JCExpression type, String name, JCExpression value, JCTree parent);\n\n\n /**\n * @param identifier left hand side of the assign operation\n * @param expression right hand side of the assign operation\n * @return compiler representation of the assign operation\n */\n JCAssign assign(JCIdent identifier, JCExpression expression);\n\n /**\n * Wrap expression into a statement type that can be added to method bodies and so on...\n *\n * @param expression expression to wrap\n * @return statement that executes the specified expression\n */\n JCExpressionStatement execute(JCExpression expression);\n\n /**\n * Create a function invocation expression\n *\n * @param method method to be called\n * @param arguments input arguments for the method\n * @return function call AST\n */\n JCExpressionStatement call(JCExpression method, List<JCExpression> arguments);\n\n /**\n * Create a function application\n *\n * @param method method application target\n * @param arguments arguments to be applied to a method\n * @return method invocation AST\n *\n */\n JCMethodInvocation apply(JCExpression method, List<JCExpression> arguments);\n\n /**\n * @param statements list of statements to enclose\n * @return returns the compiler representation of a block containing the given statements\n */\n JCBlock block(List<JCStatement> statements);\n\n JCExpression declarationType(JCExpression variable);\n \n JCTry tryFinally(JCBlock tryBlock, JCBlock finallyBlock);\n\n JCCatch catchExpression(JCVariableDecl param, JCBlock body);\n\n JCThrow throwStatement(JCExpression expr);\n\n JCTry tryCatchFinally(JCBlock tryBlock, JCCatch catchBlock, JCBlock finallyBlock);\n\n JCStatement ifCondition(JCExpression condition, JCStatement then);\n\n JCExpression notEqualExpression(JCExpression lhs, JCExpression rhs);\n\n JCTree.JCExpression nullLiteral();\n \n boolean isStaticMethod(JCMethodDecl method);\n\n String fullyQualifiedNameForTypeExpression(JCExpression typeExpression);\n\n JCAnnotation annotation(String fullyQualifiedName);\n\n JCVariableDecl catchParameter(String name, JCTree parent);\n\n JCPrimitiveTypeTree primitiveType(String type);\n\n JCBinary binary(String operation, JCExpression lhs, JCExpression rhs);\n\n JCReturn makeReturn(JCExpression result);\n\n JCExpression castToType(JCTree returnType, JCExpression expression);\n\n JCArrayAccess arrayAccess(JCExpression indexed, JCExpression index);\n\n String getOption(String option);\n}", "public enum Logger {\n ;\n\n private static Messager messager;\n\n private static boolean doVerboseLogging = false;\n\n private static String format(Class<?> klass, String method, String message) {\n final int INITIAL_CAPACITY = 32;\n StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);\n if (klass != null) {\n sb.append(klass.getName());\n sb.append(\".\");\n }\n sb.append(method);\n sb.append(\": \");\n sb.append(message);\n\n return sb.toString();\n }\n\n public static void note(Class<?> type, String method, String message) {\n if (!doVerboseLogging) {\n return;\n }\n\n validateState();\n String output = format(type, method, message);\n messager.printMessage(Diagnostic.Kind.NOTE, output);\n }\n\n public static void warning(Class<?> type, String method, String message) {\n validateState();\n String output = format(type, method, message);\n messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);\n }\n\n /**\n * Display an error message.\n *\n * @param type - class that produced the error\n * @param method - method that produced the error\n * @param message - error description\n */\n public static void error(Class<?> type, String method, String message) {\n validateState();\n String output = format(type, method, message);\n messager.printMessage(Diagnostic.Kind.ERROR, output);\n }\n\n public static void initialize(Messager msg, boolean verbose) {\n if (msg == null) {\n throw new IllegalArgumentException(\"Cannot initialize with null!\");\n }\n messager = msg;\n doVerboseLogging = verbose;\n }\n\n private static void validateState() {\n if (messager == null) {\n throw new IllegalStateException(\"Logger has not been initialized!\");\n }\n }\n\n}", "public class Clazz extends AstModel<JCTree.JCClassDecl> {\n\n public Clazz(JCTree.JCClassDecl representation) {\n super(representation);\n }\n \n public String getFullyQualifiedClassName() {\n JCTree.JCClassDecl classDecl = representation();\n final Symbol.ClassSymbol sym = classDecl.sym;\n final boolean isAnonymousClass = sym == null;\n String name = \"\";\n if (!isAnonymousClass) {\n final Name qualifiedName = sym.getQualifiedName();\n name = qualifiedName.toString();\n }\n return name;\n }\n\n}", "public class Method extends AstModel<JCMethodDecl> { \n private final String name;\n private final Clazz clazz;\n private final List<Parameter> parameters;\n\n public Method(String name, Clazz clazz, List<Parameter> parameters, JCMethodDecl representation) {\n super(representation);\n Objects.requireNonNull(clazz, \"Must provide a valid class AST model!\");\n Objects.requireNonNull(name, \"Must provide a valid parameter name!\");\n if (\"\".equals(name)) {\n throw new IllegalArgumentException(\"Must provide a non-empty method name!\");\n }\n\n this.name = name;\n this.clazz = clazz;\n this.parameters = parameters;\n }\n\n public Clazz getClazz() {\n return clazz;\n }\n \n public String getName() {\n return name;\n }\n\n public List<Parameter> getParameters() {\n return parameters;\n }\n\n @Override\n public String toString() {\n return \"Method [class=\" + clazz.getFullyQualifiedClassName() + \", name=\" + name + \", parameters=\" + parameters + \"]\";\n }\n\n}", "public class Parameter extends AstModel<JCVariableDecl> {\n private final String name;\n // fully qualified name of the type. Representing\n // it with Class<?> is not possible, since most\n // of the classes are only available at run-time\n private final String type;\n\n public Parameter(String name, String type, JCVariableDecl representation) {\n super(representation);\n Objects.requireNonNull(name, \"Must provide a valid parameter name!\");\n Objects.requireNonNull(type, \"Must provide a valid parameter type!\");\n if (\"\".equals(name)) {\n throw new IllegalArgumentException(\"Must provide a non-empty parameter name!\");\n }\n if (\"\".equals(type)) {\n throw new IllegalArgumentException(\"Must provide a non-empty, fully qualified name of the parameter type!\");\n }\n\n this.name = name;\n this.type = type;\n }\n\n public String getName() {\n return name;\n }\n\n /**\n * Returns the fully qualified name of the parameter type\n *\n * @return fully qualified name of the parameter type\n */\n public String getType() {\n return type;\n }\n\n @Override\n public String toString() {\n return \"Parameter [name=\" + name + \", type=\" + type + \"]\";\n }\n\n}" ]
import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import io.ghostwriter.openjdk.v7.ast.compiler.JavaCompiler; import io.ghostwriter.openjdk.v7.common.Logger; import io.ghostwriter.openjdk.v7.model.Clazz; import io.ghostwriter.openjdk.v7.model.Method; import io.ghostwriter.openjdk.v7.model.Parameter; import java.util.List; import java.util.Objects;
package io.ghostwriter.openjdk.v7.ast.collector; public class MethodDeclarationCollector extends Collector<Method> { private final JavaCompiler javac; public MethodDeclarationCollector(JavaCompiler javac, JCTree.JCClassDecl rootClass) { super(rootClass); this.javac = Objects.requireNonNull(javac); } @Override public void visitClassDef(JCTree.JCClassDecl klass) { collectMethodDefinitions(klass); super.visitClassDef(klass); } /** * We use this method instead of overriding the visitMethodDef method because we only want to collect * methods belonging to the current class definition. This is required in order to have a correct Clazz model * in the Method model instances. * Nested classes definitions and their methods are handled when the visitor pattern calls the corresponding * visitClassDef handler for those as well. * * @param klass class repersentation to traverse */ protected void collectMethodDefinitions(JCTree.JCClassDecl klass) { for (JCTree member : klass.getMembers()) { if (!(member instanceof JCMethodDecl)) { continue; } JCMethodDecl methodDecl = (JCMethodDecl) member; Method method = buildMethodModel(klass, methodDecl); collect(method); } } protected Method buildMethodModel(JCTree.JCClassDecl klass, JCMethodDecl methodDeclaration) { ParameterCollector parameterCollector = new ParameterCollector(javac, methodDeclaration); List<Parameter> parameters = parameterCollector.toList(); String methodName = javac.methodName(methodDeclaration);
final Clazz enclosingClass = new Clazz(klass);
2
koen-serneels/HomeAutomation
src/main/java/be/error/rpi/dac/dimmer/config/scenes/GvComfort.java
[ "public static RunConfig getInstance() {\n\tif (runConfig == null) {\n\t\tthrow new IllegalStateException(\"Initialize first\");\n\t}\n\treturn runConfig;\n}", "public static SceneContext active(GroupAddress... sceneParticipants) {\n\tSceneContext sceneContext = new SceneContext();\n\tsceneContext.sceneActive = true;\n\tsceneContext.sceneParticipants.addAll(asList(sceneParticipants));\n\treturn sceneContext;\n}", "public static SceneContext inactive() {\n\treturn new SceneContext();\n}", "public class Dimmer extends Thread {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(Dimmer.class);\n\tprivate static final BigDecimal ZERO = new BigDecimal(\"0.0\");\n\n\tprivate long turnOffDelay = 2000;\n\tprivate long delayBeforeIncreasingDimValue = 300;\n\tprivate int stepDelay = 30;\n\n\tprivate List<GroupAddress> feedbackGroupAddresses = new ArrayList();\n\tprivate List<GroupAddress> switchLedControlGroupAddresses = new ArrayList();\n\tprivate List<GroupAddress> switchGroupAddresses = new ArrayList();\n\tprivate List<GroupAddress> outputSwitchUpdateGroupAddresses = new ArrayList<>();\n\n\tprivate BigDecimal curVal = ZERO;\n\tprivate BigDecimal sentVal = ZERO;\n\n\tprivate BigDecimal minDimValue = new BigDecimal(\"1.0\");\n\tprivate DimDirection lastDimDirection;\n\n\tprivate final AtomicBoolean interupt = new AtomicBoolean(false);\n\tprivate final BlockingQueue<DimmerCommand> commandQueue = new LinkedBlockingDeque();\n\n\tprivate final LocationId dimmerName;\n\tprivate final DimmerBackend dimmerBackend;\n\tprivate final int boardAddress;\n\tprivate final int channel;\n\n\tprivate KnxDimmerProcessListener knxDimmerProcessListener;\n\n\tprivate Optional<DimmerCommand> lastDimCommand = empty();\n\tprivate Optional<DimmerCommand> activeScene = empty();\n\n\tpublic Dimmer(LocationId dimmerName, DimmerBackend dimmerBackend, int boardAddress, int channel, List<GroupAddress> switchGroupAddresses,\n\t\t\tList<GroupAddress> feedbackGroupAddresses, List<GroupAddress> switchLedControlGroupAddresses, List<GroupAddress> outputSwitchUpdateGroupAddresses)\n\t\t\tthrows IOException {\n\n\t\tthis.dimmerName = dimmerName;\n\t\tthis.dimmerBackend = dimmerBackend;\n\t\tthis.boardAddress = boardAddress;\n\t\tthis.channel = channel;\n\t\tthis.switchGroupAddresses = switchGroupAddresses;\n\t\tthis.feedbackGroupAddresses = feedbackGroupAddresses;\n\t\tthis.switchLedControlGroupAddresses = switchLedControlGroupAddresses;\n\t\tthis.outputSwitchUpdateGroupAddresses = outputSwitchUpdateGroupAddresses;\n\t}\n\n\tpublic void run() {\n\t\twhile (true) {\n\t\t\ttry {\n\t\t\t\tDimmerCommand command = commandQueue.take();\n\n\t\t\t\tKnxConnectionFactory.getInstance().runWithProcessCommunicator(pc -> {\n\t\t\t\t\tDimmerCommand dimmerCommand = command;\n\t\t\t\t\tinterupt.set(false);\n\t\t\t\t\tboolean feedbackSend = false;\n\n\t\t\t\t\tif (dimmerCommand.getSceneContext().isPresent()) {\n\t\t\t\t\t\tif (dimmerCommand.getSceneContext().get().isSceneActive()) {\n\t\t\t\t\t\t\tlastDimCommand = empty();\n\t\t\t\t\t\t\tactiveScene = of(dimmerCommand);\n\t\t\t\t\t\t\tactivateSceneLeds(pc);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tactiveScene = empty();\n\t\t\t\t\t\t\tdimmerCommand = dimmerCommand.isUseThisDimCommandOnSceneDeativate() ? dimmerCommand : lastDimCommand.orElse(dimmerCommand);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlastDimCommand = of(dimmerCommand);\n\t\t\t\t\t\tif ((dimmerCommand.getTargetVal().compareTo(ZERO) == 0)) {\n\t\t\t\t\t\t\tif ((activeScene.isPresent())) {\n\t\t\t\t\t\t\t\tactivateSceneLeds(pc);\n\t\t\t\t\t\t\t\tdimmerCommand = activeScene.get();\n\t\t\t\t\t\t\t\tsendDimmerFeedback(pc, dimmerCommand.getTargetVal().intValue(), true);\n\t\t\t\t\t\t\t\tfeedbackSend = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsendStatusFeedback(true, !command.isActicatedByPrecense(), pc);\n\t\t\t\t\t\t\tsleep(delayBeforeIncreasingDimValue);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (dimmerCommand.getTargetVal().compareTo(curVal) > 0) {\n\t\t\t\t\t\tlastDimDirection = UP;\n\t\t\t\t\t} else if (dimmerCommand.getTargetVal().compareTo(curVal) < 0) {\n\t\t\t\t\t\tlastDimDirection = DOWN;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlastDimDirection = (lastDimDirection == UP ? DOWN : UP);\n\t\t\t\t\t}\n\n\t\t\t\t\twhile (curVal.compareTo(dimmerCommand.getTargetVal()) != 0) {\n\t\t\t\t\t\tprocessCommand(dimmerCommand);\n\t\t\t\t\t\tif (commandQueue.peek() != null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (interupt.get()) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsleep(stepDelay);\n\t\t\t\t\t\tif (interupt.get()) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!feedbackSend && !getInstance().getLoxoneIa().equals(dimmerCommand.getOrigin())) {\n\t\t\t\t\t\tsendDimmerFeedback(pc, getCurVal().intValue(), false);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (curVal.compareTo(ZERO) == 0) {\n\t\t\t\t\t\tfor (int i = 0; i < turnOffDelay; i++) {\n\t\t\t\t\t\t\tsleep(1);\n\t\t\t\t\t\t\tif (interupt.get()) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!interupt.get()) {\n\t\t\t\t\t\t\tsendStatusFeedback(false, !dimmerCommand.isActicatedByPrecense(), pc);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\tlogger.error(\"Dimmer \" + dimmerName + \" got interrupt\", e);\n\t\t\t\tinterrupt();\n\t\t\t\t//Do nothing\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\"Dimmer \" + dimmerName + \" got exception\", e);\n\t\t\t\tinterrupt();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic synchronized void putCommand(DimmerCommand dimmerCommand) throws Exception {\n\t\tcommandQueue.clear();\n\t\tcommandQueue.put(dimmerCommand);\n\t}\n\n\tpublic void interrupt() {\n\t\tinterupt.set(true);\n\t}\n\n\tprivate void sendStatusFeedback(boolean status, boolean sendLedFeedback, ProcessCommunicator pc) throws Exception {\n\t\tCollection<GroupAddress> collection = union(switchGroupAddresses, outputSwitchUpdateGroupAddresses);\n\n\t\tif (sendLedFeedback) {\n\t\t\tcollection = union(collection, switchLedControlGroupAddresses);\n\t\t}\n\n\t\tfor (GroupAddress groupAddress : collection) {\n\t\t\tpc.write(groupAddress, status);\n\t\t}\n\t}\n\n\tprivate void activateSceneLeds(ProcessCommunicator pc) throws Exception {\n\t\tsendStatusFeedback(false, true, pc);\n\n\t\tfor (GroupAddress groupAddress : activeScene.get().getSceneContext().get().getSceneParticipants()) {\n\t\t\tpc.write(groupAddress, true);\n\t\t}\n\t}\n\n\tprivate void sendDimmerFeedback(ProcessCommunicator pc, int val, boolean refresh) throws Exception {\n\t\tfor (GroupAddress groupAddress : feedbackGroupAddresses) {\n\n\t\t\tDPTXlator8BitUnsigned dDPTXlator8BitUnsigned = new DPTXlator8BitUnsigned(DPT_PERCENT_U8);\n\t\t\tif (refresh) {\n\t\t\t\tdDPTXlator8BitUnsigned.setValue(0);\n\t\t\t\tpc.write(groupAddress, dDPTXlator8BitUnsigned);\n\t\t\t}\n\n\t\t\tdDPTXlator8BitUnsigned.setValue(val);\n\t\t\tpc.write(groupAddress, dDPTXlator8BitUnsigned);\n\t\t}\n\t}\n\n\tprivate void processCommand(DimmerCommand dimmerCommand) throws IOException {\n\t\tif (curVal.compareTo(dimmerCommand.getTargetVal()) < 0) {\n\t\t\tcurVal = curVal.add(new BigDecimal(\"1.0\"));\n\t\t} else {\n\t\t\tcurVal = curVal.subtract(new BigDecimal(\"1.0\"));\n\t\t}\n\n\t\t//If curval is below mindimval we sent mindimval instead. This ensures that the driver does not turn itself of if the dim value gets too low. The driver\n\t\t// should be turned off via it's relay (~KNX actor) instead and not by the dimmer input. Curval remains the internal state as it is also used to determine when\n\t\t// the relais is to be switched off (namely when curval reaches ZERO). The value actually sent to the DAC is then reflected as sentval (mostly for debug\n\t\t// purposes)\n\t\tsentVal = curVal.compareTo(minDimValue) < 0 ? minDimValue : curVal;\n\n\t\tdim(sentVal);\n\t}\n\n\tprivate void dim(BigDecimal targetValue) throws IOException {\n\t\tif (dimmerBackend == I2C) {\n\t\t\tbyte[] b = convertPercentageToDacBytes(targetValue);\n\t\t\tgetInstance().getI2CCommunicator().write(boardAddress, channel, b);\n\t\t} else {\n\t\t\tgetInstance().doWithLucidControl(boardAddress, (lucidControlAO4) -> {\n\t\t\t\ttry {\n\t\t\t\t\tlucidControlAO4.setIo(channel, new ValueVOS2(convertPercentageTo10Volt(targetValue)));\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new UncheckedIOException(e);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic BigDecimal getCurVal() {\n\t\treturn curVal;\n\t}\n\n\tpublic DimDirection getLastDimDirection() {\n\t\treturn lastDimDirection;\n\t}\n\n\tpublic Optional<DimmerCommand> getLastDimCommand() {\n\t\treturn lastDimCommand;\n\t}\n\n\tvoid setTurnOffDelay(final long turnOffDelay) {\n\t\tthis.turnOffDelay = turnOffDelay;\n\t}\n\n\tvoid setDelayBeforeIncreasingDimValue(final long delayBeforeIncreasingDimValue) {\n\t\tthis.delayBeforeIncreasingDimValue = delayBeforeIncreasingDimValue;\n\t}\n\n\tvoid setStepDelay(final int stepDelay) {\n\t\tthis.stepDelay = stepDelay;\n\t}\n\n\tpublic KnxDimmerProcessListener getKnxDimmerProcessListener() {\n\t\treturn knxDimmerProcessListener;\n\t}\n\n\tpublic void setKnxDimmerProcessListener(final KnxDimmerProcessListener knxDimmerProcessListener) {\n\t\tthis.knxDimmerProcessListener = knxDimmerProcessListener;\n\t}\n}", "public class DimmerCommand {\n\n\tprivate BigDecimal targetVal;\n\tprivate IndividualAddress origin;\n\n\tprivate boolean useThisDimCommandOnSceneDeativate;\n\tprivate Optional<SceneContext> sceneContext = empty();\n\n\tprivate boolean override;\n\tprivate boolean acticatedByPrecense;\n\n\tpublic DimmerCommand(final BigDecimal targetVal, final IndividualAddress origin, SceneContext sceneContext, boolean useThisDimCommandOnSceneDeativate) {\n\t\tthis(targetVal, origin, sceneContext);\n\t\tthis.useThisDimCommandOnSceneDeativate = useThisDimCommandOnSceneDeativate;\n\t}\n\n\tpublic DimmerCommand(final BigDecimal targetVal, final IndividualAddress origin, SceneContext sceneContext) {\n\t\tthis(targetVal, origin);\n\t\tthis.sceneContext = of(sceneContext);\n\t}\n\n\tpublic DimmerCommand(final BigDecimal targetVal, final IndividualAddress origin) {\n\t\tthis.targetVal = targetVal;\n\t\tthis.origin = origin;\n\t}\n\n\tpublic void setOverride() {\n\t\toverride = true;\n\t}\n\n\tpublic boolean isOverride() {\n\t\treturn override;\n\t}\n\n\tpublic IndividualAddress getOrigin() {\n\t\treturn origin;\n\t}\n\n\tpublic BigDecimal getTargetVal() {\n\t\treturn targetVal;\n\t}\n\n\tpublic Optional<SceneContext> getSceneContext() {\n\t\treturn sceneContext;\n\t}\n\n\tpublic boolean isUseThisDimCommandOnSceneDeativate() {\n\t\treturn useThisDimCommandOnSceneDeativate;\n\t}\n\n\tpublic boolean isActicatedByPrecense() {\n\t\treturn acticatedByPrecense;\n\t}\n\n\tpublic void setActicatedByPrecense(final boolean acticatedByPrecense) {\n\t\tthis.acticatedByPrecense = acticatedByPrecense;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"DimmerCommand{\" + \"targetVal=\" + targetVal + '}';\n\t}\n}", "public class ProcessListenerAdapter extends ProcessListenerEx {\n\n\t@Override\n\tpublic void groupReadRequest(final ProcessEvent e) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void groupReadResponse(final ProcessEvent e) {\n\n\t}\n\n\t@Override\n\tpublic void groupWrite(final ProcessEvent e) {\n\n\t}\n\n\t@Override\n\tpublic void detached(final DetachEvent e) {\n\n\t}\n}" ]
import tuwien.auto.calimero.process.ProcessEvent; import be.error.rpi.dac.dimmer.builder.Dimmer; import be.error.rpi.dac.dimmer.builder.DimmerCommand; import be.error.rpi.knx.ProcessListenerAdapter; import static be.error.rpi.config.RunConfig.getInstance; import static be.error.rpi.dac.dimmer.builder.SceneContext.active; import static be.error.rpi.dac.dimmer.builder.SceneContext.inactive; import static tuwien.auto.calimero.process.ProcessCommunicationBase.UNSCALED; import java.math.BigDecimal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tuwien.auto.calimero.GroupAddress;
/*- * #%L * Home Automation * %% * Copyright (C) 2016 - 2017 Koen Serneels * %% * 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% */ package be.error.rpi.dac.dimmer.config.scenes; /** * Created by koen on 04.10.16. */ public class GvComfort implements Runnable { private static final Logger logger = LoggerFactory.getLogger(GvComfort.class); private Dimmer eethoek; private Dimmer zithoek; private Dimmer keuken; private boolean active; public GvComfort(final Dimmer eethoek, final Dimmer zithoek, final Dimmer keuken) { this.eethoek = eethoek; this.zithoek = zithoek; this.keuken = keuken; } @Override public void run() { ProcessListenerAdapter processListenerAdapter = new ProcessListenerAdapter() { @Override public void groupWrite(final ProcessEvent e) { try { if (e.getDestination().equals(new GroupAddress("11/0/0"))) { active = !active; int i = asUnsigned(e, UNSCALED); if (i == 1) { sceneOne(active, e); } } } catch (Exception ex) { logger.error(GvComfort.class.getSimpleName() + " had exception in ProcessListenerAdapter", ex); } super.groupWrite(e); } }; getInstance().getKnxConnectionFactory().addProcessListener(processListenerAdapter); } private void sceneOne(boolean on, ProcessEvent e) throws Exception { if (on) { getInstance().getKnxConnectionFactory().runWithProcessCommunicator(pc -> pc.write(new GroupAddress("11/0/1"), true)); } else { getInstance().getKnxConnectionFactory().runWithProcessCommunicator(pc -> pc.write(new GroupAddress("11/0/1"), false)); } eethoek.interrupt(); zithoek.interrupt(); keuken.interrupt();
keuken.putCommand(new DimmerCommand(new BigDecimal(on ? 1 : 0), e.getSourceAddr(), on ? active(new GroupAddress("5/0/2")) : inactive()));
4
jhy/jsoup
src/main/java/org/jsoup/helper/W3CDom.java
[ "public final class StringUtil {\n // memoised padding up to 21 (blocks 0 to 20 spaces)\n static final String[] padding = {\"\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \",\n \" \", \" \", \" \", \" \", \" \", \" \", \" \",\n \" \", \" \", \" \", \" \", \" \"};\n\n /**\n * Join a collection of strings by a separator\n * @param strings collection of string objects\n * @param sep string to place between strings\n * @return joined string\n */\n public static String join(Collection<?> strings, String sep) {\n return join(strings.iterator(), sep);\n }\n\n /**\n * Join a collection of strings by a separator\n * @param strings iterator of string objects\n * @param sep string to place between strings\n * @return joined string\n */\n public static String join(Iterator<?> strings, String sep) {\n if (!strings.hasNext())\n return \"\";\n\n String start = strings.next().toString();\n if (!strings.hasNext()) // only one, avoid builder\n return start;\n\n StringJoiner j = new StringJoiner(sep);\n j.add(start);\n while (strings.hasNext()) {\n j.add(strings.next());\n }\n return j.complete();\n }\n\n /**\n * Join an array of strings by a separator\n * @param strings collection of string objects\n * @param sep string to place between strings\n * @return joined string\n */\n public static String join(String[] strings, String sep) {\n return join(Arrays.asList(strings), sep);\n }\n\n /**\n A StringJoiner allows incremental / filtered joining of a set of stringable objects.\n @since 1.14.1\n */\n public static class StringJoiner {\n @Nullable StringBuilder sb = borrowBuilder(); // sets null on builder release so can't accidentally be reused\n final String separator;\n boolean first = true;\n\n /**\n Create a new joiner, that uses the specified separator. MUST call {@link #complete()} or will leak a thread\n local string builder.\n\n @param separator the token to insert between strings\n */\n public StringJoiner(String separator) {\n this.separator = separator;\n }\n\n /**\n Add another item to the joiner, will be separated\n */\n public StringJoiner add(Object stringy) {\n Validate.notNull(sb); // don't reuse\n if (!first)\n sb.append(separator);\n sb.append(stringy);\n first = false;\n return this;\n }\n\n /**\n Append content to the current item; not separated\n */\n public StringJoiner append(Object stringy) {\n Validate.notNull(sb); // don't reuse\n sb.append(stringy);\n return this;\n }\n\n /**\n Return the joined string, and release the builder back to the pool. This joiner cannot be reused.\n */\n public String complete() {\n String string = releaseBuilder(sb);\n sb = null;\n return string;\n }\n }\n\n /**\n * Returns space padding (up to the default max of 30). Use {@link #padding(int, int)} to specify a different limit.\n * @param width amount of padding desired\n * @return string of spaces * width\n * @see #padding(int, int) \n */\n public static String padding(int width) {\n return padding(width, 30);\n }\n\n /**\n * Returns space padding, up to a max of maxPaddingWidth.\n * @param width amount of padding desired\n * @param maxPaddingWidth maximum padding to apply. Set to {@code -1} for unlimited.\n * @return string of spaces * width\n */\n public static String padding(int width, int maxPaddingWidth) {\n Validate.isTrue(width >= 0, \"width must be >= 0\");\n Validate.isTrue(maxPaddingWidth >= -1);\n if (maxPaddingWidth != -1)\n width = Math.min(width, maxPaddingWidth);\n if (width < padding.length)\n return padding[width]; \n char[] out = new char[width];\n for (int i = 0; i < width; i++)\n out[i] = ' ';\n return String.valueOf(out);\n }\n\n /**\n * Tests if a string is blank: null, empty, or only whitespace (\" \", \\r\\n, \\t, etc)\n * @param string string to test\n * @return if string is blank\n */\n public static boolean isBlank(final String string) {\n if (string == null || string.length() == 0)\n return true;\n\n int l = string.length();\n for (int i = 0; i < l; i++) {\n if (!StringUtil.isWhitespace(string.codePointAt(i)))\n return false;\n }\n return true;\n }\n\n /**\n Tests if a string starts with a newline character\n @param string string to test\n @return if its first character is a newline\n */\n public static boolean startsWithNewline(final String string) {\n if (string == null || string.length() == 0)\n return false;\n return string.charAt(0) == '\\n';\n }\n\n /**\n * Tests if a string is numeric, i.e. contains only digit characters\n * @param string string to test\n * @return true if only digit chars, false if empty or null or contains non-digit chars\n */\n public static boolean isNumeric(String string) {\n if (string == null || string.length() == 0)\n return false;\n\n int l = string.length();\n for (int i = 0; i < l; i++) {\n if (!Character.isDigit(string.codePointAt(i)))\n return false;\n }\n return true;\n }\n\n /**\n * Tests if a code point is \"whitespace\" as defined in the HTML spec. Used for output HTML.\n * @param c code point to test\n * @return true if code point is whitespace, false otherwise\n * @see #isActuallyWhitespace(int)\n */\n public static boolean isWhitespace(int c){\n return c == ' ' || c == '\\t' || c == '\\n' || c == '\\f' || c == '\\r';\n }\n\n /**\n * Tests if a code point is \"whitespace\" as defined by what it looks like. Used for Element.text etc.\n * @param c code point to test\n * @return true if code point is whitespace, false otherwise\n */\n public static boolean isActuallyWhitespace(int c){\n return c == ' ' || c == '\\t' || c == '\\n' || c == '\\f' || c == '\\r' || c == 160;\n // 160 is &nbsp; (non-breaking space). Not in the spec but expected.\n }\n\n public static boolean isInvisibleChar(int c) {\n return c == 8203 || c == 173; // zero width sp, soft hyphen\n // previously also included zw non join, zw join - but removing those breaks semantic meaning of text\n }\n\n /**\n * Normalise the whitespace within this string; multiple spaces collapse to a single, and all whitespace characters\n * (e.g. newline, tab) convert to a simple space.\n * @param string content to normalise\n * @return normalised string\n */\n public static String normaliseWhitespace(String string) {\n StringBuilder sb = StringUtil.borrowBuilder();\n appendNormalisedWhitespace(sb, string, false);\n return StringUtil.releaseBuilder(sb);\n }\n\n /**\n * After normalizing the whitespace within a string, appends it to a string builder.\n * @param accum builder to append to\n * @param string string to normalize whitespace within\n * @param stripLeading set to true if you wish to remove any leading whitespace\n */\n public static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n\n int len = string.length();\n int c;\n for (int i = 0; i < len; i+= Character.charCount(c)) {\n c = string.codePointAt(i);\n if (isActuallyWhitespace(c)) {\n if ((stripLeading && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n }\n else if (!isInvisibleChar(c)) {\n accum.appendCodePoint(c);\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n }\n\n public static boolean in(final String needle, final String... haystack) {\n final int len = haystack.length;\n for (int i = 0; i < len; i++) {\n if (haystack[i].equals(needle))\n return true;\n }\n return false;\n }\n\n public static boolean inSorted(String needle, String[] haystack) {\n return Arrays.binarySearch(haystack, needle) >= 0;\n }\n\n /**\n Tests that a String contains only ASCII characters.\n @param string scanned string\n @return true if all characters are in range 0 - 127\n */\n public static boolean isAscii(String string) {\n Validate.notNull(string);\n for (int i = 0; i < string.length(); i++) {\n int c = string.charAt(i);\n if (c > 127) { // ascii range\n return false;\n }\n }\n return true;\n }\n\n private static final Pattern extraDotSegmentsPattern = Pattern.compile(\"^/((\\\\.{1,2}/)+)\");\n /**\n * Create a new absolute URL, from a provided existing absolute URL and a relative URL component.\n * @param base the existing absolute base URL\n * @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)\n * @return the resolved absolute URL\n * @throws MalformedURLException if an error occurred generating the URL\n */\n public static URL resolve(URL base, String relUrl) throws MalformedURLException {\n // workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired\n if (relUrl.startsWith(\"?\"))\n relUrl = base.getPath() + relUrl;\n // workaround: //example.com + ./foo = //example.com/./foo, not //example.com/foo\n URL url = new URL(base, relUrl);\n String fixedFile = extraDotSegmentsPattern.matcher(url.getFile()).replaceFirst(\"/\");\n if (url.getRef() != null) {\n fixedFile = fixedFile + \"#\" + url.getRef();\n }\n return new URL(url.getProtocol(), url.getHost(), url.getPort(), fixedFile);\n }\n\n /**\n * Create a new absolute URL, from a provided existing absolute URL and a relative URL component.\n * @param baseUrl the existing absolute base URL\n * @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)\n * @return an absolute URL if one was able to be generated, or the empty string if not\n */\n public static String resolve(final String baseUrl, final String relUrl) {\n try {\n URL base;\n try {\n base = new URL(baseUrl);\n } catch (MalformedURLException e) {\n // the base is unsuitable, but the attribute/rel may be abs on its own, so try that\n URL abs = new URL(relUrl);\n return abs.toExternalForm();\n }\n return resolve(base, relUrl).toExternalForm();\n } catch (MalformedURLException e) {\n // it may still be valid, just that Java doesn't have a registered stream handler for it, e.g. tel\n // we test here vs at start to normalize supported URLs (e.g. HTTP -> http)\n return validUriScheme.matcher(relUrl).find() ? relUrl : \"\";\n }\n }\n private static final Pattern validUriScheme = Pattern.compile(\"^[a-zA-Z][a-zA-Z0-9+-.]*:\");\n\n private static final ThreadLocal<Stack<StringBuilder>> threadLocalBuilders = new ThreadLocal<Stack<StringBuilder>>() {\n @Override\n protected Stack<StringBuilder> initialValue() {\n return new Stack<>();\n }\n };\n\n /**\n * Maintains cached StringBuilders in a flyweight pattern, to minimize new StringBuilder GCs. The StringBuilder is\n * prevented from growing too large.\n * <p>\n * Care must be taken to release the builder once its work has been completed, with {@link #releaseBuilder}\n * @return an empty StringBuilder\n */\n public static StringBuilder borrowBuilder() {\n Stack<StringBuilder> builders = threadLocalBuilders.get();\n return builders.empty() ?\n new StringBuilder(MaxCachedBuilderSize) :\n builders.pop();\n }\n\n /**\n * Release a borrowed builder. Care must be taken not to use the builder after it has been returned, as its\n * contents may be changed by this method, or by a concurrent thread.\n * @param sb the StringBuilder to release.\n * @return the string value of the released String Builder (as an incentive to release it!).\n */\n public static String releaseBuilder(StringBuilder sb) {\n Validate.notNull(sb);\n String string = sb.toString();\n\n if (sb.length() > MaxCachedBuilderSize)\n sb = new StringBuilder(MaxCachedBuilderSize); // make sure it hasn't grown too big\n else\n sb.delete(0, sb.length()); // make sure it's emptied on release\n\n Stack<StringBuilder> builders = threadLocalBuilders.get();\n builders.push(sb);\n\n while (builders.size() > MaxIdleBuilders) {\n builders.pop();\n }\n return string;\n }\n\n private static final int MaxCachedBuilderSize = 8 * 1024;\n private static final int MaxIdleBuilders = 8;\n}", "public class Attribute implements Map.Entry<String, String>, Cloneable {\n private static final String[] booleanAttributes = {\n \"allowfullscreen\", \"async\", \"autofocus\", \"checked\", \"compact\", \"declare\", \"default\", \"defer\", \"disabled\",\n \"formnovalidate\", \"hidden\", \"inert\", \"ismap\", \"itemscope\", \"multiple\", \"muted\", \"nohref\", \"noresize\",\n \"noshade\", \"novalidate\", \"nowrap\", \"open\", \"readonly\", \"required\", \"reversed\", \"seamless\", \"selected\",\n \"sortable\", \"truespeed\", \"typemustmatch\"\n };\n\n private String key;\n @Nullable private String val;\n @Nullable Attributes parent; // used to update the holding Attributes when the key / value is changed via this interface\n\n /**\n * Create a new attribute from unencoded (raw) key and value.\n * @param key attribute key; case is preserved.\n * @param value attribute value (may be null)\n * @see #createFromEncoded\n */\n public Attribute(String key, @Nullable String value) {\n this(key, value, null);\n }\n\n /**\n * Create a new attribute from unencoded (raw) key and value.\n * @param key attribute key; case is preserved.\n * @param val attribute value (may be null)\n * @param parent the containing Attributes (this Attribute is not automatically added to said Attributes)\n * @see #createFromEncoded*/\n public Attribute(String key, @Nullable String val, @Nullable Attributes parent) {\n Validate.notNull(key);\n key = key.trim();\n Validate.notEmpty(key); // trimming could potentially make empty, so validate here\n this.key = key;\n this.val = val;\n this.parent = parent;\n }\n\n /**\n Get the attribute key.\n @return the attribute key\n */\n @Override\n public String getKey() {\n return key;\n }\n\n /**\n Set the attribute key; case is preserved.\n @param key the new key; must not be null\n */\n public void setKey(String key) {\n Validate.notNull(key);\n key = key.trim();\n Validate.notEmpty(key); // trimming could potentially make empty, so validate here\n if (parent != null) {\n int i = parent.indexOfKey(this.key);\n if (i != Attributes.NotFound)\n parent.keys[i] = key;\n }\n this.key = key;\n }\n\n /**\n Get the attribute value. Will return an empty string if the value is not set.\n @return the attribute value\n */\n @Override\n public String getValue() {\n return Attributes.checkNotNull(val);\n }\n\n /**\n * Check if this Attribute has a value. Set boolean attributes have no value.\n * @return if this is a boolean attribute / attribute without a value\n */\n public boolean hasDeclaredValue() {\n return val != null;\n }\n\n /**\n Set the attribute value.\n @param val the new attribute value; may be null (to set an enabled boolean attribute)\n @return the previous value (if was null; an empty string)\n */\n public String setValue(@Nullable String val) {\n String oldVal = this.val;\n if (parent != null) {\n int i = parent.indexOfKey(this.key);\n if (i != Attributes.NotFound) {\n oldVal = parent.get(this.key); // trust the container more\n parent.vals[i] = val;\n }\n }\n this.val = val;\n return Attributes.checkNotNull(oldVal);\n }\n\n /**\n Get the HTML representation of this attribute; e.g. {@code href=\"index.html\"}.\n @return HTML\n */\n public String html() {\n StringBuilder sb = StringUtil.borrowBuilder();\n \n try {\n \thtml(sb, (new Document(\"\")).outputSettings());\n } catch(IOException exception) {\n \tthrow new SerializationException(exception);\n }\n return StringUtil.releaseBuilder(sb);\n }\n\n protected void html(Appendable accum, Document.OutputSettings out) throws IOException {\n html(key, val, accum, out);\n }\n\n protected static void html(String key, @Nullable String val, Appendable accum, Document.OutputSettings out) throws IOException {\n key = getValidKey(key, out.syntax());\n if (key == null) return; // can't write it :(\n htmlNoValidate(key, val, accum, out);\n }\n\n static void htmlNoValidate(String key, @Nullable String val, Appendable accum, Document.OutputSettings out) throws IOException {\n // structured like this so that Attributes can check we can write first, so it can add whitespace correctly\n accum.append(key);\n if (!shouldCollapseAttribute(key, val, out)) {\n accum.append(\"=\\\"\");\n Entities.escape(accum, Attributes.checkNotNull(val) , out, true, false, false);\n accum.append('\"');\n }\n }\n\n private static final Pattern xmlKeyValid = Pattern.compile(\"[a-zA-Z_:][-a-zA-Z0-9_:.]*\");\n private static final Pattern xmlKeyReplace = Pattern.compile(\"[^-a-zA-Z0-9_:.]\");\n private static final Pattern htmlKeyValid = Pattern.compile(\"[^\\\\x00-\\\\x1f\\\\x7f-\\\\x9f \\\"'/=]+\");\n private static final Pattern htmlKeyReplace = Pattern.compile(\"[\\\\x00-\\\\x1f\\\\x7f-\\\\x9f \\\"'/=]\");\n\n @Nullable public static String getValidKey(String key, Syntax syntax) {\n // we consider HTML attributes to always be valid. XML checks key validity\n if (syntax == Syntax.xml && !xmlKeyValid.matcher(key).matches()) {\n key = xmlKeyReplace.matcher(key).replaceAll(\"\");\n return xmlKeyValid.matcher(key).matches() ? key : null; // null if could not be coerced\n }\n else if (syntax == Syntax.html && !htmlKeyValid.matcher(key).matches()) {\n key = htmlKeyReplace.matcher(key).replaceAll(\"\");\n return htmlKeyValid.matcher(key).matches() ? key : null; // null if could not be coerced\n }\n return key;\n }\n\n /**\n Get the string representation of this attribute, implemented as {@link #html()}.\n @return string\n */\n @Override\n public String toString() {\n return html();\n }\n\n /**\n * Create a new Attribute from an unencoded key and a HTML attribute encoded value.\n * @param unencodedKey assumes the key is not encoded, as can be only run of simple \\w chars.\n * @param encodedValue HTML attribute encoded value\n * @return attribute\n */\n public static Attribute createFromEncoded(String unencodedKey, String encodedValue) {\n String value = Entities.unescape(encodedValue, true);\n return new Attribute(unencodedKey, value, null); // parent will get set when Put\n }\n\n protected boolean isDataAttribute() {\n return isDataAttribute(key);\n }\n\n protected static boolean isDataAttribute(String key) {\n return key.startsWith(Attributes.dataPrefix) && key.length() > Attributes.dataPrefix.length();\n }\n\n /**\n * Collapsible if it's a boolean attribute and value is empty or same as name\n * \n * @param out output settings\n * @return Returns whether collapsible or not\n */\n protected final boolean shouldCollapseAttribute(Document.OutputSettings out) {\n return shouldCollapseAttribute(key, val, out);\n }\n\n // collapse unknown foo=null, known checked=null, checked=\"\", checked=checked; write out others\n protected static boolean shouldCollapseAttribute(final String key, @Nullable final String val, final Document.OutputSettings out) {\n return (\n out.syntax() == Syntax.html &&\n (val == null || (val.isEmpty() || val.equalsIgnoreCase(key)) && Attribute.isBooleanAttribute(key)));\n }\n\n /**\n * Checks if this attribute name is defined as a boolean attribute in HTML5\n */\n public static boolean isBooleanAttribute(final String key) {\n return Arrays.binarySearch(booleanAttributes, Normalizer.lowerCase(key)) >= 0;\n }\n\n @Override\n public boolean equals(@Nullable Object o) { // note parent not considered\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Attribute attribute = (Attribute) o;\n if (key != null ? !key.equals(attribute.key) : attribute.key != null) return false;\n return val != null ? val.equals(attribute.val) : attribute.val == null;\n }\n\n @Override\n public int hashCode() { // note parent not considered\n int result = key != null ? key.hashCode() : 0;\n result = 31 * result + (val != null ? val.hashCode() : 0);\n return result;\n }\n\n @Override\n public Attribute clone() {\n try {\n return (Attribute) super.clone();\n } catch (CloneNotSupportedException e) {\n throw new RuntimeException(e);\n }\n }\n}", "public class Attributes implements Iterable<Attribute>, Cloneable {\n // The Attributes object is only created on the first use of an attribute; the Element will just have a null\n // Attribute slot otherwise\n protected static final String dataPrefix = \"data-\";\n // Indicates a jsoup internal key. Can't be set via HTML. (It could be set via accessor, but not too worried about\n // that. Suppressed from list, iter.\n static final char InternalPrefix = '/';\n private static final int InitialCapacity = 3; // sampling found mean count when attrs present = 1.49; 1.08 overall. 2.6:1 don't have any attrs.\n\n // manages the key/val arrays\n private static final int GrowthFactor = 2;\n static final int NotFound = -1;\n private static final String EmptyString = \"\";\n\n // the number of instance fields is kept as low as possible giving an object size of 24 bytes\n private int size = 0; // number of slots used (not total capacity, which is keys.length)\n String[] keys = new String[InitialCapacity];\n String[] vals = new String[InitialCapacity];\n\n // check there's room for more\n private void checkCapacity(int minNewSize) {\n Validate.isTrue(minNewSize >= size);\n int curCap = keys.length;\n if (curCap >= minNewSize)\n return;\n int newCap = curCap >= InitialCapacity ? size * GrowthFactor : InitialCapacity;\n if (minNewSize > newCap)\n newCap = minNewSize;\n\n keys = Arrays.copyOf(keys, newCap);\n vals = Arrays.copyOf(vals, newCap);\n }\n\n int indexOfKey(String key) {\n Validate.notNull(key);\n for (int i = 0; i < size; i++) {\n if (key.equals(keys[i]))\n return i;\n }\n return NotFound;\n }\n\n private int indexOfKeyIgnoreCase(String key) {\n Validate.notNull(key);\n for (int i = 0; i < size; i++) {\n if (key.equalsIgnoreCase(keys[i]))\n return i;\n }\n return NotFound;\n }\n\n // we track boolean attributes as null in values - they're just keys. so returns empty for consumers\n static String checkNotNull(@Nullable String val) {\n return val == null ? EmptyString : val;\n }\n\n /**\n Get an attribute value by key.\n @param key the (case-sensitive) attribute key\n @return the attribute value if set; or empty string if not set (or a boolean attribute).\n @see #hasKey(String)\n */\n public String get(String key) {\n int i = indexOfKey(key);\n return i == NotFound ? EmptyString : checkNotNull(vals[i]);\n }\n\n /**\n * Get an attribute's value by case-insensitive key\n * @param key the attribute name\n * @return the first matching attribute value if set; or empty string if not set (ora boolean attribute).\n */\n public String getIgnoreCase(String key) {\n int i = indexOfKeyIgnoreCase(key);\n return i == NotFound ? EmptyString : checkNotNull(vals[i]);\n }\n\n /**\n * Adds a new attribute. Will produce duplicates if the key already exists.\n * @see Attributes#put(String, String)\n */\n public Attributes add(String key, @Nullable String value) {\n checkCapacity(size + 1);\n keys[size] = key;\n vals[size] = value;\n size++;\n return this;\n }\n\n /**\n * Set a new attribute, or replace an existing one by key.\n * @param key case sensitive attribute key (not null)\n * @param value attribute value (may be null, to set a boolean attribute)\n * @return these attributes, for chaining\n */\n public Attributes put(String key, @Nullable String value) {\n Validate.notNull(key);\n int i = indexOfKey(key);\n if (i != NotFound)\n vals[i] = value;\n else\n add(key, value);\n return this;\n }\n\n void putIgnoreCase(String key, @Nullable String value) {\n int i = indexOfKeyIgnoreCase(key);\n if (i != NotFound) {\n vals[i] = value;\n if (!keys[i].equals(key)) // case changed, update\n keys[i] = key;\n }\n else\n add(key, value);\n }\n\n /**\n * Set a new boolean attribute, remove attribute if value is false.\n * @param key case <b>insensitive</b> attribute key\n * @param value attribute value\n * @return these attributes, for chaining\n */\n public Attributes put(String key, boolean value) {\n if (value)\n putIgnoreCase(key, null);\n else\n remove(key);\n return this;\n }\n\n /**\n Set a new attribute, or replace an existing one by key.\n @param attribute attribute with case sensitive key\n @return these attributes, for chaining\n */\n public Attributes put(Attribute attribute) {\n Validate.notNull(attribute);\n put(attribute.getKey(), attribute.getValue());\n attribute.parent = this;\n return this;\n }\n\n // removes and shifts up\n @SuppressWarnings(\"AssignmentToNull\")\n private void remove(int index) {\n Validate.isFalse(index >= size);\n int shifted = size - index - 1;\n if (shifted > 0) {\n System.arraycopy(keys, index + 1, keys, index, shifted);\n System.arraycopy(vals, index + 1, vals, index, shifted);\n }\n size--;\n keys[size] = null; // release hold\n vals[size] = null;\n }\n\n /**\n Remove an attribute by key. <b>Case sensitive.</b>\n @param key attribute key to remove\n */\n public void remove(String key) {\n int i = indexOfKey(key);\n if (i != NotFound)\n remove(i);\n }\n\n /**\n Remove an attribute by key. <b>Case insensitive.</b>\n @param key attribute key to remove\n */\n public void removeIgnoreCase(String key) {\n int i = indexOfKeyIgnoreCase(key);\n if (i != NotFound)\n remove(i);\n }\n\n /**\n Tests if these attributes contain an attribute with this key.\n @param key case-sensitive key to check for\n @return true if key exists, false otherwise\n */\n public boolean hasKey(String key) {\n return indexOfKey(key) != NotFound;\n }\n\n /**\n Tests if these attributes contain an attribute with this key.\n @param key key to check for\n @return true if key exists, false otherwise\n */\n public boolean hasKeyIgnoreCase(String key) {\n return indexOfKeyIgnoreCase(key) != NotFound;\n }\n\n /**\n * Check if these attributes contain an attribute with a value for this key.\n * @param key key to check for\n * @return true if key exists, and it has a value\n */\n public boolean hasDeclaredValueForKey(String key) {\n int i = indexOfKey(key);\n return i != NotFound && vals[i] != null;\n }\n\n /**\n * Check if these attributes contain an attribute with a value for this key.\n * @param key case-insensitive key to check for\n * @return true if key exists, and it has a value\n */\n public boolean hasDeclaredValueForKeyIgnoreCase(String key) {\n int i = indexOfKeyIgnoreCase(key);\n return i != NotFound && vals[i] != null;\n }\n\n /**\n Get the number of attributes in this set, including any jsoup internal-only attributes. Internal attributes are\n excluded from the {@link #html()}, {@link #asList()}, and {@link #iterator()} methods.\n @return size\n */\n public int size() {\n return size;\n }\n\n /**\n * Test if this Attributes list is empty (size==0).\n */\n public boolean isEmpty() {\n return size == 0;\n }\n\n /**\n Add all the attributes from the incoming set to this set.\n @param incoming attributes to add to these attributes.\n */\n public void addAll(Attributes incoming) {\n if (incoming.size() == 0)\n return;\n checkCapacity(size + incoming.size);\n\n boolean needsPut = size != 0; // if this set is empty, no need to check existing set, so can add() vs put()\n // (and save bashing on the indexOfKey()\n for (Attribute attr : incoming) {\n if (needsPut)\n put(attr);\n else\n add(attr.getKey(), attr.getValue());\n }\n }\n\n public Iterator<Attribute> iterator() {\n return new Iterator<Attribute>() {\n int i = 0;\n\n @Override\n public boolean hasNext() {\n while (i < size) {\n if (isInternalKey(keys[i])) // skip over internal keys\n i++;\n else\n break;\n }\n\n return i < size;\n }\n\n @Override\n public Attribute next() {\n final Attribute attr = new Attribute(keys[i], vals[i], Attributes.this);\n i++;\n return attr;\n }\n\n @Override\n public void remove() {\n Attributes.this.remove(--i); // next() advanced, so rewind\n }\n };\n }\n\n /**\n Get the attributes as a List, for iteration.\n @return an view of the attributes as an unmodifiable List.\n */\n public List<Attribute> asList() {\n ArrayList<Attribute> list = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n if (isInternalKey(keys[i]))\n continue; // skip internal keys\n Attribute attr = new Attribute(keys[i], vals[i], Attributes.this);\n list.add(attr);\n }\n return Collections.unmodifiableList(list);\n }\n\n /**\n * Retrieves a filtered view of attributes that are HTML5 custom data attributes; that is, attributes with keys\n * starting with {@code data-}.\n * @return map of custom data attributes.\n */\n public Map<String, String> dataset() {\n return new Dataset(this);\n }\n\n /**\n Get the HTML representation of these attributes.\n @return HTML\n */\n public String html() {\n StringBuilder sb = StringUtil.borrowBuilder();\n try {\n html(sb, (new Document(\"\")).outputSettings()); // output settings a bit funky, but this html() seldom used\n } catch (IOException e) { // ought never happen\n throw new SerializationException(e);\n }\n return StringUtil.releaseBuilder(sb);\n }\n\n final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {\n final int sz = size;\n for (int i = 0; i < sz; i++) {\n if (isInternalKey(keys[i]))\n continue;\n final String key = Attribute.getValidKey(keys[i], out.syntax());\n if (key != null)\n Attribute.htmlNoValidate(key, vals[i], accum.append(' '), out);\n }\n }\n\n @Override\n public String toString() {\n return html();\n }\n\n /**\n * Checks if these attributes are equal to another set of attributes, by comparing the two sets. Note that the order\n * of the attributes does not impact this equality (as per the Map interface equals()).\n * @param o attributes to compare with\n * @return if both sets of attributes have the same content\n */\n @Override\n public boolean equals(@Nullable Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Attributes that = (Attributes) o;\n if (size != that.size) return false;\n for (int i = 0; i < size; i++) {\n String key = keys[i];\n int thatI = that.indexOfKey(key);\n if (thatI == NotFound)\n return false;\n String val = vals[i];\n String thatVal = that.vals[thatI];\n if (val == null) {\n if (thatVal != null)\n return false;\n } else if (!val.equals(thatVal))\n return false;\n }\n return true;\n }\n\n /**\n * Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes.\n * @return calculated hashcode\n */\n @Override\n public int hashCode() {\n int result = size;\n result = 31 * result + Arrays.hashCode(keys);\n result = 31 * result + Arrays.hashCode(vals);\n return result;\n }\n\n @Override\n public Attributes clone() {\n Attributes clone;\n try {\n clone = (Attributes) super.clone();\n } catch (CloneNotSupportedException e) {\n throw new RuntimeException(e);\n }\n clone.size = size;\n clone.keys = Arrays.copyOf(keys, size);\n clone.vals = Arrays.copyOf(vals, size);\n return clone;\n }\n\n /**\n * Internal method. Lowercases all keys.\n */\n public void normalize() {\n for (int i = 0; i < size; i++) {\n keys[i] = lowerCase(keys[i]);\n }\n }\n\n /**\n * Internal method. Removes duplicate attribute by name. Settings for case sensitivity of key names.\n * @param settings case sensitivity\n * @return number of removed dupes\n */\n public int deduplicate(ParseSettings settings) {\n if (isEmpty())\n return 0;\n boolean preserve = settings.preserveAttributeCase();\n int dupes = 0;\n OUTER: for (int i = 0; i < keys.length; i++) {\n for (int j = i + 1; j < keys.length; j++) {\n if (keys[j] == null)\n continue OUTER; // keys.length doesn't shrink when removing, so re-test\n if ((preserve && keys[i].equals(keys[j])) || (!preserve && keys[i].equalsIgnoreCase(keys[j]))) {\n dupes++;\n remove(j);\n j--;\n }\n }\n }\n return dupes;\n }\n\n private static class Dataset extends AbstractMap<String, String> {\n private final Attributes attributes;\n\n private Dataset(Attributes attributes) {\n this.attributes = attributes;\n }\n\n @Override\n public Set<Entry<String, String>> entrySet() {\n return new EntrySet();\n }\n\n @Override\n public String put(String key, String value) {\n String dataKey = dataKey(key);\n String oldValue = attributes.hasKey(dataKey) ? attributes.get(dataKey) : null;\n attributes.put(dataKey, value);\n return oldValue;\n }\n\n private class EntrySet extends AbstractSet<Map.Entry<String, String>> {\n\n @Override\n public Iterator<Map.Entry<String, String>> iterator() {\n return new DatasetIterator();\n }\n\n @Override\n public int size() {\n int count = 0;\n Iterator iter = new DatasetIterator();\n while (iter.hasNext())\n count++;\n return count;\n }\n }\n\n private class DatasetIterator implements Iterator<Map.Entry<String, String>> {\n private Iterator<Attribute> attrIter = attributes.iterator();\n private Attribute attr;\n public boolean hasNext() {\n while (attrIter.hasNext()) {\n attr = attrIter.next();\n if (attr.isDataAttribute()) return true;\n }\n return false;\n }\n\n public Entry<String, String> next() {\n return new Attribute(attr.getKey().substring(dataPrefix.length()), attr.getValue());\n }\n\n public void remove() {\n attributes.remove(attr.getKey());\n }\n }\n }\n\n private static String dataKey(String key) {\n return dataPrefix + key;\n }\n\n static String internalKey(String key) {\n return InternalPrefix + key;\n }\n\n private boolean isInternalKey(String key) {\n return key != null && key.length() > 1 && key.charAt(0) == InternalPrefix;\n }\n}", "public class NodeTraversor {\n /**\n * Start a depth-first traverse of the root and all of its descendants.\n * @param visitor Node visitor.\n * @param root the root node point to traverse.\n */\n public static void traverse(NodeVisitor visitor, Node root) {\n Validate.notNull(visitor);\n Validate.notNull(root);\n Node node = root;\n int depth = 0;\n \n while (node != null) {\n Node parent = node.parentNode(); // remember parent to find nodes that get replaced in .head\n int origSize = parent != null ? parent.childNodeSize() : 0;\n Node next = node.nextSibling();\n\n visitor.head(node, depth); // visit current node\n if (parent != null && !node.hasParent()) { // removed or replaced\n if (origSize == parent.childNodeSize()) { // replaced\n node = parent.childNode(node.siblingIndex()); // replace ditches parent but keeps sibling index\n } else { // removed\n node = next;\n if (node == null) { // last one, go up\n node = parent;\n depth--;\n }\n continue; // don't tail removed\n }\n }\n\n if (node.childNodeSize() > 0) { // descend\n node = node.childNode(0);\n depth++;\n } else {\n while (true) {\n assert node != null; // as depth > 0, will have parent\n if (!(node.nextSibling() == null && depth > 0)) break;\n visitor.tail(node, depth); // when no more siblings, ascend\n node = node.parentNode();\n depth--;\n }\n visitor.tail(node, depth);\n if (node == root)\n break;\n node = node.nextSibling();\n }\n }\n }\n\n /**\n * Start a depth-first traverse of all elements.\n * @param visitor Node visitor.\n * @param elements Elements to filter.\n */\n public static void traverse(NodeVisitor visitor, Elements elements) {\n Validate.notNull(visitor);\n Validate.notNull(elements);\n for (Element el : elements)\n traverse(visitor, el);\n }\n\n /**\n * Start a depth-first filtering of the root and all of its descendants.\n * @param filter Node visitor.\n * @param root the root node point to traverse.\n * @return The filter result of the root node, or {@link FilterResult#STOP}.\n */\n public static FilterResult filter(NodeFilter filter, Node root) {\n Node node = root;\n int depth = 0;\n\n while (node != null) {\n FilterResult result = filter.head(node, depth);\n if (result == FilterResult.STOP)\n return result;\n // Descend into child nodes:\n if (result == FilterResult.CONTINUE && node.childNodeSize() > 0) {\n node = node.childNode(0);\n ++depth;\n continue;\n }\n // No siblings, move upwards:\n while (true) {\n assert node != null; // depth > 0, so has parent\n if (!(node.nextSibling() == null && depth > 0)) break;\n // 'tail' current node:\n if (result == FilterResult.CONTINUE || result == FilterResult.SKIP_CHILDREN) {\n result = filter.tail(node, depth);\n if (result == FilterResult.STOP)\n return result;\n }\n Node prev = node; // In case we need to remove it below.\n node = node.parentNode();\n depth--;\n if (result == FilterResult.REMOVE)\n prev.remove(); // Remove AFTER finding parent.\n result = FilterResult.CONTINUE; // Parent was not pruned.\n }\n // 'tail' current node, then proceed with siblings:\n if (result == FilterResult.CONTINUE || result == FilterResult.SKIP_CHILDREN) {\n result = filter.tail(node, depth);\n if (result == FilterResult.STOP)\n return result;\n }\n if (node == root)\n return result;\n Node prev = node; // In case we need to remove it below.\n node = node.nextSibling();\n if (result == FilterResult.REMOVE)\n prev.remove(); // Remove AFTER finding sibling.\n }\n // root == null?\n return FilterResult.CONTINUE;\n }\n\n /**\n * Start a depth-first filtering of all elements.\n * @param filter Node filter.\n * @param elements Elements to filter.\n */\n public static void filter(NodeFilter filter, Elements elements) {\n Validate.notNull(filter);\n Validate.notNull(elements);\n for (Element el : elements)\n if (filter(filter, el) == FilterResult.STOP)\n break;\n }\n}", "public interface NodeVisitor {\n /**\n Callback for when a node is first visited.\n <p>The node may be modified (e.g. {@link Node#attr(String)}, replaced {@link Node#replaceWith(Node)}) or removed\n {@link Node#remove()}. If it's {@code instanceOf Element}, you may cast it to an {@link Element} and access those\n methods.</p>\n\n @param node the node being visited.\n @param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node\n of that will have depth 1.\n */\n void head(Node node, int depth);\n\n /**\n Callback for when a node is last visited, after all of its descendants have been visited.\n <p>This method has a default no-op implementation.</p>\n <p>Note that neither replacement with {@link Node#replaceWith(Node)} nor removal with {@link Node#remove()} is\n supported during {@code tail()}.\n\n @param node the node being visited.\n @param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node\n of that will have depth 1.\n */\n default void tail(Node node, int depth) {\n // no-op by default, to allow just specifying the head() method\n }\n}", "public class Selector {\n // not instantiable\n private Selector() {}\n\n /**\n * Find elements matching selector.\n *\n * @param query CSS selector\n * @param root root element to descend into\n * @return matching elements, empty if none\n * @throws Selector.SelectorParseException (unchecked) on an invalid CSS query.\n */\n public static Elements select(String query, Element root) {\n Validate.notEmpty(query);\n return select(QueryParser.parse(query), root);\n }\n\n /**\n * Find elements matching selector.\n *\n * @param evaluator CSS selector\n * @param root root element to descend into\n * @return matching elements, empty if none\n */\n public static Elements select(Evaluator evaluator, Element root) {\n Validate.notNull(evaluator);\n Validate.notNull(root);\n return Collector.collect(evaluator, root);\n }\n\n /**\n * Find elements matching selector.\n *\n * @param query CSS selector\n * @param roots root elements to descend into\n * @return matching elements, empty if none\n */\n public static Elements select(String query, Iterable<Element> roots) {\n Validate.notEmpty(query);\n Validate.notNull(roots);\n Evaluator evaluator = QueryParser.parse(query);\n Elements elements = new Elements();\n IdentityHashMap<Element, Boolean> seenElements = new IdentityHashMap<>();\n // dedupe elements by identity, not equality\n\n for (Element root : roots) {\n final Elements found = select(evaluator, root);\n for (Element el : found) {\n if (seenElements.put(el, Boolean.TRUE) == null) {\n elements.add(el);\n }\n }\n }\n return elements;\n }\n\n // exclude set. package open so that Elements can implement .not() selector.\n static Elements filterOut(Collection<Element> elements, Collection<Element> outs) {\n Elements output = new Elements();\n for (Element el : elements) {\n boolean found = false;\n for (Element out : outs) {\n if (el.equals(out)) {\n found = true;\n break;\n }\n }\n if (!found)\n output.add(el);\n }\n return output;\n }\n\n /**\n * Find the first element that matches the query.\n * @param cssQuery CSS selector\n * @param root root element to descend into\n * @return the matching element, or <b>null</b> if none.\n */\n public static @Nullable Element selectFirst(String cssQuery, Element root) {\n Validate.notEmpty(cssQuery);\n return Collector.findFirst(QueryParser.parse(cssQuery), root);\n }\n\n public static class SelectorParseException extends IllegalStateException {\n public SelectorParseException(String msg) {\n super(msg);\n }\n\n public SelectorParseException(String msg, Object... params) {\n super(String.format(msg, params));\n }\n }\n}", "public enum Syntax {html, xml}" ]
import org.jsoup.internal.StringUtil; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Attributes; import org.jsoup.select.NodeTraversor; import org.jsoup.select.NodeVisitor; import org.jsoup.select.Selector; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactoryConfigurationException; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Stack; import static javax.xml.transform.OutputKeys.METHOD; import static org.jsoup.nodes.Document.OutputSettings.Syntax;
for (int i = 0; i < nodeList.getLength(); i++) { org.w3c.dom.Node node = nodeList.item(i); Object source = node.getUserData(W3CDom.SourceProperty); if (nodeType.isInstance(source)) nodes.add(nodeType.cast(source)); } return nodes; } /** For a Document created by {@link #fromJsoup(org.jsoup.nodes.Element)}, retrieves the W3C context node. @param wDoc Document created by this class @return the corresponding W3C Node to the jsoup Element that was used as the creating context. */ public Node contextNode(Document wDoc) { return (Node) wDoc.getUserData(ContextNodeProperty); } /** * Serialize a W3C document to a String. The output format will be XML or HTML depending on the content of the doc. * * @param doc Document * @return Document as string * @see W3CDom#asString(Document, Map) */ public String asString(Document doc) { return asString(doc, null); } /** * Implements the conversion by walking the input. */ protected static class W3CBuilder implements NodeVisitor { private static final String xmlnsKey = "xmlns"; private static final String xmlnsPrefix = "xmlns:"; private final Document doc; private final Stack<HashMap<String, String>> namespacesStack = new Stack<>(); // stack of namespaces, prefix => urn private Node dest; private Syntax syntax = Syntax.xml; // the syntax (to coerce attributes to). From the input doc if available. @Nullable private final org.jsoup.nodes.Element contextElement; public W3CBuilder(Document doc) { this.doc = doc; namespacesStack.push(new HashMap<>()); dest = doc; contextElement = (org.jsoup.nodes.Element) doc.getUserData(ContextProperty); // Track the context jsoup Element, so we can save the corresponding w3c element } public void head(org.jsoup.nodes.Node source, int depth) { namespacesStack.push(new HashMap<>(namespacesStack.peek())); // inherit from above on the stack if (source instanceof org.jsoup.nodes.Element) { org.jsoup.nodes.Element sourceEl = (org.jsoup.nodes.Element) source; String prefix = updateNamespaces(sourceEl); String namespace = namespacesStack.peek().get(prefix); String tagName = sourceEl.tagName(); /* Tag names in XML are quite permissive, but less permissive than HTML. Rather than reimplement the validation, we just try to use it as-is. If it fails, insert as a text node instead. We don't try to normalize the tagname to something safe, because that isn't going to be meaningful downstream. This seems(?) to be how browsers handle the situation, also. https://github.com/jhy/jsoup/issues/1093 */ try { Element el = namespace == null && tagName.contains(":") ? doc.createElementNS("", tagName) : // doesn't have a real namespace defined doc.createElementNS(namespace, tagName); copyAttributes(sourceEl, el); append(el, sourceEl); if (sourceEl == contextElement) doc.setUserData(ContextNodeProperty, el, null); dest = el; // descend } catch (DOMException e) { append(doc.createTextNode("<" + tagName + ">"), sourceEl); } } else if (source instanceof org.jsoup.nodes.TextNode) { org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source; Text text = doc.createTextNode(sourceText.getWholeText()); append(text, sourceText); } else if (source instanceof org.jsoup.nodes.Comment) { org.jsoup.nodes.Comment sourceComment = (org.jsoup.nodes.Comment) source; Comment comment = doc.createComment(sourceComment.getData()); append(comment, sourceComment); } else if (source instanceof org.jsoup.nodes.DataNode) { org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source; Text node = doc.createTextNode(sourceData.getWholeData()); append(node, sourceData); } else { // unhandled. note that doctype is not handled here - rather it is used in the initial doc creation } } private void append(Node append, org.jsoup.nodes.Node source) { append.setUserData(SourceProperty, source, null); dest.appendChild(append); } public void tail(org.jsoup.nodes.Node source, int depth) { if (source instanceof org.jsoup.nodes.Element && dest.getParentNode() instanceof Element) { dest = dest.getParentNode(); // undescend } namespacesStack.pop(); } private void copyAttributes(org.jsoup.nodes.Node source, Element el) { for (Attribute attribute : source.attributes()) { String key = Attribute.getValidKey(attribute.getKey(), syntax); if (key != null) { // null if couldn't be coerced to validity el.setAttribute(key, attribute.getValue()); } } } /** * Finds any namespaces defined in this element. Returns any tag prefix. */ private String updateNamespaces(org.jsoup.nodes.Element el) { // scan the element for namespace declarations // like: xmlns="blah" or xmlns:prefix="blah"
Attributes attributes = el.attributes();
2
Skyost/SkyDocs
src/main/java/fr/skyost/skydocs/DocsMenu.java
[ "public class InvalidMenuDataException extends Exception {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic InvalidMenuDataException(final String message) {\n\t\tsuper(message);\n\t}\n\t\n\tpublic InvalidMenuDataException(final Exception ex) {\n\t\tsuper(ex);\n\t}\n\t\n}", "public class InvalidMenuEntryException extends Exception {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic InvalidMenuEntryException(final String message) {\n\t\tsuper(message);\n\t}\n\t\n\tpublic InvalidMenuEntryException(final Exception ex) {\n\t\tsuper(ex);\n\t}\n\t\n}", "public class IncludeFileFunction extends SimpleJtwigFunction {\r\n\t\r\n\t/**\r\n\t * The pattern that will be rendered when <i>render</i> is set to false.\r\n\t */\r\n\t\r\n\tprivate static final Pattern PARTIAL_RENDER_PATTERN = Pattern.compile(\"\\\\{\\\\{[ ]*\" + Constants.FUNCTION_INCLUDE_FILE + \"\\\\(\\\"([^\\\"]|\\\\\\\\\\\")*\\\"\\\\)[ ]{0,}}}\");\r\n\t\r\n\t/**\r\n\t * The directory (where you look up for files).\r\n\t */\r\n\t\r\n\tprivate final File directory;\r\n\t\r\n\t/**\r\n\t * The current jtwig model.\r\n\t */\r\n\t\r\n\tprivate JtwigModel model;\r\n\t\r\n\t/**\r\n\t * If the function should entirely render the file.\r\n\t */\r\n\t\r\n\tprivate final boolean render;\r\n\t\r\n\t/**\r\n\t * Functions to use for parsing files.\r\n\t */\r\n\t\r\n\tprivate final JtwigFunction[] functions;\r\n\t\r\n\t/**\r\n\t * Creates a new IncludeFileFunction instance.\r\n\t * \r\n\t * @param directory Where to find files.\r\n\t * @param model The jtwig model.\r\n\t * @param functions The functions (used to render).\r\n\t */\r\n\t\r\n\tpublic IncludeFileFunction(final File directory, final JtwigModel model, final JtwigFunction... functions) {\r\n\t\tthis(directory, model, true, functions);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Creates a new IncludeFileFunction instance.\r\n\t * \r\n\t * @param directory Where to find files.\r\n\t * @param model The jtwig model.\r\n\t * @param render If the file should be entirely rendered.\r\n\t * @param functions The functions (used to render).\r\n\t */\r\n\t\r\n\tpublic IncludeFileFunction(final File directory, final JtwigModel model, final boolean render, final JtwigFunction... functions) {\r\n\t\tthis.directory = directory;\r\n\t\tthis.model = model;\r\n\t\tthis.render = render;\r\n\t\tthis.functions = functions == null ? new JtwigFunction[0] : functions;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final String name() {\r\n\t\treturn Constants.FUNCTION_INCLUDE_FILE;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic final Object execute(final FunctionRequest functionRequest) {\r\n\t\tif(functionRequest.getNumberOfArguments() == 0) {\r\n\t\t\treturn \"You must specify a file in \" + Constants.FUNCTION_INCLUDE_FILE + \".\";\r\n\t\t}\r\n\t\tfinal String fileName = functionRequest.getArguments().get(0).toString();\r\n\t\ttry {\r\n\t\t\tfinal File file = new File(directory.getPath() + File.separator + fileName);\r\n\t\t\tif(!file.exists() || !file.isFile()) {\r\n\t\t\t\treturn \"Incorrect path given : \" + directory.getPath() + fileName;\r\n\t\t\t}\r\n\t\t\tif(!render) {\r\n\t\t\t\treturn renderIncludeFile(file);\r\n\t\t\t}\r\n\t\t\tfinal EnvironmentConfiguration configuration = EnvironmentConfigurationBuilder.configuration().functions().add(this).add(Arrays.asList(functions)).and().build();\r\n\t\t\treturn JtwigTemplate.fileTemplate(file, configuration).render(model);\r\n\t\t}\r\n\t\tcatch(final Exception ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t\treturn \"Unable to parse \" + directory.getPath() + File.separator + fileName + \" (\" + ex.getClass().getName() + \")\";\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the current model.\r\n\t * \r\n\t * @return The current model.\r\n\t */\r\n\t\r\n\tpublic final JtwigModel getModel() {\r\n\t\treturn model;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Sets the current model.\r\n\t * \r\n\t * @param model The new model.\r\n\t */\r\n\t\r\n\tpublic final void setModel(final JtwigModel model) {\r\n\t\tthis.model = model;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Renders a String but process only include file functions.\r\n\t * \r\n\t * @param file File to render.\r\n\t * \r\n\t * @return Rendered String.\r\n\t * \r\n\t * @throws IOException If any exception occurs while reading the file.\r\n\t */\r\n\t\r\n\tpublic final String renderIncludeFile(final File file) throws IOException {\r\n\t\treturn renderIncludeFile(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Renders a String but process only include file functions.\r\n\t * \r\n\t * @param toRender String to render.\r\n\t * \r\n\t * @return The rendered String.\r\n\t */\r\n\t\r\n\tpublic final String renderIncludeFile(String toRender) {\r\n\t\tfinal EnvironmentConfiguration configuration = EnvironmentConfigurationBuilder.configuration().functions().add(this).add(Arrays.asList(functions)).and().build();\r\n\t\tfinal Matcher matcher = PARTIAL_RENDER_PATTERN.matcher(toRender);\r\n\t\twhile(matcher.find()) {\r\n\t\t\tfinal String matching = matcher.group();\r\n\t\t\ttoRender = toRender.replace(matching, JtwigTemplate.inlineTemplate(matching, configuration).render(model));\r\n\t\t}\r\n\t\treturn toRender;\r\n\t}\r\n\t\r\n}", "public class Utils {\r\n\t\r\n\t/**\r\n\t * System independent line separator.\r\n\t */\r\n\t\r\n\tpublic static final String LINE_SEPARATOR = System.lineSeparator();\r\n\t\r\n\t/**\r\n\t * The auto refresh page script.\r\n\t */\r\n\t\r\n\tpublic static final String AUTO_REFRESH_SCRIPT;\r\n\t\r\n\tstatic {\r\n\t\tfinal AutoLineBreakStringBuilder builder = new AutoLineBreakStringBuilder(Utils.LINE_SEPARATOR + \"<!-- Auto refresh script, this is not part of your built page so just ignore it ! -->\");\r\n\t\tbuilder.append(\"<script type=\\\"text/javascript\\\">\");\r\n\t\tbuilder.append(\"var lastRefresh = new Date().getTime();\");\r\n\t\tbuilder.append(\"function httpGetAsync() {\");\r\n\t\tbuilder.append(\"\tvar request = new XMLHttpRequest();\");\r\n\t\tbuilder.append(\"\trequest.onreadystatechange = function() { \");\r\n\t\tbuilder.append(\"\t\tif(request.readyState == 4) {\");\r\n\t\tbuilder.append(\"\t\t\tif(request.status == 200 && lastRefresh < request.responseText) {\");\r\n\t\tbuilder.append(\"\t\t\t\tlocation.reload();\");\r\n\t\tbuilder.append(\"\t\t\t\treturn;\");\r\n\t\tbuilder.append(\"\t\t\t}\");\r\n\t\tbuilder.append(\"\t\t\tsetTimeout(httpGetAsync, \" + Constants.SERVE_FILE_POLLING_INTERVAL + \");\");\r\n\t\tbuilder.append(\"\t\t}\");\r\n\t\tbuilder.append(\"\t}\");\r\n\t\tbuilder.append(\"\trequest.open('GET', '/\" + Constants.SERVE_LASTBUILD_URL + \"', true);\");\r\n\t\tbuilder.append(\"\trequest.send(null);\");\r\n\t\tbuilder.append(\"}\");\r\n\t\tbuilder.append(\"httpGetAsync();\");\r\n\t\tbuilder.append(\"</script>\");\r\n\t\tAUTO_REFRESH_SCRIPT = builder.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Creates a file or a directory if it does not exist.\r\n\t * \r\n\t * @param file The file or directory.\r\n\t * \r\n\t * @return The file.\r\n\t * \r\n\t * @throws IOException If an error occurs while trying to create the file.\r\n\t */\r\n\t\r\n\tpublic static File createFileIfNotExist(final File file) throws IOException {\r\n\t\tif(!file.exists()) {\r\n\t\t\tif(file.isDirectory()) {\r\n\t\t\t\tfile.mkdirs();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tfile.createNewFile();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn file;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Tries to parse an Integer from a String.\r\n\t * \r\n\t * @param string The String.\r\n\t * \r\n\t * @return The Integer or null.\r\n\t */\r\n\t\r\n\tpublic static Integer parseInt(final String string) {\r\n\t\ttry {\r\n\t\t\treturn Integer.parseInt(string);\r\n\t\t}\r\n\t\tcatch(final Exception ex) {}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Tries to parse a Boolean from a String.\r\n\t * \r\n\t * @param string The String.\r\n\t * \r\n\t * @return The Boolean or null.\r\n\t */\r\n\t\r\n\tpublic static Boolean parseBoolean(final String string) {\r\n\t\ttry {\r\n\t\t\treturn Boolean.parseBoolean(string);\r\n\t\t}\r\n\t\tcatch(final Exception ex) {}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the JAR file.\r\n\t * \r\n\t * @return The JAR file.\r\n\t */\r\n\t\r\n\tpublic static File getJARFile() {\r\n\t\ttry {\r\n\t\t\treturn new File(SkyDocs.class.getProtectionDomain().getCodeSource().getLocation().toURI());\r\n\t\t}\r\n\t\tcatch(final Exception ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the JAR parent folder.\r\n\t * \r\n\t * @return The JAR parent folder.\r\n\t */\r\n\t\r\n\tpublic static File getParentFolder() {\r\n\t\tfinal File jar = Utils.getJARFile();\r\n\t\tif(jar == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn jar.getParentFile();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Reads a file and separate header from content.\r\n\t * \r\n\t * @param file The part.\r\n\t * \r\n\t * @return A String array, index 0 is the header and index 1 is the content.\r\n\t */\r\n\t\r\n\tpublic static String[] separateFileHeader(final File file) {\r\n\t\ttry {\r\n\t\t\tfinal List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);\r\n\t\t\tif(lines.isEmpty()) {\r\n\t\t\t\treturn new String[]{null, \"\"};\r\n\t\t\t}\r\n\t\t\tif(!lines.get(0).equals(Constants.HEADER_MARK)) {\r\n\t\t\t\treturn new String[]{null, Utils.join(LINE_SEPARATOR, lines)};\r\n\t\t\t}\r\n\t\t\tint headerLimit = -1;\r\n\t\t\tfor(int i = 0; i != lines.size(); i++) {\r\n\t\t\t\tif(i != 0 && lines.get(i).equals(Constants.HEADER_MARK)) {\r\n\t\t\t\t\theaderLimit = i;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(headerLimit == -1) {\r\n\t\t\t\treturn new String[]{null, Utils.join(LINE_SEPARATOR, lines)};\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn new String[]{\r\n\t\t\t\t\tUtils.join(LINE_SEPARATOR, lines.subList(1, headerLimit)),\r\n\t\t\t\t\tUtils.join(LINE_SEPARATOR, lines.subList(headerLimit + 1, lines.size()))\r\n\t\t\t};\r\n\t\t}\r\n\t\tcatch(final Exception ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t}\r\n\t\treturn new String[]{null, null};\r\n\t}\r\n\t\r\n\t/**\r\n\t * Decodes a file's header.\r\n\t * \r\n\t * @param header The header.\r\n\t * \r\n\t * @return A map representing the YAML content key : value.\r\n\t */\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic static Map<String, Object> decodeFileHeader(final String header) {\r\n\t\tif(header == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tfinal Yaml yaml = new Yaml();\r\n\t\treturn (Map<String, Object>)yaml.load(header);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Copies a directory.\r\n\t * \r\n\t * @param directory The directory.\r\n\t * @param destination The destination.\r\n\t * \r\n\t * @throws IOException If an error occurs while trying to create the directory.\r\n\t */\r\n\t\r\n\tpublic static void copyDirectory(final File directory, final File destination) throws IOException {\r\n\t\tif(directory.isFile()) {\r\n\t\t\tFiles.copy(directory.toPath(), destination.toPath());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tdestination.mkdirs();\r\n\t\tfor(final File file : directory.listFiles()) {\r\n\t\t\tcopyDirectory(file, new File(destination, file.getName()));\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Deletes a directory.\r\n\t * \r\n\t * @param directory The directory.\r\n\t */\r\n\t\r\n\tpublic static void deleteDirectory(final File directory) {\r\n\t\tif(directory.isFile()) {\r\n\t\t\tdirectory.delete();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfor(final File file : directory.listFiles()) {\r\n\t\t\tdeleteDirectory(file);\r\n\t\t}\r\n\t\tdirectory.delete();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Extracts a file to the specified directory.\r\n\t * \r\n\t * @param path Path of the file or directory.\r\n\t * @param toExtract The file or directory to extract.\r\n\t * @param destination The destination directory.\r\n\t * \r\n\t * @throws IOException If an exception occurs when trying to extract the file.\r\n\t * @throws URISyntaxException If an exception occurs when trying to locate the file on disk.\r\n\t */\r\n\t\r\n\tpublic static void extract(final String path, final String toExtract, File destination) throws IOException, URISyntaxException {\r\n\t\tfinal File appLocation = new File(SkyDocs.class.getProtectionDomain().getCodeSource().getLocation().toURI());\r\n\t\tif(appLocation.isFile()) {\r\n\t\t\tfinal JarFile jar = new JarFile(appLocation);\r\n\t\t\tfinal Enumeration<JarEntry> enumEntries = jar.entries();\r\n\t\t\t\r\n\t\t\twhile(enumEntries.hasMoreElements()) {\r\n\t\t\t\tfinal JarEntry file = enumEntries.nextElement();\r\n\t\t\t\tif(file.isDirectory() || !file.getName().contains(path + toExtract)) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tFile destFile = new File(destination.getPath() + File.separator + file.getName().replace(path, \"\").replace(toExtract, \"\"));\r\n\t\t\t\tif(destFile.isDirectory()) {\r\n\t\t\t\t\tdestFile = new File(destFile.getPath() + File.separator + toExtract);\r\n\t\t\t\t}\r\n\t\t\t\tif(!destFile.getParentFile().exists()) {\r\n\t\t\t\t\tdestFile.getParentFile().mkdirs();\r\n\t\t\t\t}\r\n\t\t\t\tfinal InputStream is = jar.getInputStream(file);\r\n\t\t\t\tfinal FileOutputStream fos = new FileOutputStream(destFile);\r\n\t\t\t\twhile(is.available() > 0) {\r\n\t\t\t\t\tfos.write(is.read());\r\n\t\t\t\t}\r\n\t\t\t\tfos.close();\r\n\t\t\t\tis.close();\r\n\t\t\t}\r\n\t\t\tjar.close();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tfinal File file = new File(appLocation.getPath() + File.separator + path + toExtract);\r\n\t\tif(!file.exists()) {\r\n\t\t\tthrow new FileNotFoundException(file.getPath() + \" not found.\");\r\n\t\t}\r\n\t\t\r\n\t\tif(file.isFile()) {\r\n\t\t\tFiles.copy(file.toPath(), (destination.isFile() ? destination : new File(destination, file.getName())).toPath());\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif(destination.isFile()) {\r\n\t\t\t\tdestination = destination.getParentFile();\r\n\t\t\t}\r\n\t\t\tUtils.copyDirectory(file, destination);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * Strips HTML from a String.\r\n\t * \r\n\t * @param string The String.\r\n\t * \r\n\t * @return The String without HTML.\r\n\t */\r\n\t\r\n\tpublic static String stripHTML(final String string) {\r\n\t\treturn string.replaceAll(\"<.*?>\", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\");\r\n\t}\r\n\t\r\n\t/**\r\n\t * Joins a String list.\r\n\t * \r\n\t * @param joiner The String used to join arrays.\r\n\t * @param list The list.\r\n\t * \r\n\t * @return The joined list.\r\n\t */\r\n\r\n\tpublic static String join(final String joiner, final List<String> list) {\r\n\t\treturn join(joiner, list.toArray(new String[list.size()]));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Joins a String array.\r\n\t * \r\n\t * @param joiner The String used to join arrays.\r\n\t * @param strings The array.\r\n\t * \r\n\t * @return The joined array.\r\n\t */\r\n\r\n\tpublic static String join(final String joiner, final String... strings) {\r\n\t\tif(strings.length == 1) {\r\n\t\t\treturn strings[0];\r\n\t\t}\r\n\t\telse if(strings.length == 0) {\r\n\t\t\treturn \"\";\r\n\t\t}\r\n\t\tfinal StringBuilder builder = new StringBuilder();\r\n\t\tfor(final String string : strings) {\r\n\t\t\tbuilder.append(string + joiner);\r\n\t\t}\r\n\t\tbuilder.setLength(builder.length() - joiner.length());\r\n\t\treturn builder.toString();\r\n\t}\r\n\t\r\n\t/**\r\n\t * Just a StringBuilder simulator that adds a line break between each append(...).\r\n\t */\r\n\t\r\n\tpublic static final class AutoLineBreakStringBuilder {\r\n\t\t\r\n\t\tprivate final StringBuilder builder = new StringBuilder();\r\n\t\t\r\n\t\tpublic AutoLineBreakStringBuilder() {}\r\n\t\t\r\n\t\tpublic AutoLineBreakStringBuilder(final String string) {\r\n\t\t\tappend(string);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final void append(final String string) {\r\n\t\t\tdefaultAppend(string + LINE_SEPARATOR);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final void defaultAppend(final String string) {\r\n\t\t\tbuilder.append(string);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final void reset() {\r\n\t\t\tbuilder.setLength(0);\r\n\t\t}\r\n\t\t\r\n\t\tpublic final String toString() {\r\n\t\t\treturn builder.toString();\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Represents a Pair of two elements.\r\n\t *\r\n\t * @param <A> Element A.\r\n\t * @param <B> Element B.\r\n\t */\r\n\t\r\n\tpublic static class Pair<A,B> {\r\n\t\t\r\n\t\tpublic final A a;\r\n\t\tpublic final B b;\r\n\r\n\t\tpublic Pair(A a, B b) {\r\n\t\t\tthis.a = a;\r\n\t\t\tthis.b = b;\r\n\t\t}\r\n\t}\r\n\t\r\n}", "public static final class AutoLineBreakStringBuilder {\r\n\t\t\r\n\tprivate final StringBuilder builder = new StringBuilder();\r\n\t\t\r\n\tpublic AutoLineBreakStringBuilder() {}\r\n\t\t\r\n\tpublic AutoLineBreakStringBuilder(final String string) {\r\n\t\tappend(string);\r\n\t}\r\n\t\t\r\n\tpublic final void append(final String string) {\r\n\t\tdefaultAppend(string + LINE_SEPARATOR);\r\n\t}\r\n\t\t\r\n\tpublic final void defaultAppend(final String string) {\r\n\t\tbuilder.append(string);\r\n\t}\r\n\t\t\r\n\tpublic final void reset() {\r\n\t\tbuilder.setLength(0);\r\n\t}\r\n\t\t\r\n\tpublic final String toString() {\r\n\t\treturn builder.toString();\r\n\t}\r\n\t\t\r\n}\r" ]
import fr.skyost.skydocs.exception.InvalidMenuDataException; import fr.skyost.skydocs.exception.InvalidMenuEntryException; import fr.skyost.skydocs.utils.IncludeFileFunction; import fr.skyost.skydocs.utils.Utils; import fr.skyost.skydocs.utils.Utils.AutoLineBreakStringBuilder; import org.jtwig.JtwigModel; import org.jtwig.JtwigTemplate; import org.jtwig.environment.EnvironmentConfiguration; import org.jtwig.environment.EnvironmentConfigurationBuilder; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.util.*;
package fr.skyost.skydocs; /** * Represents a menu. */ public class DocsMenu { /** * The language of this menu. */ private String language; /** * Menu entries. */ private final List<DocsMenuEntry> entries = new ArrayList<>(); /** * Creates a new DocsMenu instance. * * @param language Language of the menu. * @param entries Entries of the menu. */ public DocsMenu(final String language, final DocsMenuEntry... entries) { this.language = language; this.entries.addAll(Arrays.asList(entries)); } /** * Gets the language of this menu. * * @return The language of this menu. */ public final String getLanguage() { return language; } /** * Sets the language of this menu. * * @param language The new language of this menu. */ public final void setLanguage(final String language) { this.language = language; } /** * Gets an entry by its link. * * @param link Entry's link. * * @return The entry. */ public final DocsMenuEntry getEntryByLink(final String link) { for(final DocsMenuEntry entry : entries) { if(entry.getLink().equals(link)) { return entry; } } return null; } /** * Gets all entries from this menu. * * @return All entries. */ public final List<DocsMenuEntry> getEntries() { return entries; } /** * Adds entries to this menu. * * @param entries Entries to add. */ public final void addEntries(final DocsMenuEntry... entries) { this.entries.addAll(Arrays.asList(entries)); } /** * Removes an entry from this menu. * * @param name Entry's name. */ public final void removeEntry(final String name) { for(final DocsMenuEntry entry : entries) { if(entry.getTitle().equals(name)) { removeEntry(entry); } } } /** * Removes an entry from this menu. * * @param entry Entry to remove. */ public final void removeEntry(final DocsMenuEntry entry) { entries.remove(entry); } /** * Clears entries from this menu. */ public final void clearEntries() { entries.clear(); } /** * Converts this menu to its HTML form. * * @return The HTML content. */ public final String toHTML() { return toHTML(null); } /** * Converts this menu to its HTML form. * * @param page The page that is calling <strong>toHTML()</strong>. * * @return The HTML content. */ protected final String toHTML(final DocsPage page) {
final AutoLineBreakStringBuilder builder = new AutoLineBreakStringBuilder("<ul>");
4
Gocnak/Botnak
src/main/java/face/Icons.java
[ "public class ChatPane implements DocumentListener {\n\n private JFrame poppedOutPane = null;\n\n // The timestamp of when we decided to wait to scroll back down\n private long scrollbarTimestamp = -1;\n\n public void setPoppedOutPane(JFrame pane) {\n poppedOutPane = pane;\n }\n\n public JFrame getPoppedOutPane() {\n return poppedOutPane;\n }\n\n public void createPopOut() {\n if (poppedOutPane == null) {\n JFrame frame = new JFrame(getPoppedOutTitle());\n frame.addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosed(WindowEvent e) {\n getScrollPane().setViewportView(scrollablePanel);\n scrollToBottom();\n setPoppedOutPane(null);\n }\n });\n JScrollPane pane = new JScrollPane();\n frame.setIconImage(new ImageIcon(getClass().getResource(\"/image/icon.png\")).getImage());\n pane.setViewportView(scrollablePanel);\n pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n pane.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));\n frame.add(pane);\n frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n frame.pack();\n frame.setSize(750, 420);\n frame.setVisible(true);\n setPoppedOutPane(frame);\n }\n }\n\n /**\n * Keeps track of how many subs this channel gets.\n * TODO: make this a statistic that the user can output to a file (\"yesterday sub #\")\n */\n private int subCount = 0;\n\n private int viewerCount = -1;\n private int viewerPeak = 0;\n\n public void setViewerCount(int newCount) {\n if (newCount > viewerPeak) viewerPeak = newCount;\n viewerCount = newCount;\n if (getPoppedOutPane() != null) poppedOutPane.setTitle(getPoppedOutTitle());\n if (GUIMain.channelPane.getSelectedIndex() == index) GUIMain.updateTitle(getViewerCountString());\n }\n\n public String getPoppedOutTitle() {\n return chan + \" | \" + getViewerCountString();\n }\n\n public String getViewerCountString() {\n if (chan.equalsIgnoreCase(\"system logs\")) return null;\n if (viewerCount == -1) return \"Viewer count: Offline\";\n return String.format(\"Viewer count: %s (%s)\",\n NumberFormat.getInstance().format(viewerCount),\n NumberFormat.getInstance().format(viewerPeak));\n }\n\n /**\n * This is the main boolean to check to see if this tab should pulse.\n * <p>\n * This boolean checks to see if the tab wasn't toggled, if it's visible (not in a combined tab),\n * and if it's not selected.\n * <p>\n * The global setting will override this.\n *\n * @return True if this tab should pulse, else false.\n */\n public boolean shouldPulse() {\n boolean shouldPulseLocal = (this instanceof CombinedChatPane) ?\n ((CombinedChatPane) this).getActiveChatPane().shouldPulseLoc() : shouldPulseLoc;\n return Settings.showTabPulses.getValue() && shouldPulseLocal && isTabVisible() &&\n GUIMain.channelPane.getSelectedIndex() != index && index != 0;\n }\n\n private boolean shouldPulseLoc = true;\n\n /**\n * Determines if this tab should pulse.\n *\n * @return True if this tab is not toggled off, else false. (\"Tab Pulsing OFF\")\n */\n public boolean shouldPulseLoc() {\n return shouldPulseLoc;\n }\n\n /**\n * Sets the value for if this tab should pulse or not.\n *\n * @param newBool True (default) if tab pulsing should happen, else false if you wish to\n * toggle tab pulsing off.\n */\n public void setShouldPulse(boolean newBool) {\n shouldPulseLoc = newBool;\n }\n\n\n /**\n * Sets the pulsing boolean if this tab is starting to pulse.\n * <p>\n * Used by the TabPulse class.\n *\n * @param isPulsing True if the tab is starting to pulse, else false to stop pulsing.\n */\n public void setPulsing(boolean isPulsing) {\n this.isPulsing = isPulsing;\n }\n\n /**\n * Used by the TabPulse class.\n *\n * @return true if the chat pane is currently pulsing, else false.\n */\n public boolean isPulsing() {\n return isPulsing;\n }\n\n private boolean isPulsing = false;\n\n //credit to http://stackoverflow.com/a/4047794 for the below\n public boolean isScrollBarFullyExtended(JScrollBar vScrollBar) {\n BoundedRangeModel model = vScrollBar.getModel();\n return (model.getExtent() + model.getValue()) == model.getMaximum();\n }\n\n public void doScrollToBottom() {\n if (textPane.isVisible()) {\n Rectangle visibleRect = textPane.getVisibleRect();\n visibleRect.y = textPane.getHeight() - visibleRect.height;\n textPane.scrollRectToVisible(visibleRect);\n } else {\n textPane.setCaretPosition(textPane.getDocument().getLength());\n }\n }\n\n private boolean messageOut = false;\n\n @Override\n public void insertUpdate(DocumentEvent e) {\n maybeScrollToBottom();\n if (Settings.cleanupChat.getValue()) {\n try {\n if (e.getDocument().getText(e.getOffset(), e.getLength()).contains(\"\\n\")) {\n cleanupCounter++;\n }\n } catch (Exception ignored) {\n }\n if (cleanupCounter > Settings.chatMax.getValue()) {\n /* cleanup every n messages */\n if (!messageOut) {\n MessageQueue.addMessage(new Message().setType(Message.MessageType.CLEAR_TEXT).setExtra(this));\n messageOut = true;\n }\n }\n }\n }\n\n @Override\n public void removeUpdate(DocumentEvent e) {\n maybeScrollToBottom();\n }\n\n @Override\n public void changedUpdate(DocumentEvent e) {\n maybeScrollToBottom();\n }\n\n /**\n * Used to queue a scrollToBottom only if the scroll bar is already at the bottom\n * OR\n * It's been more than 10 seconds since we've been scrolled up and have been receiving messages\n */\n private void maybeScrollToBottom() {\n JScrollBar scrollBar = scrollPane.getVerticalScrollBar();\n boolean scrollBarAtBottom = isScrollBarFullyExtended(scrollBar);\n if (scrollBarAtBottom) {\n // We're back at the bottom, reset timer\n scrollbarTimestamp = -1;\n scrollToBottom();\n } else if (scrollbarTimestamp != -1) {\n if (System.currentTimeMillis() - scrollbarTimestamp >= 10 * 1000L) {\n // If the time difference is more than 10 seconds, scroll to bottom anyway after resetting time\n scrollbarTimestamp = -1;\n scrollToBottom();\n }\n } else {\n scrollbarTimestamp = System.currentTimeMillis();\n }\n }\n\n public void scrollToBottom() {\n // Push the call to \"scrollToBottom\" back TWO PLACES on the\n // AWT-EDT queue so that it runs *after* Swing has had an\n // opportunity to \"react\" to the appending of new text:\n // this ensures that we \"scrollToBottom\" only after a new\n // bottom has been recalculated during the natural\n // revalidation of the GUI that occurs after having\n // appending new text to the JTextArea.\n EventQueue.invokeLater(() -> EventQueue.invokeLater(this::doScrollToBottom));\n }\n\n private String chan;\n\n public String getChannel() {\n return chan;\n }\n\n private int index;\n\n public void setIndex(int newIndex) {\n index = newIndex;\n }\n\n public int getIndex() {\n return index;\n }\n\n private ScrollablePanel scrollablePanel;\n\n private JTextPane textPane;\n\n public JTextPane getTextPane() {\n return textPane;\n }\n\n private JScrollPane scrollPane;\n\n public JScrollPane getScrollPane() {\n return scrollPane;\n }\n\n public void setScrollPane(JScrollPane pane) {\n scrollPane = pane;\n }\n\n private boolean isTabVisible = true;\n\n public boolean isTabVisible() {\n return isTabVisible;\n }\n\n public void setTabVisible(boolean newBool) {\n isTabVisible = newBool;\n }\n\n private int cleanupCounter = 0;\n\n public void resetCleanupCounter() {\n cleanupCounter = 0;\n }\n\n //TODO make this be in 24 hour if they want\n final SimpleDateFormat format = new SimpleDateFormat(\"[h:mm a]\", Locale.getDefault());\n\n public String getTime() {\n return format.format(new Date(System.currentTimeMillis()));\n }\n\n /**\n * You initialize this class with the channel it's for and the text pane you'll be editing.\n *\n * @param channel The channel (\"name\") of this chat pane. Ex: \"System Logs\" or \"#gocnak\"\n * @param scrollPane The scroll pane for the tab.\n * @param pane The text pane that shows the messages for the given channel.\n * @param index The index of the pane in the main GUI.\n */\n public ChatPane(String channel, JScrollPane scrollPane, JTextPane pane, ScrollablePanel panel, int index) {\n chan = channel;\n textPane = pane;\n ((DefaultCaret) textPane.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);\n this.index = index;\n this.scrollPane = scrollPane;\n this.scrollablePanel = panel;\n textPane.getDocument().addDocumentListener(this);\n }\n\n public ChatPane() {\n //Used by the CombinedChatPane class, which calls its super anyways.\n }\n\n /**\n * This is the main message method when somebody sends a message to the channel.\n *\n * @param m The message from the chat.\n */\n public void onMessage(MessageWrapper m, boolean showChannel) {\n if (textPane == null) return;\n Message message = m.getLocal();\n long senderID = message.getSenderID();\n String channel = message.getChannel();\n String mess = message.getContent();\n boolean isMe = (message.getType() == Message.MessageType.ACTION_MESSAGE);\n try {\n print(m, \"\\n\" + getTime(), GUIMain.norm);\n User senderUser = Settings.channelManager.getUser(senderID, true);\n String sender = senderUser.getLowerNick();\n SimpleAttributeSet user = getUserSet(senderUser);\n if (channel.substring(1).equals(sender)) {\n insertIcon(m, IconEnum.BROADCASTER, null);\n }\n if (senderUser.isOp(channel))\n {\n if (!channel.substring(1).equals(sender) && !senderUser.isStaff() && !senderUser.isAdmin() && !senderUser.isGlobalMod())\n {//not the broadcaster again\n insertIcon(m, IconEnum.MOD, null);\n }\n }\n if (senderUser.isGlobalMod())\n {\n insertIcon(m, IconEnum.GLOBAL_MOD, null);\n }\n if (senderUser.isStaff())\n {\n insertIcon(m, IconEnum.STAFF, null);\n }\n if (senderUser.isAdmin())\n {\n insertIcon(m, IconEnum.ADMIN, null);\n }\n boolean isSubscriber = senderUser.isSubscriber(channel);\n if (isSubscriber) {\n insertIcon(m, IconEnum.SUBSCRIBER, channel);\n } else {\n if (Utils.isMainChannel(channel)) {\n Optional<Subscriber> sub = Settings.subscriberManager.getSubscriber(senderID);\n if (sub.isPresent() && !sub.get().isActive()) {\n insertIcon(m, IconEnum.EX_SUBSCRIBER, channel);\n }\n }\n }\n if (senderUser.isTurbo())\n {\n insertIcon(m, IconEnum.TURBO, null);\n }\n\n if (senderUser.isPrime())\n insertIcon(m, IconEnum.PRIME, null);\n\n if (senderUser.isVerified())\n insertIcon(m, IconEnum.VERIFIED, null);\n\n //Cheering\n int cheerTotal = senderUser.getCheer(channel);\n if (cheerTotal > 0)\n {\n insertIcon(m, Donor.getCheerStatus(cheerTotal), null);\n }\n\n // Third party donor\n if (Settings.showDonorIcons.getValue())\n {\n if (senderUser.isDonor())\n {\n insertIcon(m, senderUser.getDonationStatus(), null);\n }\n }\n\n //name stuff\n print(m, \" \", GUIMain.norm);\n SimpleAttributeSet userColor = new SimpleAttributeSet(user);\n FaceManager.handleNameFaces(senderID, user);\n print(m, senderUser.getDisplayName(), user);\n if (showChannel) {\n print(m, \" (\" + channel.substring(1) + \")\" + (isMe ? \" \" : \": \"), GUIMain.norm);\n } else {\n print(m, (!isMe ? \": \" : \" \"), userColor);\n }\n //keyword?\n SimpleAttributeSet set;\n if (Utils.mentionsKeyword(mess)) {\n set = Utils.getSetForKeyword(mess);\n } else {\n set = (isMe ? userColor : GUIMain.norm);\n }\n //URL, Faces, rest of message\n printMessage(m, mess, set, senderUser);\n\n if (BotnakTrayIcon.shouldDisplayMentions() && !Utils.isTabSelected(index)) {\n if (mess.toLowerCase().contains(Settings.accountManager.getUserAccount().getName().toLowerCase())) {\n GUIMain.getSystemTrayIcon().displayMention(m.getLocal());\n }\n }\n\n if (Utils.isMainChannel(channel))\n //check status of the sub, has it been a month?\n Settings.subscriberManager.updateSubscriber(senderUser, channel, isSubscriber);\n if (shouldPulse())\n GUIMain.instance.pulseTab(this);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n /**\n * Credit: TDuva\n * <p>\n * Cycles through message data, tagging things like Faces and URLs.\n *\n * @param text The message\n * @param style The default message style to use.\n */\n protected void printMessage(MessageWrapper m, String text, SimpleAttributeSet style, User u) {\n // Where stuff was found\n TreeMap<Integer, Integer> ranges = new TreeMap<>();\n // The style of the stuff (basically metadata)\n HashMap<Integer, SimpleAttributeSet> rangesStyle = new HashMap<>();\n\n findLinks(text, ranges, rangesStyle);\n findEmoticons(text, ranges, rangesStyle, u, m.getLocal().getChannel());\n\n // Actually print everything\n int lastPrintedPos = 0;\n for (Map.Entry<Integer, Integer> range : ranges.entrySet()) {\n int start = range.getKey();\n int end = range.getValue();\n if (start > lastPrintedPos) {\n // If there is anything between the special stuff, print that\n // first as regular text\n print(m, text.substring(lastPrintedPos, start), style);\n }\n print(m, text.substring(start, end + 1), rangesStyle.get(start));\n lastPrintedPos = end + 1;\n }\n // If anything is left, print that as well as regular text\n if (lastPrintedPos < text.length()) {\n print(m, text.substring(lastPrintedPos), style);\n }\n }\n\n private void findLinks(String text, Map<Integer, Integer> ranges, Map<Integer, SimpleAttributeSet> rangesStyle) {\n // Find links\n Constants.urlMatcher.reset(text);\n while (Constants.urlMatcher.find()) {\n int start = Constants.urlMatcher.start();\n int end = Constants.urlMatcher.end() - 1;\n if (!Utils.inRanges(start, ranges) && !Utils.inRanges(end, ranges)) {\n String foundUrl = Constants.urlMatcher.group();\n if (Utils.checkURL(foundUrl)) {\n ranges.put(start, end);\n rangesStyle.put(start, Utils.URLStyle(foundUrl));\n }\n }\n }\n }\n\n private void findEmoticons(String text, Map<Integer, Integer> ranges, Map<Integer, SimpleAttributeSet> rangesStyle, User u, String channel) {\n FaceManager.handleFaces(ranges, rangesStyle, text, FaceManager.FACE_TYPE.NORMAL_FACE, null, null);\n if (u != null && u.getEmotes() != null) {\n FaceManager.handleFaces(ranges, rangesStyle, text, FaceManager.FACE_TYPE.TWITCH_FACE, null, u.getEmotes());\n }\n if (Settings.ffzFacesEnable.getValue() && channel != null) {\n channel = channel.replaceAll(\"#\", \"\");\n FaceManager.handleFaces(ranges, rangesStyle, text, FaceManager.FACE_TYPE.FRANKER_FACE, channel, null);\n }\n }\n\n protected void print(MessageWrapper wrapper, String string, SimpleAttributeSet set) {\n if (textPane == null) return;\n Runnable r = () -> {\n try {\n textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), string, set);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n };\n wrapper.addPrint(r);\n }\n\n /**\n * Handles inserting icons before and after the message.\n *\n * @param m The message itself.\n * @param status IconEnum.Subscriber for sub message, else pass Donor#getDonationStatus(d#getAmount())\n */\n public void onIconMessage(MessageWrapper m, IconEnum status) {\n try {\n Message message = m.getLocal();\n print(m, \"\\n\", GUIMain.norm);\n for (int i = 0; i < 3; i++) {\n insertIcon(m, status, (status == IconEnum.SUBSCRIBER ? message.getChannel() : null));\n }\n print(m, \" \" + message.getContent() + (status == IconEnum.SUBSCRIBER ? (\" (\" + (subCount + 1) + \") \") : \" \"), GUIMain.norm);\n for (int i = 0; i < 3; i++) {\n insertIcon(m, status, (status == IconEnum.SUBSCRIBER ? message.getChannel() : null));\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n boolean shouldIncrement = ((status == IconEnum.SUBSCRIBER) && (m.getLocal().getExtra() == null));//checking for repeat messages\n if (shouldIncrement) subCount++;\n }\n\n public void onSub(MessageWrapper m) {\n onIconMessage(m, IconEnum.SUBSCRIBER);\n }\n\n public void onWhisper(MessageWrapper m) {\n SimpleAttributeSet senderSet, receiverSet;\n\n long sender = m.getLocal().getSenderID();\n String receiver = (String) m.getLocal().getExtra();\n print(m, \"\\n\" + getTime(), GUIMain.norm);\n User senderUser = Settings.channelManager.getUser(sender, true);\n User receiverUser = Settings.channelManager.getUser(receiver, true);\n senderSet = getUserSet(senderUser);\n receiverSet = getUserSet(receiverUser);\n\n //name stuff\n print(m, \" \", GUIMain.norm);\n FaceManager.handleNameFaces(senderUser.getUserID(), senderSet);\n FaceManager.handleNameFaces(receiverUser.getUserID(), receiverSet);\n print(m, senderUser.getDisplayName(), senderSet);\n print(m, \" (whisper)-> \", GUIMain.norm);\n print(m, receiverUser.getDisplayName(), receiverSet);\n print(m, \": \", GUIMain.norm);\n\n printMessage(m, m.getLocal().getContent(), GUIMain.norm, senderUser);\n }\n\n private SimpleAttributeSet getUserSet(User u) {\n SimpleAttributeSet user = new SimpleAttributeSet();\n StyleConstants.setFontFamily(user, Settings.font.getValue().getFamily());\n StyleConstants.setFontSize(user, Settings.font.getValue().getSize());\n StyleConstants.setForeground(user, Utils.getColorFromUser(u));\n user.addAttribute(HTML.Attribute.NAME, u.getDisplayName());\n return user;\n }\n\n public void onDonation(MessageWrapper m) {\n Donation d = (Donation) m.getLocal().getExtra();\n onIconMessage(m, Donor.getDonationStatus(d.getAmount()));\n }\n\n public void onCheer(MessageWrapper m)\n {\n int bitsAmount = (int) m.getLocal().getExtra();\n String bitString = \"\" + bitsAmount + \" bit\" + (bitsAmount > 1 ? \"s\" : \"\") + \"!\";\n String cheerMessage = m.getLocal().getSenderName() + \" just cheered \" + bitString;\n String originalMessage = m.getLocal().getContent().replaceAll(\"(^|\\\\s?)cheer\\\\d+(\\\\s?|$)\", \" \").trim().replaceAll(\"\\\\s+\", \" \");\n\n //We're first going to send a \"hey they cheered\" message, then immediately follow it with their message\n // This requires overriding the content to be the cheer message first (for the icons), then replacing it back\n m.getLocal().setContent(cheerMessage);\n onIconMessage(m, Donor.getCheerAmountStatus(bitsAmount));\n\n //Let's get this message out there too, if they have one.\n if (originalMessage.length() > 0)\n {\n m.getLocal().setContent(originalMessage);\n onMessage(m, false);\n }\n }\n\n public void insertIcon(MessageWrapper m, IconEnum type, String channel) {\n SimpleAttributeSet attrs = new SimpleAttributeSet();\n Icons.BotnakIcon icon = Icons.getIcon(type, channel);\n StyleConstants.setIcon(attrs, icon.getImage());\n try {\n print(m, \" \", null);\n print(m, icon.getType().type, attrs);\n } catch (Exception e) {\n GUIMain.log(\"Exception in insertIcon: \");\n GUIMain.log(e);\n }\n }\n\n public String getText() {\n return (textPane != null && textPane.getText() != null) ? textPane.getText() : \"\";\n }\n\n // Source: http://stackoverflow.com/a/4628879\n // by http://stackoverflow.com/users/131872/camickr & Community\n public void cleanupChat() {\n if (scrollablePanel == null || scrollablePanel.getParent() == null) return;\n if (!(scrollablePanel.getParent() instanceof JViewport)) return;\n JViewport viewport = ((JViewport) scrollablePanel.getParent());\n Point startPoint = viewport.getViewPosition();\n // we are not deleting right before the visible area, but one screen behind\n // for convenience, otherwise flickering.\n if (startPoint == null) return;\n\n final int start = textPane.viewToModel(startPoint);\n if (start > 0) // not equal zero, because then we don't have to delete anything\n {\n final StyledDocument doc = textPane.getStyledDocument();\n try {\n if (Settings.logChat.getValue() && chan != null) {\n String[] toRemove = doc.getText(0, start).split(\"\\\\n\");\n Utils.logChat(toRemove, chan, 1);\n }\n doc.remove(0, start);\n resetCleanupCounter();\n } catch (Exception e) {\n GUIMain.log(\"Failed clearing chat: \");\n GUIMain.log(e);\n }\n }\n messageOut = false;\n }\n\n /**\n * Creates a pane of the given channel.\n *\n * @param channel The channel, also used as the key for the hashmap.\n * @return The created ChatPane.\n */\n public static ChatPane createPane(String channel) {\n JScrollPane scrollPane = new JScrollPane();\n scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n JTextPane pane = new JTextPane();\n pane.setContentType(\"text/html; charset=UTF-8\");\n pane.setEditorKit(Constants.wrapEditorKit);\n pane.setEditable(false);\n pane.setFocusable(false);\n pane.setMargin(new Insets(0, 0, 0, 0));\n pane.setBackground(Color.black);\n pane.setFont(Settings.font.getValue());\n pane.addMouseListener(Constants.listenerURL);\n pane.addMouseListener(Constants.listenerName);\n pane.addMouseListener(Constants.listenerFace);\n ScrollablePanel sp = new ScrollablePanel();\n sp.add(pane, BorderLayout.SOUTH);\n scrollPane.setViewportView(sp);\n return new ChatPane(channel, scrollPane, pane, sp, GUIMain.channelPane.getTabCount() - 1);\n }\n\n /**\n * Deletes the pane and removes the tab from the tabbed pane.\n */\n public void deletePane() {\n if (Settings.logChat.getValue()) {\n Utils.logChat(getText().split(\"\\\\n\"), chan, 2);\n }\n GUIViewerList list = GUIMain.viewerLists.get(chan);\n if (list != null) {\n list.dispose();\n }\n if (getPoppedOutPane() != null) {\n getPoppedOutPane().dispose();\n }\n GUIMain.channelPane.removeTabAt(index);\n GUIMain.channelPane.setSelectedIndex(index - 1);\n }\n\n /**\n * Logs a message to this chat pane.\n *\n * @param message The message itself.\n * @param isSystem Whether the message is a system log message or not.\n */\n public void log(MessageWrapper message, boolean isSystem) {\n print(message, \"\\n\" + getTime(), GUIMain.norm);\n print(message, \" \" + (isSystem ? \"SYS: \" : \"\") + message.getLocal().getContent(), GUIMain.norm);\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof ChatPane && ((ChatPane) obj).index == this.index &&\n ((ChatPane) obj).getChannel().equals(this.getChannel());\n }\n}", "public class GUIMain extends JFrame {\n\n public static Map<Long, Color> userColMap;\n public static Map<String, Color> keywordMap;\n public static Set<Command> commandSet;\n public static Set<ConsoleCommand> conCommands;\n public static Set<String> channelSet;\n public static Map<String, ChatPane> chatPanes;\n public static Set<CombinedChatPane> combinedChatPanes;\n public static Set<TabPulse> tabPulses;\n public static Map<String, GUIViewerList> viewerLists;\n\n public static int userResponsesIndex = 0;\n public static ArrayList<String> userResponses;\n\n public static IRCBot bot;\n public static IRCViewer viewer;\n public static GUISettings settings = null;\n public static GUIStreams streams = null;\n public static GUIAbout aboutGUI = null;\n public static GUIStatus statusGUI = null;\n public static GUIRaffle raffleGUI = null;\n public static GUIVote voteGUI = null;\n\n public static boolean shutDown = false;\n\n public static SimpleAttributeSet norm = new SimpleAttributeSet();\n\n public static GUIMain instance;\n\n private static BotnakTrayIcon systemTrayIcon;\n\n public static Heartbeat heartbeat;\n\n private static ChatPane systemLogsPane;\n\n public GUIMain() {\n new MessageQueue();\n instance = this;\n channelSet = new CopyOnWriteArraySet<>();\n userColMap = new ConcurrentHashMap<>();\n commandSet = new CopyOnWriteArraySet<>();\n conCommands = new CopyOnWriteArraySet<>();\n keywordMap = new ConcurrentHashMap<>();\n tabPulses = new CopyOnWriteArraySet<>();\n combinedChatPanes = new CopyOnWriteArraySet<>();\n viewerLists = new ConcurrentHashMap<>();\n userResponses = new ArrayList<>();\n chatPanes = new ConcurrentHashMap<>();\n ThreadEngine.init();\n FaceManager.init();\n SoundEngine.init();\n StyleConstants.setForeground(norm, Color.white);\n StyleConstants.setFontFamily(norm, Settings.font.getValue().getFamily());\n StyleConstants.setFontSize(norm, Settings.font.getValue().getSize());\n StyleConstants.setBold(norm, Settings.font.getValue().isBold());\n StyleConstants.setItalic(norm, Settings.font.getValue().isItalic());\n initComponents();\n systemLogsPane = new ChatPane(\"System Logs\", allChatsScroll, allChats, null, 0);\n chatPanes.put(\"System Logs\", systemLogsPane);\n Settings.init();\n ThreadEngine.submit(() -> {\n Settings.load();\n if (Settings.stUseSystemTray.getValue()) getSystemTrayIcon();\n heartbeat = new Heartbeat();\n });\n }\n\n public static boolean loadedSettingsUser() {\n return Settings.accountManager != null && Settings.accountManager.getUserAccount() != null;\n }\n\n public static boolean loadedSettingsBot() {\n return Settings.accountManager != null && Settings.accountManager.getBotAccount() != null;\n }\n\n public static boolean loadedCommands() {\n return !commandSet.isEmpty();\n }\n\n public void chatButtonActionPerformed() {\n userResponsesIndex = 0;\n String channel = channelPane.getTitleAt(channelPane.getSelectedIndex());\n if (Settings.accountManager.getViewer() == null) {\n logCurrent(\"Failed to send message, there is no viewer account! Please set one up!\");\n return;\n }\n if (!Settings.accountManager.getViewer().isConnected()) {\n logCurrent(\"Failed to send message, currently trying to (re)connect!\");\n return;\n }\n String userInput = Utils.checkText(userChat.getText().replaceAll(\"\\n\", \"\"));\n if (channel != null && !channel.equalsIgnoreCase(\"system logs\") && !\"\".equals(userInput)) {\n CombinedChatPane ccp = Utils.getCombinedChatPane(channelPane.getSelectedIndex());\n boolean comboExists = ccp != null;\n if (comboExists) {\n List<String> channels = ccp.getActiveChannel().equalsIgnoreCase(\"All\") ?\n ccp.getChannels() : Collections.singletonList(ccp.getActiveChannel());\n\n for (String c : channels)\n Settings.accountManager.getViewer().sendMessage(\"#\" + c, userInput);\n\n if (!userResponses.contains(userInput))\n userResponses.add(userInput);\n }\n else\n {\n Settings.accountManager.getViewer().sendMessage(\"#\" + channel, userInput);\n if (!userResponses.contains(userInput))\n userResponses.add(userInput);\n }\n userChat.setText(\"\");\n }\n }\n\n /**\n * Wrapper for ensuring no null chat pane is produced due to hash tags.\n *\n * @param channel The channel, either inclusive of the hash tag or not.\n * @return The chat pane if existent, otherwise to System Logs to prevent null pointers.\n * (Botnak will just print out to System Logs the message that was eaten)\n */\n public static ChatPane getChatPane(String channel) {\n ChatPane toReturn = chatPanes.get(channel.replaceAll(\"#\", \"\"));\n return toReturn == null ? getSystemLogsPane() : toReturn;\n }\n\n /**\n * @return The System Logs chat pane.\n */\n public static ChatPane getSystemLogsPane() {\n return systemLogsPane;\n }\n\n /**\n * Logs a message to the current chat pane.\n *\n * @param message The message to log.\n */\n public static void logCurrent(Object message) {\n ChatPane current = getCurrentPane();\n if (message != null && chatPanes != null && !chatPanes.isEmpty() && current != null)\n MessageQueue.addMessage(new Message().setType(Message.MessageType.LOG_MESSAGE)\n .setContent(message.toString()).setExtra(current));\n }\n\n public static ChatPane getCurrentPane() {\n ChatPane toReturn;\n int index = channelPane.getSelectedIndex();\n if (index == 0) return getSystemLogsPane();\n toReturn = Utils.getChatPane(index);\n if (toReturn == null) {\n toReturn = Utils.getCombinedChatPane(index);\n }\n return toReturn == null ? getSystemLogsPane() : toReturn;\n }\n\n /**\n * Logs a message to the chat console under all white, SYS username.\n * This should only be used for serious reports, like exception reporting and\n * other status updates.\n *\n * @param message The message to log.\n */\n public static void log(Object message) {\n if (message == null) return;\n String toPrint;\n Message.MessageType type = Message.MessageType.LOG_MESSAGE; // Moved here to allow for changing message type to something like error for throwables\n if (message instanceof Throwable) {\n Throwable t = (Throwable) message;\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n t.printStackTrace(pw);\n toPrint = sw.toString(); // stack trace as a string\n pw.close();\n } else {\n // Not a throwable.. Darn strings\n toPrint = message.toString();\n }\n if (chatPanes == null || chatPanes.isEmpty()) {//allowing for errors to at least go somewhere\n System.out.println(toPrint == null ? \"Null toPrint!\" : toPrint);\n } else {\n MessageQueue.addMessage(new Message(toPrint, type));\n }\n }\n\n public static void updateTitle(String viewerCount) {\n StringBuilder stanSB = new StringBuilder();\n stanSB.append(\"Botnak \");\n if (viewerCount != null) {\n stanSB.append(\"| \");\n stanSB.append(viewerCount);\n stanSB.append(\" \");\n }\n if (Settings.accountManager != null) {\n if (Settings.accountManager.getUserAccount() != null) {\n stanSB.append(\"| User: \");\n stanSB.append(Settings.accountManager.getUserAccount().getName());\n }\n if (Settings.accountManager.getBotAccount() != null) {\n stanSB.append(\" | Bot: \");\n stanSB.append(Settings.accountManager.getBotAccount().getName());\n }\n }\n instance.setTitle(stanSB.toString());\n }\n\n public void exitButtonActionPerformed() {\n shutDown = true;\n if (viewer != null) {\n viewer.close(false);\n }\n if (bot != null) {\n bot.close(false);\n }\n if (!tabPulses.isEmpty()) {\n tabPulses.forEach(TabPulse::interrupt);\n tabPulses.clear();\n }\n if (systemTrayIcon != null) systemTrayIcon.close();\n SoundEngine.getEngine().close();\n Settings.save();\n heartbeat.interrupt();\n ThreadEngine.close();\n Set<Map.Entry<String, ChatPane>> entries = chatPanes.entrySet();\n for (Map.Entry<String, ChatPane> entry : entries)\n {\n String channel = entry.getKey();\n ChatPane pane = entry.getValue();\n if (Settings.logChat.getValue())\n {\n Utils.logChat(pane.getText().split(\"\\\\n\"), channel, 2);\n }\n }\n System.gc();\n dispose();\n System.exit(0);\n }\n\n\n public synchronized void pulseTab(ChatPane cp) {\n if (shutDown) return;\n if (cp.isPulsing()) return;\n TabPulse tp = new TabPulse(cp);\n tp.start();\n tabPulses.add(tp);\n }\n\n public static BotnakTrayIcon getSystemTrayIcon() {\n if (systemTrayIcon == null) systemTrayIcon = new BotnakTrayIcon();\n return systemTrayIcon;\n }\n\n\n private void openBotnakFolderOptionActionPerformed() {\n Utils.openWebPage(Settings.defaultDir.toURI().toString());\n }\n\n private void openLogViewerOptionActionPerformed() {\n // TODO add your code here\n }\n\n private void openSoundsOptionActionPerformed() {\n Utils.openWebPage(new File(Settings.defaultSoundDir.getValue()).toURI().toString());\n }\n\n private void autoReconnectToggleItemStateChanged(ItemEvent e) {\n Settings.autoReconnectAccounts.setValue(e.getStateChange() == ItemEvent.SELECTED);\n if (e.getStateChange() == ItemEvent.SELECTED) {\n if (viewer != null && viewer.getViewer() != null) {\n if (!viewer.getViewer().getConnection().isConnected())\n Settings.accountManager.createReconnectThread(viewer.getViewer().getConnection());\n }\n if (bot != null && bot.getBot() != null) {\n if (!bot.getBot().isConnected())\n Settings.accountManager.createReconnectThread(bot.getBot().getConnection());\n }\n }\n }\n\n private void alwaysOnTopToggleItemStateChanged(ItemEvent e) {\n Settings.alwaysOnTop.setValue(e.getStateChange() == ItemEvent.SELECTED);\n }\n\n public void updateAlwaysOnTopStatus(boolean newBool) {\n if (alwaysOnTopToggle.isSelected() != newBool) {\n alwaysOnTopToggle.setSelected(newBool);\n //this is going to be called from the setting load,\n //which will probably, in turn, fire another\n //change event, setting the setting to the same setting it is,\n //but since no change happens, this void is not called again,\n //and we can continue on in the original call\n }\n Window[] windows = getWindows();\n for (Window w : windows) {\n w.setAlwaysOnTop(newBool);\n }\n }\n\n private void settingsOptionActionPerformed() {\n if (settings == null) {\n settings = new GUISettings();\n }\n if (!settings.isVisible()) {\n settings.setVisible(true);\n }\n }\n\n private void startRaffleOptionActionPerformed() {\n if (raffleGUI == null)\n raffleGUI = new GUIRaffle();\n if (!raffleGUI.isVisible())\n raffleGUI.setVisible(true);\n else\n raffleGUI.toFront();\n }\n\n private void startVoteOptionActionPerformed() {\n if (voteGUI == null)\n voteGUI = new GUIVote();\n if (!voteGUI.isVisible())\n voteGUI.setVisible(true);\n else\n voteGUI.toFront();\n }\n\n private void soundsToggleItemStateChanged() {\n Response r = SoundEngine.getEngine().toggleSound(null, false);\n if (r.isSuccessful()) {\n if (bot != null && bot.getBot() != null) {\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n }\n }\n\n private void manageTextCommandsOptionActionPerformed() {\n // TODO add your code here\n }\n\n private void updateStatusOptionActionPerformed() {\n if (statusGUI == null) {\n statusGUI = new GUIStatus();\n }\n if (!statusGUI.isVisible()) {\n statusGUI.setVisible(true);\n }\n }\n\n private void subOnlyToggleItemStateChanged() {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n subOnlyToggle.isSelected() ? \"/subscribers\" : \"/subscribersoff\");\n }\n }\n\n private void projectGithubOptionActionPerformed() {\n Utils.openWebPage(\"https://github.com/Gocnak/Botnak/\");\n }\n\n private void projectWikiOptionActionPerformed() {\n Utils.openWebPage(\"https://github.com/Gocnak/Botnak/wiki\");\n }\n\n private void projectDetailsOptionActionPerformed() {\n if (aboutGUI == null) {\n aboutGUI = new GUIAbout();\n }\n if (!aboutGUI.isVisible())\n aboutGUI.setVisible(true);\n }\n\n public void updateSoundDelay(int secDelay) {\n if (secDelay > 1000)\n secDelay /= 1000;\n switch (secDelay) {\n case 0:\n soundDelayOffOption.setSelected(true);\n break;\n case 5:\n soundDelay5secOption.setSelected(true);\n break;\n case 10:\n soundDelay10secOption.setSelected(true);\n break;\n case 20:\n soundDelay20secOption.setSelected(true);\n break;\n default:\n soundDelayCustomOption.setSelected(true);\n soundDelayCustomOption.setText(String.format(\"Custom: %d seconds\", secDelay));\n break;\n }\n if (!soundDelayCustomOption.isSelected()) soundDelayCustomOption.setText(\"Custom (use chat)\");\n }\n\n public void updateSoundPermission(int permission) {\n switch (permission) {\n case 0:\n soundPermEveryoneOption.setSelected(true);\n break;\n case 1:\n soundPermSDMBOption.setSelected(true);\n break;\n case 2:\n soundPermDMBOption.setSelected(true);\n break;\n case 3:\n soundPermModAndBroadOption.setSelected(true);\n break;\n case 4:\n soundPermBroadOption.setSelected(true);\n break;\n default:\n break;\n }\n }\n\n public void updateSoundToggle(boolean newBool) {\n soundsToggle.setSelected(newBool);\n }\n\n public void updateSubsOnly(String num) {\n subOnlyToggle.setSelected(\"1\".equals(num));\n }\n\n public void updateSlowMode(String slowModeAmount) {\n switch (slowModeAmount) {\n case \"0\":\n slowModeOffOption.setSelected(true);\n break;\n case \"5\":\n slowMode5secOption.setSelected(true);\n break;\n case \"10\":\n slowMode10secOption.setSelected(true);\n break;\n case \"15\":\n slowMode15secOption.setSelected(true);\n break;\n case \"30\":\n slowMode30secOption.setSelected(true);\n break;\n default:\n slowModeCustomOption.setSelected(true);\n slowModeCustomOption.setText(\"Custom: \" + slowModeAmount + \" seconds\");\n break;\n }\n if (!slowModeCustomOption.isSelected()) slowModeCustomOption.setText(\"Custom (use chat)\");\n }\n\n public void updateBotReplyPerm(int perm) {\n switch (perm) {\n case 2:\n botReplyAll.setSelected(true);\n break;\n case 1:\n botReplyJustYou.setSelected(true);\n break;\n case 0:\n botReplyNobody.setSelected(true);\n break;\n default:\n break;\n }\n }\n\n private void initComponents() {\n // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents\n // Generated using JFormDesigner Evaluation license - Nick K\n menuBar1 = new JMenuBar();\n fileMenu = new JMenu();\n openBotnakFolderOption = new JMenuItem();\n openLogViewerOption = new JMenuItem();\n openSoundsOption = new JMenuItem();\n exitOption = new JMenuItem();\n preferencesMenu = new JMenu();\n botReplyMenu = new JMenu();\n botReplyAll = new JRadioButtonMenuItem();\n botReplyJustYou = new JRadioButtonMenuItem();\n botReplyNobody = new JRadioButtonMenuItem();\n autoReconnectToggle = new JCheckBoxMenuItem();\n alwaysOnTopToggle = new JCheckBoxMenuItem();\n settingsOption = new JMenuItem();\n toolsMenu = new JMenu();\n startRaffleOption = new JMenuItem();\n startVoteOption = new JMenuItem();\n soundsToggle = new JCheckBoxMenuItem();\n soundDelayMenu = new JMenu();\n soundDelayOffOption = new JRadioButtonMenuItem();\n soundDelay5secOption = new JRadioButtonMenuItem();\n soundDelay10secOption = new JRadioButtonMenuItem();\n soundDelay20secOption = new JRadioButtonMenuItem();\n soundDelayCustomOption = new JRadioButtonMenuItem();\n soundDelayCustomOption.setToolTipText(\"Set a custom sound delay with \\\"!setsound (time)\\\" in chat\");\n soundPermissionMenu = new JMenu();\n soundPermEveryoneOption = new JRadioButtonMenuItem();\n soundPermSDMBOption = new JRadioButtonMenuItem();\n soundPermDMBOption = new JRadioButtonMenuItem();\n soundPermModAndBroadOption = new JRadioButtonMenuItem();\n soundPermBroadOption = new JRadioButtonMenuItem();\n manageTextCommandsOption = new JMenuItem();\n runAdMenu = new JMenu();\n timeOption30sec = new JMenuItem();\n timeOption60sec = new JMenuItem();\n timeOption90sec = new JMenuItem();\n timeOption120sec = new JMenuItem();\n timeOption150sec = new JMenuItem();\n timeOption180sec = new JMenuItem();\n updateStatusOption = new JMenuItem();\n subOnlyToggle = new JCheckBoxMenuItem();\n slowModeMenu = new JMenu();\n slowModeOffOption = new JRadioButtonMenuItem();\n slowMode5secOption = new JRadioButtonMenuItem();\n slowMode10secOption = new JRadioButtonMenuItem();\n slowMode15secOption = new JRadioButtonMenuItem();\n slowMode30secOption = new JRadioButtonMenuItem();\n slowModeCustomOption = new JRadioButtonMenuItem();\n slowModeCustomOption.setToolTipText(\"Set a custom slow mode time with \\\"/slow (time in seconds)\\\" in chat\");\n helpMenu = new JMenu();\n projectGithubOption = new JMenuItem();\n projectWikiOption = new JMenuItem();\n projectDetailsOption = new JMenuItem();\n channelPane = new DraggableTabbedPane();\n allChatsScroll = new JScrollPane();\n allChats = new JTextPane();\n dankLabel = new JLabel();\n scrollPane1 = new JScrollPane();\n userChat = new JTextArea();\n\n //======== Botnak ========\n {\n setMinimumSize(new Dimension(640, 404));\n setName(\"Botnak Control Panel\");\n setTitle(\"Botnak | Please go to Preferences->Settings!\");\n setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n setIconImage(new ImageIcon(getClass().getResource(\"/image/icon.png\")).getImage());\n Container BotnakContentPane = getContentPane();\n\n //======== menuBar1 ========\n {\n\n //======== fileMenu ========\n {\n fileMenu.setText(\"File\");\n\n //---- openBotnakFolderOption ----\n openBotnakFolderOption.setText(\"Open Botnak Folder\");\n openBotnakFolderOption.addActionListener(e -> openBotnakFolderOptionActionPerformed());\n fileMenu.add(openBotnakFolderOption);\n\n //---- openLogViewerOption ----\n openLogViewerOption.setText(\"Open Log Viewer\");\n openLogViewerOption.addActionListener(e -> openLogViewerOptionActionPerformed());\n openLogViewerOption.setEnabled(false);//TODO\n fileMenu.add(openLogViewerOption);\n\n //---- openSoundsOption ----\n openSoundsOption.setText(\"Open Sound Directory\");\n openSoundsOption.addActionListener(e -> openSoundsOptionActionPerformed());\n fileMenu.add(openSoundsOption);\n fileMenu.addSeparator();\n\n //---- exitOption ----\n exitOption.setText(\"Save and Exit\");\n exitOption.addActionListener(e -> exitButtonActionPerformed());\n fileMenu.add(exitOption);\n }\n menuBar1.add(fileMenu);\n\n //======== preferencesMenu ========\n {\n preferencesMenu.setText(\"Preferences\");\n\n //======== botReplyMenu ========\n {\n botReplyMenu.setText(\"Bot Reply\");\n\n //---- botReplyAll ----\n botReplyAll.setText(\"Reply to all\");\n botReplyAll.addActionListener(e -> {\n if (bot != null) {\n Response r = bot.parseReplyType(\"2\", Settings.accountManager.getUserAccount().getName());\n logCurrent(r.getResponseText());\n }\n });\n botReplyMenu.add(botReplyAll);\n\n //---- botReplyJustYou ----\n botReplyJustYou.setText(\"Reply to you\");\n botReplyJustYou.addActionListener(e -> {\n if (bot != null) {\n Response r = bot.parseReplyType(\"1\", Settings.accountManager.getUserAccount().getName());\n logCurrent(r.getResponseText());\n }\n });\n botReplyMenu.add(botReplyJustYou);\n\n //---- botReplyNobody ----\n botReplyNobody.setText(\"Reply to none\");\n botReplyNobody.addActionListener(e -> {\n if (bot != null) {\n Response r = bot.parseReplyType(\"0\", Settings.accountManager.getUserAccount().getName());\n logCurrent(r.getResponseText());\n }\n });\n botReplyNobody.setSelected(true);\n botReplyMenu.add(botReplyNobody);\n }\n preferencesMenu.add(botReplyMenu);\n\n //---- autoReconnectToggle ----\n autoReconnectToggle.setText(\"Auto-Reconnect\");\n autoReconnectToggle.setSelected(true);\n autoReconnectToggle.addItemListener(this::autoReconnectToggleItemStateChanged);\n preferencesMenu.add(autoReconnectToggle);\n\n //---- alwaysOnTopToggle ----\n alwaysOnTopToggle.setText(\"Always On Top\");\n alwaysOnTopToggle.setSelected(false);\n alwaysOnTopToggle.addItemListener(this::alwaysOnTopToggleItemStateChanged);\n preferencesMenu.add(alwaysOnTopToggle);\n preferencesMenu.addSeparator();\n\n //---- settingsOption ----\n settingsOption.setText(\"Settings...\");\n settingsOption.addActionListener(e -> settingsOptionActionPerformed());\n preferencesMenu.add(settingsOption);\n }\n menuBar1.add(preferencesMenu);\n\n //======== toolsMenu ========\n {\n toolsMenu.setText(\"Tools\");\n\n //---- startRaffleOption ----\n startRaffleOption.setText(\"Create Raffle...\");\n startRaffleOption.addActionListener(e -> startRaffleOptionActionPerformed());\n toolsMenu.add(startRaffleOption);\n\n //---- startVoteOption ----\n startVoteOption.setText(\"Create Vote...\");\n startVoteOption.addActionListener(e -> startVoteOptionActionPerformed());\n toolsMenu.add(startVoteOption);\n\n //---- soundsToggle ----\n soundsToggle.setText(\"Enable Sounds\");\n soundsToggle.setSelected(true);\n soundsToggle.addActionListener(e -> soundsToggleItemStateChanged());\n toolsMenu.add(soundsToggle);\n\n //======== soundDelayMenu ========\n {\n soundDelayMenu.setText(\"Sound Delay\");\n\n //---- soundDelayOffOption ----\n soundDelayOffOption.setText(\"None (Off)\");\n soundDelayOffOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 0)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"0\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelayMenu.add(soundDelayOffOption);\n\n //---- soundDelay5secOption ----\n soundDelay5secOption.setText(\"5 seconds\");\n soundDelay5secOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 5000)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"5\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelayMenu.add(soundDelay5secOption);\n\n //---- soundDelay10secOption ----\n soundDelay10secOption.setText(\"10 seconds\");\n soundDelay10secOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 10000)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"10\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelay10secOption.setSelected(true);\n soundDelayMenu.add(soundDelay10secOption);\n\n //---- soundDelay20secOption ----\n soundDelay20secOption.setText(\"20 seconds\");\n soundDelay20secOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null && Settings.soundEngineDelay.getValue() != 20000)\n {\n Response r = SoundEngine.getEngine().setSoundDelay(\"20\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundDelayMenu.add(soundDelay20secOption);\n\n //---- soundDelayCustomOption ----\n soundDelayCustomOption.setText(\"Custom (Use chat)\");\n soundDelayCustomOption.setEnabled(false);\n soundDelayMenu.add(soundDelayCustomOption);\n }\n toolsMenu.add(soundDelayMenu);\n\n //======== soundPermissionMenu ========\n {\n soundPermissionMenu.setText(\"Sound Permission\");\n\n //---- soundPermEveryoneOption ----\n soundPermEveryoneOption.setText(\"Everyone\");\n soundPermEveryoneOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"0\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermEveryoneOption);\n\n //---- soundPermSDMBOption ----\n soundPermSDMBOption.setText(\"Subs, Donors, Mods, Broadcaster\");\n soundPermSDMBOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"1\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermSDMBOption.setSelected(true);\n soundPermissionMenu.add(soundPermSDMBOption);\n\n //---- soundPermDMBOption ----\n soundPermDMBOption.setText(\"Donors, Mods, Broadcaster\");\n soundPermDMBOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"2\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermDMBOption);\n\n //---- soundPermModAndBroadOption ----\n soundPermModAndBroadOption.setText(\"Mods and Broadcaster Only\");\n soundPermModAndBroadOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"3\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermModAndBroadOption);\n\n //---- soundPermBroadOption ----\n soundPermBroadOption.setText(\"Broadcaster Only\");\n soundPermBroadOption.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = SoundEngine.getEngine().setSoundPermission(\"4\");\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n }\n });\n soundPermissionMenu.add(soundPermBroadOption);\n }\n toolsMenu.add(soundPermissionMenu);\n\n //---- manageTextCommandsOption ----\n manageTextCommandsOption.setText(\"Manage Text Commands...\");\n manageTextCommandsOption.setEnabled(false);//TODO\n manageTextCommandsOption.addActionListener(e -> manageTextCommandsOptionActionPerformed());\n toolsMenu.add(manageTextCommandsOption);\n toolsMenu.addSeparator();\n\n //======== runAdMenu ========\n {\n runAdMenu.setText(\"Run Ad\");\n\n //---- timeOption30sec ----\n timeOption30sec.setText(\"30 sec\");\n timeOption30sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"30\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(30000);\n logCurrent(\"The 30-second advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption30sec);\n\n //---- timeOption60sec ----\n timeOption60sec.setText(\"1 min\");\n timeOption60sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"1m\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(60000);\n logCurrent(\"The 1-minute advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption60sec);\n\n //---- timeOption90sec ----\n timeOption90sec.setText(\"1 min 30 sec\");\n timeOption90sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"1m30s\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(90000);\n logCurrent(\"The 1-minute 30-second advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption90sec);\n\n //---- timeOption120sec ----\n timeOption120sec.setText(\"2 min\");\n timeOption120sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"2m\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(120000);\n logCurrent(\"The 2 minute advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption120sec);\n\n //---- timeOption150sec ----\n timeOption150sec.setText(\"2 min 30 sec\");\n timeOption150sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"2m30s\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(150000);\n logCurrent(\"The 2 minute 30 second advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption150sec);\n\n //---- timeOption180sec ----\n timeOption180sec.setText(\"3 min\");\n timeOption180sec.addActionListener(e -> {\n if (bot != null && bot.getBot() != null) {\n Response r = bot.playAdvert(Settings.accountManager.getUserAccount().getOAuth(),\n \"3m\", Settings.accountManager.getUserAccount().getName());\n bot.getBot().sendMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n r.getResponseText());\n ThreadEngine.submit(() -> {\n try {\n Thread.sleep(180000);\n logCurrent(\"The 3 minute advertisement has ended.\");\n } catch (InterruptedException ignored) {\n }\n });\n }\n });\n runAdMenu.add(timeOption180sec);\n }\n toolsMenu.add(runAdMenu);\n\n //---- updateStatusOption ----\n updateStatusOption.setText(\"Update Status...\");\n updateStatusOption.addActionListener(e -> updateStatusOptionActionPerformed());\n toolsMenu.add(updateStatusOption);\n\n //---- subOnlyToggle ----\n subOnlyToggle.setText(\"Sub-only Chat\");\n subOnlyToggle.addActionListener(e -> subOnlyToggleItemStateChanged());\n toolsMenu.add(subOnlyToggle);\n\n //======== slowModeMenu ========\n {\n slowModeMenu.setText(\"Slow Mode\");\n\n //---- slowModeOffOption ----\n slowModeOffOption.setText(\"Off\");\n slowModeOffOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slowoff\");\n }\n });\n slowModeOffOption.setSelected(true);\n slowModeMenu.add(slowModeOffOption);\n\n //---- slowMode5secOption ----\n slowMode5secOption.setText(\"5 seconds\");\n slowMode5secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 5\");\n }\n });\n slowModeMenu.add(slowMode5secOption);\n\n //---- slowMode10secOption ----\n slowMode10secOption.setText(\"10 seconds\");\n slowMode10secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 10\");\n }\n });\n slowModeMenu.add(slowMode10secOption);\n\n //---- slowMode15secOption ----\n slowMode15secOption.setText(\"15 seconds\");\n slowMode15secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 15\");\n }\n });\n slowModeMenu.add(slowMode15secOption);\n\n //---- slowMode30secOption ----\n slowMode30secOption.setText(\"30 seconds\");\n slowMode30secOption.addActionListener(e -> {\n if (viewer != null) {\n viewer.getViewer().sendRawMessage(\"#\" + Settings.accountManager.getUserAccount().getName(),\n \"/slow 30\");\n }\n });\n slowModeMenu.add(slowMode30secOption);\n\n //---- slowModeCustomOption ----\n slowModeCustomOption.setText(\"Custom (use chat)\");\n slowModeCustomOption.setEnabled(false);\n slowModeMenu.add(slowModeCustomOption);\n }\n toolsMenu.add(slowModeMenu);\n }\n menuBar1.add(toolsMenu);\n\n //======== helpMenu ========\n {\n helpMenu.setText(\"Help\");\n\n //---- projectGithubOption ----\n projectGithubOption.setText(\"Botnak Github\");\n projectGithubOption.addActionListener(e -> projectGithubOptionActionPerformed());\n helpMenu.add(projectGithubOption);\n\n //---- projectWikiOption ----\n projectWikiOption.setText(\"Botnak Wiki\");\n projectWikiOption.addActionListener(e -> projectWikiOptionActionPerformed());\n helpMenu.add(projectWikiOption);\n JMenuItem bugReport = new JMenuItem(\"Report an Issue\");\n bugReport.addActionListener(e -> Utils.openWebPage(\"https://github.com/Gocnak/Botnak/issues/new\"));\n helpMenu.add(bugReport);\n helpMenu.addSeparator();\n\n //---- projectDetailsOption ----\n projectDetailsOption.setText(\"About...\");\n projectDetailsOption.addActionListener(e -> projectDetailsOptionActionPerformed());\n helpMenu.add(projectDetailsOption);\n }\n menuBar1.add(helpMenu);\n }\n setJMenuBar(menuBar1);\n\n //======== channelPane ========\n {\n channelPane.setFocusable(false);\n channelPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);\n channelPane.setAutoscrolls(true);\n channelPane.addChangeListener(Constants.tabListener);\n channelPane.addMouseListener(Constants.tabListener);\n\n //======== allChatsScroll ========\n {\n allChatsScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n\n //---- allChats ----\n allChats.setEditable(false);\n allChats.setForeground(Color.white);\n allChats.setBackground(Color.black);\n allChats.setFont(new Font(\"Calibri\", Font.PLAIN, 16));\n allChats.setMargin(new Insets(0, 0, 0, 0));\n allChats.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);\n allChats.addMouseListener(Constants.listenerURL);\n allChats.addMouseListener(Constants.listenerName);\n allChats.setEditorKit(Constants.wrapEditorKit);\n allChatsScroll.setViewportView(allChats);\n }\n channelPane.addTab(\"System Logs\", allChatsScroll);\n\n //---- dankLabel ----\n dankLabel.setText(\"Dank memes\");\n channelPane.addTab(\"+\", dankLabel);\n channelPane.setEnabledAt(channelPane.getTabCount() - 1, false);\n channelPane.addMouseListener(new NewTabListener());\n }\n\n //======== scrollPane1 ========\n {\n scrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\n\n //---- userChat ----\n userChat.setFont(new Font(\"Consolas\", Font.PLAIN, 12));\n userChat.setLineWrap(true);\n userChat.setWrapStyleWord(true);\n userChat.addKeyListener(new ListenerUserChat(userChat));\n scrollPane1.setViewportView(userChat);\n }\n\n GroupLayout BotnakContentPaneLayout = new GroupLayout(BotnakContentPane);\n BotnakContentPane.setLayout(BotnakContentPaneLayout);\n BotnakContentPaneLayout.setHorizontalGroup(\n BotnakContentPaneLayout.createParallelGroup()\n .addComponent(channelPane, GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE)\n .addComponent(scrollPane1)\n );\n BotnakContentPaneLayout.setVerticalGroup(\n BotnakContentPaneLayout.createParallelGroup()\n .addGroup(BotnakContentPaneLayout.createSequentialGroup()\n .addComponent(channelPane, GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)\n .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE))\n );\n addComponentListener(new ComponentAdapter() {\n @Override\n public void componentResized(ComponentEvent e) {\n if (channelPane != null) {\n channelPane.scrollDownPanes();\n }\n }\n });\n addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n exitButtonActionPerformed();\n }\n });\n pack();\n setLocationRelativeTo(getOwner());\n }\n\n //---- botReplyGroup ----\n ButtonGroup botReplyGroup = new ButtonGroup();\n botReplyGroup.add(botReplyAll);\n botReplyGroup.add(botReplyJustYou);\n botReplyGroup.add(botReplyNobody);\n\n //---- soundDelayGroup ----\n ButtonGroup soundDelayGroup = new ButtonGroup();\n soundDelayGroup.add(soundDelayOffOption);\n soundDelayGroup.add(soundDelay5secOption);\n soundDelayGroup.add(soundDelay10secOption);\n soundDelayGroup.add(soundDelay20secOption);\n soundDelayGroup.add(soundDelayCustomOption);\n\n //---- soundPermissionGroup ----\n ButtonGroup soundPermissionGroup = new ButtonGroup();\n soundPermissionGroup.add(soundPermEveryoneOption);\n soundPermissionGroup.add(soundPermSDMBOption);\n soundPermissionGroup.add(soundPermDMBOption);\n soundPermissionGroup.add(soundPermModAndBroadOption);\n soundPermissionGroup.add(soundPermBroadOption);\n\n //---- slowModeGroup ----\n ButtonGroup slowModeGroup = new ButtonGroup();\n slowModeGroup.add(slowModeOffOption);\n slowModeGroup.add(slowMode5secOption);\n slowModeGroup.add(slowMode10secOption);\n slowModeGroup.add(slowMode15secOption);\n slowModeGroup.add(slowMode30secOption);\n slowModeGroup.add(slowModeCustomOption);\n // JFormDesigner - End of component initialization //GEN-END:initComponents\n }\n\n // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables\n // Generated using JFormDesigner Evaluation license - Nick K\n private JMenuBar menuBar1;\n private JMenu fileMenu;\n private JMenuItem openBotnakFolderOption;\n private JMenuItem openLogViewerOption;\n private JMenuItem openSoundsOption;\n private JMenuItem exitOption;\n private JMenu preferencesMenu;\n private JMenu botReplyMenu;\n private JRadioButtonMenuItem botReplyAll;\n private JRadioButtonMenuItem botReplyJustYou;\n private JRadioButtonMenuItem botReplyNobody;\n private JCheckBoxMenuItem autoReconnectToggle;\n public JCheckBoxMenuItem alwaysOnTopToggle;\n private JMenuItem settingsOption;\n private JMenu toolsMenu;\n private JMenuItem startRaffleOption;\n private JMenuItem startVoteOption;\n private JCheckBoxMenuItem soundsToggle;\n private JMenu soundDelayMenu;\n private JRadioButtonMenuItem soundDelayOffOption;\n private JRadioButtonMenuItem soundDelay5secOption;\n private JRadioButtonMenuItem soundDelay10secOption;\n private JRadioButtonMenuItem soundDelay20secOption;\n private JRadioButtonMenuItem soundDelayCustomOption;\n private JMenu soundPermissionMenu;\n private JRadioButtonMenuItem soundPermEveryoneOption;\n private JRadioButtonMenuItem soundPermSDMBOption;\n private JRadioButtonMenuItem soundPermDMBOption;\n private JRadioButtonMenuItem soundPermModAndBroadOption;\n private JRadioButtonMenuItem soundPermBroadOption;\n private JMenuItem manageTextCommandsOption;\n public JMenu runAdMenu;\n private JMenuItem timeOption30sec;\n private JMenuItem timeOption60sec;\n private JMenuItem timeOption90sec;\n private JMenuItem timeOption120sec;\n private JMenuItem timeOption150sec;\n private JMenuItem timeOption180sec;\n public JMenuItem updateStatusOption;\n private JCheckBoxMenuItem subOnlyToggle;\n private JMenu slowModeMenu;\n private JRadioButtonMenuItem slowModeOffOption;\n private JRadioButtonMenuItem slowMode5secOption;\n private JRadioButtonMenuItem slowMode10secOption;\n private JRadioButtonMenuItem slowMode15secOption;\n private JRadioButtonMenuItem slowMode30secOption;\n private JRadioButtonMenuItem slowModeCustomOption;\n private JMenu helpMenu;\n private JMenuItem projectGithubOption;\n private JMenuItem projectWikiOption;\n private JMenuItem projectDetailsOption;\n public static DraggableTabbedPane channelPane;\n private JScrollPane allChatsScroll;\n private JTextPane allChats;\n private JLabel dankLabel;\n private JScrollPane scrollPane1;\n public static JTextArea userChat;\n}", "@SuppressWarnings(\"unused\")\npublic class Scalr {\n /**\n * System property name used to define the debug boolean flag.\n * <p>\n * Value is \"<code>imgscalr.debug</code>\".\n */\n public static final String DEBUG_PROPERTY_NAME = \"imgscalr.debug\";\n\n /**\n * System property name used to define a custom log prefix.\n * <p>\n * Value is \"<code>imgscalr.logPrefix</code>\".\n */\n public static final String LOG_PREFIX_PROPERTY_NAME = \"imgscalr.logPrefix\";\n\n /**\n * Flag used to indicate if debugging output has been enabled by setting the\n * \"<code>imgscalr.debug</code>\" system property to <code>true</code>. This\n * value will be <code>false</code> if the \"<code>imgscalr.debug</code>\"\n * system property is undefined or set to <code>false</code>.\n * <p>\n * This property can be set on startup with:<br/>\n * <code>\n * -Dimgscalr.debug=true\n * </code> or by calling {@link System#setProperty(String, String)} to set a\n * new property value for {@link #DEBUG_PROPERTY_NAME} before this class is\n * loaded.\n * <p>\n * Default value is <code>false</code>.\n */\n public static final boolean DEBUG = Boolean.getBoolean(DEBUG_PROPERTY_NAME);\n\n /**\n * Prefix to every log message this library logs. Using a well-defined\n * prefix helps make it easier both visually and programmatically to scan\n * log files for messages produced by this library.\n * <p>\n * This property can be set on startup with:<br/>\n * <code>\n * -Dimgscalr.logPrefix=&lt;YOUR PREFIX HERE&gt;\n * </code> or by calling {@link System#setProperty(String, String)} to set a\n * new property value for {@link #LOG_PREFIX_PROPERTY_NAME} before this\n * class is loaded.\n * <p>\n * Default value is \"<code>[imgscalr] </code>\" (including the space).\n */\n public static final String LOG_PREFIX = System.getProperty(\n LOG_PREFIX_PROPERTY_NAME, \"[imgscalr] \");\n\n /**\n * A {@link ConvolveOp} using a very light \"blur\" kernel that acts like an\n * anti-aliasing filter (softens the image a bit) when applied to an image.\n * <p>\n * A common request by users of the library was that they wished to \"soften\"\n * resulting images when scaling them down drastically. After quite a bit of\n * A/B testing, the kernel used by this Op was selected as the closest match\n * for the target which was the softer results from the deprecated\n * {@link AreaAveragingScaleFilter} (which is used internally by the\n * deprecated {@link Image#getScaledInstance(int, int, int)} method in the\n * JDK that imgscalr is meant to replace).\n * <p>\n * This ConvolveOp uses a 3x3 kernel with the values:\n * <table cellpadding=\"4\" border=\"1\">\n * <tr>\n * <td>.0f</td>\n * <td>.08f</td>\n * <td>.0f</td>\n * </tr>\n * <tr>\n * <td>.08f</td>\n * <td>.68f</td>\n * <td>.08f</td>\n * </tr>\n * <tr>\n * <td>.0f</td>\n * <td>.08f</td>\n * <td>.0f</td>\n * </tr>\n * </table>\n * <p>\n * For those that have worked with ConvolveOps before, this Op uses the\n * {@link ConvolveOp#EDGE_NO_OP} instruction to not process the pixels along\n * the very edge of the image (otherwise EDGE_ZERO_FILL would create a\n * black-border around the image). If you have not worked with a ConvolveOp\n * before, it just means this default OP will \"do the right thing\" and not\n * give you garbage results.\n * <p>\n * This ConvolveOp uses no {@link RenderingHints} values as internally the\n * {@link ConvolveOp} class only uses hints when doing a color conversion\n * between the source and destination {@link BufferedImage} targets.\n * imgscalr allows the {@link ConvolveOp} to create its own destination\n * image every time, so no color conversion is ever needed and thus no\n * hints.\n * <h3>Performance</h3>\n * Use of this (and other) {@link ConvolveOp}s are hardware accelerated when\n * possible. For more information on if your image op is hardware\n * accelerated or not, check the source code of the underlying JDK class\n * that actually executes the Op code, <a href=\n * \"http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html\"\n * >sun.awt.image.ImagingLib</a>.\n * <h3>Known Issues</h3>\n * In all versions of Java (tested up to Java 7 preview Build 131), running\n * this op against a GIF with transparency and attempting to save the\n * resulting image as a GIF results in a corrupted/empty file. The file must\n * be saved out as a PNG to maintain the transparency.\n *\n * @since 3.0\n */\n public static final ConvolveOp OP_ANTIALIAS = new ConvolveOp(\n new Kernel(3, 3, new float[]{.0f, .08f, .0f, .08f, .68f, .08f,\n .0f, .08f, .0f}), ConvolveOp.EDGE_NO_OP, null\n );\n\n /**\n * A {@link RescaleOp} used to make any input image 10% darker.\n * <p>\n * This operation can be applied multiple times in a row if greater than 10%\n * changes in brightness are desired.\n *\n * @since 4.0\n */\n public static final RescaleOp OP_DARKER = new RescaleOp(0.9f, 0, null);\n\n /**\n * A {@link RescaleOp} used to make any input image 10% brighter.\n * <p>\n * This operation can be applied multiple times in a row if greater than 10%\n * changes in brightness are desired.\n *\n * @since 4.0\n */\n public static final RescaleOp OP_BRIGHTER = new RescaleOp(1.1f, 0, null);\n\n /**\n * A {@link ColorConvertOp} used to convert any image to a grayscale color\n * palette.\n * <p>\n * Applying this op multiple times to the same image has no compounding\n * effects.\n *\n * @since 4.0\n */\n public static final ColorConvertOp OP_GRAYSCALE = new ColorConvertOp(\n ColorSpace.getInstance(ColorSpace.CS_GRAY), null);\n\n /**\n * Static initializer used to prepare some of the variables used by this\n * class.\n */\n static {\n log(0, \"Debug output ENABLED\");\n }\n\n /**\n * Used to define the different scaling hints that the algorithm can use.\n *\n * @author Riyad Kalla ([email protected])\n * @since 1.1\n */\n public enum Method {\n /**\n * Used to indicate that the scaling implementation should decide which\n * method to use in order to get the best looking scaled image in the\n * least amount of time.\n * <p>\n * The scaling algorithm will use the\n * {@link Scalr#THRESHOLD_QUALITY_BALANCED} or\n * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds as cut-offs to\n * decide between selecting the <code>QUALITY</code>,\n * <code>BALANCED</code> or <code>SPEED</code> scaling algorithms.\n * <p>\n * By default the thresholds chosen will give nearly the best looking\n * result in the fastest amount of time. We intend this method to work\n * for 80% of people looking to scale an image quickly and get a good\n * looking result.\n */\n AUTOMATIC,\n /**\n * Used to indicate that the scaling implementation should scale as fast\n * as possible and return a result. For smaller images (800px in size)\n * this can result in noticeable aliasing but it can be a few magnitudes\n * times faster than using the QUALITY method.\n */\n SPEED,\n /**\n * Used to indicate that the scaling implementation should use a scaling\n * operation balanced between SPEED and QUALITY. Sometimes SPEED looks\n * too low quality to be useful (e.g. text can become unreadable when\n * scaled using SPEED) but using QUALITY mode will increase the\n * processing time too much. This mode provides a \"better than SPEED\"\n * quality in a \"less than QUALITY\" amount of time.\n */\n BALANCED,\n /**\n * Used to indicate that the scaling implementation should do everything\n * it can to create as nice of a result as possible. This approach is\n * most important for smaller pictures (800px or smaller) and less\n * important for larger pictures as the difference between this method\n * and the SPEED method become less and less noticeable as the\n * source-image size increases. Using the AUTOMATIC method will\n * automatically prefer the QUALITY method when scaling an image down\n * below 800px in size.\n */\n QUALITY,\n /**\n * Used to indicate that the scaling implementation should go above and\n * beyond the work done by {@link Method#QUALITY} to make the image look\n * exceptionally good at the cost of more processing time. This is\n * especially evident when generating thumbnails of images that look\n * jagged with some of the other {@link Method}s (even\n * {@link Method#QUALITY}).\n */\n ULTRA_QUALITY\n }\n\n /**\n * Used to define the different modes of resizing that the algorithm can\n * use.\n *\n * @author Riyad Kalla ([email protected])\n * @since 3.1\n */\n public enum Mode {\n /**\n * Used to indicate that the scaling implementation should calculate\n * dimensions for the resultant image by looking at the image's\n * orientation and generating proportional dimensions that best fit into\n * the target width and height given\n * <p>\n * See \"Image Proportions\" in the {@link Scalr} class description for\n * more detail.\n */\n AUTOMATIC,\n /**\n * Used to fit the image to the exact dimensions given regardless of the\n * image's proportions. If the dimensions are not proportionally\n * correct, this will introduce vertical or horizontal stretching to the\n * image.\n * <p>\n * It is recommended that you use one of the other <code>FIT_TO</code>\n * modes or {@link Mode#AUTOMATIC} if you want the image to look\n * correct, but if dimension-fitting is the #1 priority regardless of\n * how it makes the image look, that is what this mode is for.\n */\n FIT_EXACT,\n /**\n * Used to indicate that the scaling implementation should calculate\n * dimensions for the resultant image that best-fit within the given\n * width, regardless of the orientation of the image.\n */\n FIT_TO_WIDTH,\n /**\n * Used to indicate that the scaling implementation should calculate\n * dimensions for the resultant image that best-fit within the given\n * height, regardless of the orientation of the image.\n */\n FIT_TO_HEIGHT\n }\n\n /**\n * Used to define the different types of rotations that can be applied to an\n * image during a resize operation.\n *\n * @author Riyad Kalla ([email protected])\n * @since 3.2\n */\n public enum Rotation {\n /**\n * 90-degree, clockwise rotation (to the right). This is equivalent to a\n * quarter-turn of the image to the right; moving the picture on to its\n * right side.\n */\n CW_90,\n /**\n * 180-degree, clockwise rotation (to the right). This is equivalent to\n * 1 half-turn of the image to the right; rotating the picture around\n * until it is upside down from the original position.\n */\n CW_180,\n /**\n * 270-degree, clockwise rotation (to the right). This is equivalent to\n * a quarter-turn of the image to the left; moving the picture on to its\n * left side.\n */\n CW_270,\n /**\n * Flip the image horizontally by reflecting it around the y axis.\n * <p>\n * This is not a standard rotation around a center point, but instead\n * creates the mirrored reflection of the image horizontally.\n * <p>\n * More specifically, the vertical orientation of the image stays the\n * same (the top stays on top, and the bottom on bottom), but the right\n * and left sides flip. This is different than a standard rotation where\n * the top and bottom would also have been flipped.\n */\n FLIP_HORZ,\n /**\n * Flip the image vertically by reflecting it around the x axis.\n * <p>\n * This is not a standard rotation around a center point, but instead\n * creates the mirrored reflection of the image vertically.\n * <p>\n * More specifically, the horizontal orientation of the image stays the\n * same (the left stays on the left and the right stays on the right),\n * but the top and bottom sides flip. This is different than a standard\n * rotation where the left and right would also have been flipped.\n */\n FLIP_VERT\n }\n\n /**\n * Threshold (in pixels) at which point the scaling operation using the\n * {@link Method#AUTOMATIC} method will decide if a {@link Method#BALANCED}\n * method will be used (if smaller than or equal to threshold) or a\n * {@link Method#SPEED} method will be used (if larger than threshold).\n * <p>\n * The bigger the image is being scaled to, the less noticeable degradations\n * in the image becomes and the faster algorithms can be selected.\n * <p>\n * The value of this threshold (1600) was chosen after visual, by-hand, A/B\n * testing between different types of images scaled with this library; both\n * photographs and screenshots. It was determined that images below this\n * size need to use a {@link Method#BALANCED} scale method to look decent in\n * most all cases while using the faster {@link Method#SPEED} method for\n * images bigger than this threshold showed no noticeable degradation over a\n * <code>BALANCED</code> scale.\n */\n public static final int THRESHOLD_BALANCED_SPEED = 1600;\n\n /**\n * Threshold (in pixels) at which point the scaling operation using the\n * {@link Method#AUTOMATIC} method will decide if a {@link Method#QUALITY}\n * method will be used (if smaller than or equal to threshold) or a\n * {@link Method#BALANCED} method will be used (if larger than threshold).\n * <p>\n * The bigger the image is being scaled to, the less noticeable degradations\n * in the image becomes and the faster algorithms can be selected.\n * <p>\n * The value of this threshold (800) was chosen after visual, by-hand, A/B\n * testing between different types of images scaled with this library; both\n * photographs and screenshots. It was determined that images below this\n * size need to use a {@link Method#QUALITY} scale method to look decent in\n * most all cases while using the faster {@link Method#BALANCED} method for\n * images bigger than this threshold showed no noticeable degradation over a\n * <code>QUALITY</code> scale.\n */\n public static final int THRESHOLD_QUALITY_BALANCED = 800;\n\n /**\n * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to\n * a given {@link BufferedImage} and return the result.\n * <p>\n * <strong>Feature</strong>: This implementation works around <a\n * href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606\">a\n * decade-old JDK bug</a> that can cause a {@link RasterFormatException}\n * when applying a perfectly valid {@link BufferedImageOp}s to images.\n * <p>\n * <strong>Feature</strong>: This implementation also works around\n * {@link BufferedImageOp}s failing to apply and throwing\n * {@link ImagingOpException}s when run against a <code>src</code> image\n * type that is poorly supported. Unfortunately using {@link ImageIO} and\n * standard Java methods to load images provides no consistency in getting\n * images in well-supported formats. This method automatically accounts and\n * corrects for all those problems (if necessary).\n * <p>\n * It is recommended you always use this method to apply any\n * {@link BufferedImageOp}s instead of relying on directly using the\n * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.\n * <p>\n * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are\n * hardware accelerated operations, but many of the most popular (like\n * {@link ConvolveOp}) are. For more information on if your image op is\n * hardware accelerated or not, check the source code of the underlying JDK\n * class that actually executes the Op code, <a href=\n * \"http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html\"\n * >sun.awt.image.ImagingLib</a>.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will have the ops applied to it.\n * @param ops <code>1</code> or more ops to apply to the image.\n * @return a new {@link BufferedImage} that represents the <code>src</code>\n * with all the given operations applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>ops</code> is <code>null</code> or empty.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (ops == null || ops.length == 0)\n throw new IllegalArgumentException(\"ops cannot be null or empty\");\n\n int type = src.getType();\n\n\t\t/*\n * Ensure the src image is in the best supported image type before we\n\t\t * continue, otherwise it is possible our calls below to getBounds2D and\n\t\t * certainly filter(...) may fail if not.\n\t\t *\n\t\t * Java2D makes an attempt at applying most BufferedImageOps using\n\t\t * hardware acceleration via the ImagingLib internal library.\n\t\t *\n\t\t * Unfortunately may of the BufferedImageOp are written to simply fail\n\t\t * with an ImagingOpException if the operation cannot be applied with no\n\t\t * additional information about what went wrong or attempts at\n\t\t * re-applying it in different ways.\n\t\t *\n\t\t * This is assuming the failing BufferedImageOp even returns a null\n\t\t * image after failing to apply; some simply return a corrupted/black\n\t\t * image that result in no exception and it is up to the user to\n\t\t * discover this.\n\t\t *\n\t\t * In internal testing, EVERY failure I've ever seen was the result of\n\t\t * the source image being in a poorly-supported BufferedImage Type like\n\t\t * BGR or ABGR (even though it was loaded with ImageIO).\n\t\t *\n\t\t * To avoid this nasty/stupid surprise with BufferedImageOps, we always\n\t\t * ensure that the src image starts in an optimally supported format\n\t\t * before we try and apply the filter.\n\t\t */\n if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))\n src = copyToOptimalImage(src);\n\n if (DEBUG)\n log(0, \"Applying %d BufferedImageOps...\", ops.length);\n\n boolean hasReassignedSrc = false;\n\n for (BufferedImageOp op1 : ops) {\n long subT = System.currentTimeMillis();\n\n // Skip null ops instead of throwing an exception.\n if (op1 == null)\n continue;\n\n if (DEBUG)\n log(1, \"Applying BufferedImageOp [class=%s, toString=%s]...\",\n op1.getClass(), op1.toString());\n\n\t\t\t/*\n * Must use op.getBounds instead of src.getWidth and src.getHeight\n\t\t\t * because we are trying to create an image big enough to hold the\n\t\t\t * result of this operation (which may be to scale the image\n\t\t\t * smaller), in that case the bounds reported by this op and the\n\t\t\t * bounds reported by the source image will be different.\n\t\t\t */\n Rectangle2D resultBounds = op1.getBounds2D(src);\n\n // Watch out for flaky/misbehaving ops that fail to work right.\n if (resultBounds == null)\n throw new ImagingOpException(\n \"BufferedImageOp [\"\n + op1.toString()\n + \"] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.\"\n );\n\n\t\t\t/*\n * We must manually create the target image; we cannot rely on the\n\t\t\t * null-destination filter() method to create a valid destination\n\t\t\t * for us thanks to this JDK bug that has been filed for almost a\n\t\t\t * decade:\n\t\t\t * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606\n\t\t\t */\n BufferedImage dest = createOptimalImage(src,\n (int) Math.round(resultBounds.getWidth()),\n (int) Math.round(resultBounds.getHeight()));\n\n // Perform the operation, update our result to return.\n BufferedImage result = op1.filter(src, dest);\n\n\t\t\t/*\n * Flush the 'src' image ONLY IF it is one of our interim temporary\n\t\t\t * images being used when applying 2 or more operations back to\n\t\t\t * back. We never want to flush the original image passed in.\n\t\t\t */\n if (hasReassignedSrc)\n src.flush();\n\n\t\t\t/*\n * Incase there are more operations to perform, update what we\n\t\t\t * consider the 'src' reference to our last result so on the next\n\t\t\t * iteration the next op is applied to this result and not back\n\t\t\t * against the original src passed in.\n\t\t\t */\n src = result;\n\n\t\t\t/*\n * Keep track of when we re-assign 'src' to an interim temporary\n\t\t\t * image, so we know when we can explicitly flush it and clean up\n\t\t\t * references on future iterations.\n\t\t\t */\n hasReassignedSrc = true;\n\n if (DEBUG)\n log(1,\n \"Applied BufferedImageOp in %d ms, result [width=%d, height=%d]\",\n System.currentTimeMillis() - subT, result.getWidth(),\n result.getHeight());\n }\n\n if (DEBUG)\n log(0, \"All %d BufferedImageOps applied in %d ms\", ops.length,\n System.currentTimeMillis() - t);\n\n return src;\n }\n\n /**\n * Used to crop the given <code>src</code> image from the top-left corner\n * and applying any optional {@link BufferedImageOp}s to the result before\n * returning it.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image to crop.\n * @param width The width of the bounding cropping box.\n * @param height The height of the bounding cropping box.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing the cropped region of\n * the <code>src</code> image with any optional operations applied\n * to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if any coordinates of the bounding crop box is invalid within\n * the bounds of the <code>src</code> image (e.g. negative or\n * too big).\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage crop(BufferedImage src, int width, int height,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n return crop(src, 0, 0, width, height, ops);\n }\n\n /**\n * Used to crop the given <code>src</code> image and apply any optional\n * {@link BufferedImageOp}s to it before returning the result.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image to crop.\n * @param x The x-coordinate of the top-left corner of the bounding box\n * used for cropping.\n * @param y The y-coordinate of the top-left corner of the bounding box\n * used for cropping.\n * @param width The width of the bounding cropping box.\n * @param height The height of the bounding cropping box.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing the cropped region of\n * the <code>src</code> image with any optional operations applied\n * to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if any coordinates of the bounding crop box is invalid within\n * the bounds of the <code>src</code> image (e.g. negative or\n * too big).\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage crop(BufferedImage src, int x, int y,\n int width, int height, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (x < 0 || y < 0 || width < 0 || height < 0)\n throw new IllegalArgumentException(\"Invalid crop bounds: x [\" + x\n + \"], y [\" + y + \"], width [\" + width + \"] and height [\"\n + height + \"] must all be >= 0\");\n\n int srcWidth = src.getWidth();\n int srcHeight = src.getHeight();\n\n if ((x + width) > srcWidth)\n throw new IllegalArgumentException(\n \"Invalid crop bounds: x + width [\" + (x + width)\n + \"] must be <= src.getWidth() [\" + srcWidth + \"]\"\n );\n if ((y + height) > srcHeight)\n throw new IllegalArgumentException(\n \"Invalid crop bounds: y + height [\" + (y + height)\n + \"] must be <= src.getHeight() [\" + srcHeight\n + \"]\"\n );\n\n if (DEBUG)\n log(0,\n \"Cropping Image [width=%d, height=%d] to [x=%d, y=%d, width=%d, height=%d]...\",\n srcWidth, srcHeight, x, y, width, height);\n\n // Create a target image of an optimal type to render into.\n BufferedImage result = createOptimalImage(src, width, height);\n Graphics g = result.getGraphics();\n\n\t\t/*\n * Render the region specified by our crop bounds from the src image\n\t\t * directly into our result image (which is the exact size of the crop\n\t\t * region).\n\t\t */\n g.drawImage(src, 0, 0, width, height, x, y, (x + width), (y + height),\n null);\n g.dispose();\n\n if (DEBUG)\n log(0, \"Cropped Image in %d ms\", System.currentTimeMillis() - t);\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Used to apply padding around the edges of an image using\n * {@link Color#BLACK} to fill the extra padded space and then return the\n * result.\n * <p>\n * The amount of <code>padding</code> specified is applied to all sides;\n * more specifically, a <code>padding</code> of <code>2</code> would add 2\n * extra pixels of space (filled by the given <code>color</code>) on the\n * top, bottom, left and right sides of the resulting image causing the\n * result to be 4 pixels wider and 4 pixels taller than the <code>src</code>\n * image.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image the padding will be added to.\n * @param padding The number of pixels of padding to add to each side in the\n * resulting image. If this value is <code>0</code> then\n * <code>src</code> is returned unmodified.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing <code>src</code> with\n * the given padding applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>padding</code> is &lt; <code>1</code>.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage pad(BufferedImage src, int padding,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n return pad(src, padding, Color.BLACK);\n }\n\n /**\n * Used to apply padding around the edges of an image using the given color\n * to fill the extra padded space and then return the result. {@link Color}s\n * using an alpha channel (i.e. transparency) are supported.\n * <p>\n * The amount of <code>padding</code> specified is applied to all sides;\n * more specifically, a <code>padding</code> of <code>2</code> would add 2\n * extra pixels of space (filled by the given <code>color</code>) on the\n * top, bottom, left and right sides of the resulting image causing the\n * result to be 4 pixels wider and 4 pixels taller than the <code>src</code>\n * image.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image the padding will be added to.\n * @param padding The number of pixels of padding to add to each side in the\n * resulting image. If this value is <code>0</code> then\n * <code>src</code> is returned unmodified.\n * @param color The color to fill the padded space with. {@link Color}s using\n * an alpha channel (i.e. transparency) are supported.\n * @param ops <code>0</code> or more ops to apply to the image. If\n * <code>null</code> or empty then <code>src</code> is return\n * unmodified.\n * @return a new {@link BufferedImage} representing <code>src</code> with\n * the given padding applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>padding</code> is &lt; <code>1</code>.\n * @throws IllegalArgumentException if <code>color</code> is <code>null</code>.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage pad(BufferedImage src, int padding,\n Color color, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (padding < 1)\n throw new IllegalArgumentException(\"padding [\" + padding\n + \"] must be > 0\");\n if (color == null)\n throw new IllegalArgumentException(\"color cannot be null\");\n\n int srcWidth = src.getWidth();\n int srcHeight = src.getHeight();\n\n\t\t/*\n * Double the padding to account for all sides of the image. More\n\t\t * specifically, if padding is \"1\" we add 2 pixels to width and 2 to\n\t\t * height, so we have 1 new pixel of padding all the way around our\n\t\t * image.\n\t\t */\n int sizeDiff = (padding * 2);\n int newWidth = srcWidth + sizeDiff;\n int newHeight = srcHeight + sizeDiff;\n\n if (DEBUG)\n log(0,\n \"Padding Image from [originalWidth=%d, originalHeight=%d, padding=%d] to [newWidth=%d, newHeight=%d]...\",\n srcWidth, srcHeight, padding, newWidth, newHeight);\n\n boolean colorHasAlpha = (color.getAlpha() != 255);\n boolean imageHasAlpha = (src.getTransparency() != BufferedImage.OPAQUE);\n\n BufferedImage result;\n\n\t\t/*\n\t\t * We need to make sure our resulting image that we render into contains\n\t\t * alpha if either our original image OR the padding color we are using\n\t\t * contain it.\n\t\t */\n if (colorHasAlpha || imageHasAlpha) {\n if (DEBUG)\n log(1,\n \"Transparency FOUND in source image or color, using ARGB image type...\");\n\n result = new BufferedImage(newWidth, newHeight,\n BufferedImage.TYPE_INT_ARGB);\n } else {\n if (DEBUG)\n log(1,\n \"Transparency NOT FOUND in source image or color, using RGB image type...\");\n\n result = new BufferedImage(newWidth, newHeight,\n BufferedImage.TYPE_INT_RGB);\n }\n\n Graphics g = result.getGraphics();\n\n // \"Clear\" the background of the new image with our padding color first.\n g.setColor(color);\n g.fillRect(0, 0, newWidth, newHeight);\n\n // Draw the image into the center of the new padded image.\n g.drawImage(src, padding, padding, null);\n g.dispose();\n\n if (DEBUG)\n log(0, \"Padding Applied in %d ms\", System.currentTimeMillis() - t);\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} and mode of\n * {@link Mode#AUTOMATIC} are used.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage resize(BufferedImage src, int targetSize,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize,\n targetSize, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> using the given scaling\n * method and apply the given {@link BufferedImageOp}s (if any) to the\n * result before returning it.\n * <p>\n * A mode of {@link Mode#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n int targetSize, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, scalingMethod, Mode.AUTOMATIC, targetSize,\n targetSize, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> (or fitting the image to\n * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode}\n * specified) and apply the given {@link BufferedImageOp}s (if any) to the\n * result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Mode resizeMode,\n int targetSize, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, Method.AUTOMATIC, resizeMode, targetSize,\n targetSize, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to a width and\n * height no bigger than <code>targetSize</code> (or fitting the image to\n * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode}\n * specified) using the given scaling method and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetSize The target width and height (square) that you wish the image\n * to fit within.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetSize</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n Mode resizeMode, int targetSize, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, scalingMethod, resizeMode, targetSize, targetSize,\n ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height and apply the given {@link BufferedImageOp}s (if any) to\n * the result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} and mode of\n * {@link Mode#AUTOMATIC} are used.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n */\n public static BufferedImage resize(BufferedImage src, int targetWidth,\n int targetHeight, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetWidth,\n targetHeight, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height using the given scaling method and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * A mode of {@link Mode#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n int targetWidth, int targetHeight, BufferedImageOp... ops) {\n return resize(src, scalingMethod, Mode.AUTOMATIC, targetWidth,\n targetHeight, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height (or fitting the image to the given WIDTH or HEIGHT\n * explicitly, depending on the {@link Mode} specified) and apply the given\n * {@link BufferedImageOp}s (if any) to the result before returning it.\n * <p>\n * A scaling method of {@link Method#AUTOMATIC} is used.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Mode resizeMode,\n int targetWidth, int targetHeight, BufferedImageOp... ops)\n throws IllegalArgumentException, ImagingOpException {\n return resize(src, Method.AUTOMATIC, resizeMode, targetWidth,\n targetHeight, ops);\n }\n\n /**\n * Resize a given image (maintaining its original proportion) to the target\n * width and height (or fitting the image to the given WIDTH or HEIGHT\n * explicitly, depending on the {@link Mode} specified) using the given\n * scaling method and apply the given {@link BufferedImageOp}s (if any) to\n * the result before returning it.\n * <p>\n * <strong>TIP</strong>: See the class description to understand how this\n * class handles recalculation of the <code>targetWidth</code> or\n * <code>targetHeight</code> depending on the image's orientation in order\n * to maintain the original proportion.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will be scaled.\n * @param scalingMethod The method used for scaling the image; preferring speed to\n * quality or a balance of both.\n * @param resizeMode Used to indicate how imgscalr should calculate the final\n * target size for the image, either fitting the image to the\n * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image\n * to the given height ({@link Mode#FIT_TO_HEIGHT}). If\n * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate\n * proportional dimensions for the scaled image based on its\n * orientation (landscape, square or portrait). Unless you have\n * very specific size requirements, most of the time you just\n * want to use {@link Mode#AUTOMATIC} to \"do the right thing\".\n * @param targetWidth The target width that you wish the image to have.\n * @param targetHeight The target height that you wish the image to have.\n * @param ops <code>0</code> or more optional image operations (e.g.\n * sharpen, blur, etc.) that can be applied to the final result\n * before returning the image.\n * @return a new {@link BufferedImage} representing the scaled\n * <code>src</code> image.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>scalingMethod</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>resizeMode</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>targetWidth</code> is &lt; 0 or if\n * <code>targetHeight</code> is &lt; 0.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Method\n * @see Mode\n */\n public static BufferedImage resize(BufferedImage src, Method scalingMethod,\n Mode resizeMode, int targetWidth, int targetHeight,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (targetWidth < 0)\n throw new IllegalArgumentException(\"targetWidth must be >= 0\");\n if (targetHeight < 0)\n throw new IllegalArgumentException(\"targetHeight must be >= 0\");\n if (scalingMethod == null)\n throw new IllegalArgumentException(\n \"scalingMethod cannot be null. A good default value is Method.AUTOMATIC.\");\n if (resizeMode == null)\n throw new IllegalArgumentException(\n \"resizeMode cannot be null. A good default value is Mode.AUTOMATIC.\");\n\n BufferedImage result = null;\n\n int currentWidth = src.getWidth();\n int currentHeight = src.getHeight();\n\n // <= 1 is a square or landscape-oriented image, > 1 is a portrait.\n float ratio = ((float) currentHeight / (float) currentWidth);\n\n if (DEBUG)\n log(0,\n \"Resizing Image [size=%dx%d, resizeMode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]\",\n currentWidth, currentHeight, resizeMode,\n (ratio <= 1 ? \"Landscape/Square\" : \"Portrait\"), ratio,\n targetWidth, targetHeight);\n\n\t\t/*\n\t\t * First determine if ANY size calculation needs to be done, in the case\n\t\t * of FIT_EXACT, ignore image proportions and orientation and just use\n\t\t * what the user sent in, otherwise the proportion of the picture must\n\t\t * be honored.\n\t\t *\n\t\t * The way that is done is to figure out if the image is in a\n\t\t * LANDSCAPE/SQUARE or PORTRAIT orientation and depending on its\n\t\t * orientation, use the primary dimension (width for LANDSCAPE/SQUARE\n\t\t * and height for PORTRAIT) to recalculate the alternative (height and\n\t\t * width respectively) value that adheres to the existing ratio.\n\t\t *\n\t\t * This helps make life easier for the caller as they don't need to\n\t\t * pre-compute proportional dimensions before calling the API, they can\n\t\t * just specify the dimensions they would like the image to roughly fit\n\t\t * within and it will do the right thing without mangling the result.\n\t\t */\n if (resizeMode != Mode.FIT_EXACT) {\n if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC)\n || (resizeMode == Mode.FIT_TO_WIDTH)) {\n // First make sure we need to do any work in the first place\n if (targetWidth == src.getWidth())\n return src;\n\n // Save for detailed logging (this is cheap).\n int originalTargetHeight = targetHeight;\n\n\t\t\t\t/*\n\t\t\t\t * Landscape or Square Orientation: Ignore the given height and\n\t\t\t\t * re-calculate a proportionally correct value based on the\n\t\t\t\t * targetWidth.\n\t\t\t\t */\n targetHeight = Math.round((float) targetWidth * ratio);\n\n if (DEBUG && originalTargetHeight != targetHeight)\n log(1,\n \"Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions.\",\n originalTargetHeight, targetHeight);\n } else {\n // First make sure we need to do any work in the first place\n if (targetHeight == src.getHeight())\n return src;\n\n // Save for detailed logging (this is cheap).\n int originalTargetWidth = targetWidth;\n\n\t\t\t\t/*\n\t\t\t\t * Portrait Orientation: Ignore the given width and re-calculate\n\t\t\t\t * a proportionally correct value based on the targetHeight.\n\t\t\t\t */\n targetWidth = Math.round((float) targetHeight / ratio);\n\n if (DEBUG && originalTargetWidth != targetWidth)\n log(1,\n \"Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions.\",\n originalTargetWidth, targetWidth);\n }\n } else {\n if (DEBUG)\n log(1,\n \"Resize Mode FIT_EXACT used, no width/height checking or re-calculation will be done.\");\n }\n\n // If AUTOMATIC was specified, determine the real scaling method.\n if (scalingMethod == Scalr.Method.AUTOMATIC)\n scalingMethod = determineScalingMethod(targetWidth, targetHeight,\n ratio);\n\n if (DEBUG)\n log(1, \"Using Scaling Method: %s\", scalingMethod);\n\n // Now we scale the image\n if (scalingMethod == Scalr.Method.SPEED) {\n result = scaleImage(src, targetWidth, targetHeight,\n RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);\n } else if (scalingMethod == Scalr.Method.BALANCED) {\n result = scaleImage(src, targetWidth, targetHeight,\n RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n } else if (scalingMethod == Scalr.Method.QUALITY\n || scalingMethod == Scalr.Method.ULTRA_QUALITY) {\n\t\t\t/*\n\t\t\t * If we are scaling up (in either width or height - since we know\n\t\t\t * the image will stay proportional we just check if either are\n\t\t\t * being scaled up), directly using a single BICUBIC will give us\n\t\t\t * better results then using Chris Campbell's incremental scaling\n\t\t\t * operation (and take a lot less time).\n\t\t\t *\n\t\t\t * If we are scaling down, we must use the incremental scaling\n\t\t\t * algorithm for the best result.\n\t\t\t */\n if (targetWidth > currentWidth || targetHeight > currentHeight) {\n if (DEBUG)\n log(1,\n \"QUALITY scale-up, a single BICUBIC scale operation will be used...\");\n\n\t\t\t\t/*\n\t\t\t\t * BILINEAR and BICUBIC look similar the smaller the scale jump\n\t\t\t\t * upwards is, if the scale is larger BICUBIC looks sharper and\n\t\t\t\t * less fuzzy. But most importantly we have to use BICUBIC to\n\t\t\t\t * match the contract of the QUALITY rendering scalingMethod.\n\t\t\t\t * This note is just here for anyone reading the code and\n\t\t\t\t * wondering how they can speed their own calls up.\n\t\t\t\t */\n result = scaleImage(src, targetWidth, targetHeight,\n RenderingHints.VALUE_INTERPOLATION_BICUBIC);\n } else {\n if (DEBUG)\n log(1,\n \"QUALITY scale-down, incremental scaling will be used...\");\n\n\t\t\t\t/*\n\t\t\t\t * Originally we wanted to use BILINEAR interpolation here\n\t\t\t\t * because it takes 1/3rd the time that the BICUBIC\n\t\t\t\t * interpolation does, however, when scaling large images down\n\t\t\t\t * to most sizes bigger than a thumbnail we witnessed noticeable\n\t\t\t\t * \"softening\" in the resultant image with BILINEAR that would\n\t\t\t\t * be unexpectedly annoying to a user expecting a \"QUALITY\"\n\t\t\t\t * scale of their original image. Instead BICUBIC was chosen to\n\t\t\t\t * honor the contract of a QUALITY scale of the original image.\n\t\t\t\t */\n result = scaleImageIncrementally(src, targetWidth,\n targetHeight, scalingMethod,\n RenderingHints.VALUE_INTERPOLATION_BICUBIC);\n }\n }\n\n if (DEBUG)\n log(0, \"Resized Image in %d ms\", System.currentTimeMillis() - t);\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Used to apply a {@link Rotation} and then <code>0</code> or more\n * {@link BufferedImageOp}s to a given image and return the result.\n * <p>\n * <strong>TIP</strong>: This operation leaves the original <code>src</code>\n * image unmodified. If the caller is done with the <code>src</code> image\n * after getting the result of this operation, remember to call\n * {@link BufferedImage#flush()} on the <code>src</code> to free up native\n * resources and make it easier for the GC to collect the unused image.\n *\n * @param src The image that will have the rotation applied to it.\n * @param rotation The rotation that will be applied to the image.\n * @param ops Zero or more optional image operations (e.g. sharpen, blur,\n * etc.) that can be applied to the final result before returning\n * the image.\n * @return a new {@link BufferedImage} representing <code>src</code> rotated\n * by the given amount and any optional ops applied to it.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n * @throws IllegalArgumentException if <code>rotation</code> is <code>null</code>.\n * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply.\n * These exceptions bubble up from the inside of most of the\n * {@link BufferedImageOp} implementations and are explicitly\n * defined on the imgscalr API to make it easier for callers to\n * catch the exception (if they are passing along optional ops\n * to be applied). imgscalr takes detailed steps to avoid the\n * most common pitfalls that will cause {@link BufferedImageOp}s\n * to fail, even when using straight forward JDK-image\n * operations.\n * @see Rotation\n */\n public static BufferedImage rotate(BufferedImage src, Rotation rotation,\n BufferedImageOp... ops) throws IllegalArgumentException,\n ImagingOpException {\n long t = -1;\n if (DEBUG)\n t = System.currentTimeMillis();\n\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n if (rotation == null)\n throw new IllegalArgumentException(\"rotation cannot be null\");\n\n if (DEBUG)\n log(0, \"Rotating Image [%s]...\", rotation);\n\n\t\t/*\n\t\t * Setup the default width/height values from our image.\n\t\t *\n\t\t * In the case of a 90 or 270 (-90) degree rotation, these two values\n\t\t * flip-flop and we will correct those cases down below in the switch\n\t\t * statement.\n\t\t */\n int newWidth = src.getWidth();\n int newHeight = src.getHeight();\n\n\t\t/*\n\t\t * We create a transform per operation request as (oddly enough) it ends\n\t\t * up being faster for the VM to create, use and destroy these instances\n\t\t * than it is to re-use a single AffineTransform per-thread via the\n\t\t * AffineTransform.setTo(...) methods which was my first choice (less\n\t\t * object creation); after benchmarking this explicit case and looking\n\t\t * at just how much code gets run inside of setTo() I opted for a new AT\n\t\t * for every rotation.\n\t\t *\n\t\t * Besides the performance win, trying to safely reuse AffineTransforms\n\t\t * via setTo(...) would have required ThreadLocal instances to avoid\n\t\t * race conditions where two or more resize threads are manipulating the\n\t\t * same transform before applying it.\n\t\t *\n\t\t * Misusing ThreadLocals are one of the #1 reasons for memory leaks in\n\t\t * server applications and since we have no nice way to hook into the\n\t\t * init/destroy Servlet cycle or any other initialization cycle for this\n\t\t * library to automatically call ThreadLocal.remove() to avoid the\n\t\t * memory leak, it would have made using this library *safely* on the\n\t\t * server side much harder.\n\t\t *\n\t\t * So we opt for creating individual transforms per rotation op and let\n\t\t * the VM clean them up in a GC. I only clarify all this reasoning here\n\t\t * for anyone else reading this code and being tempted to reuse the AT\n\t\t * instances of performance gains; there aren't any AND you get a lot of\n\t\t * pain along with it.\n\t\t */\n AffineTransform tx = new AffineTransform();\n\n switch (rotation) {\n case CW_90:\n\t\t\t/*\n\t\t\t * A 90 or -90 degree rotation will cause the height and width to\n\t\t\t * flip-flop from the original image to the rotated one.\n\t\t\t */\n newWidth = src.getHeight();\n newHeight = src.getWidth();\n\n // Reminder: newWidth == result.getHeight() at this point\n tx.translate(newWidth, 0);\n tx.quadrantRotate(1);\n\n break;\n\n case CW_270:\n\t\t\t/*\n\t\t\t * A 90 or -90 degree rotation will cause the height and width to\n\t\t\t * flip-flop from the original image to the rotated one.\n\t\t\t */\n newWidth = src.getHeight();\n newHeight = src.getWidth();\n\n // Reminder: newHeight == result.getWidth() at this point\n tx.translate(0, newHeight);\n tx.quadrantRotate(3);\n break;\n\n case CW_180:\n tx.translate(newWidth, newHeight);\n tx.quadrantRotate(2);\n break;\n\n case FLIP_HORZ:\n tx.translate(newWidth, 0);\n tx.scale(-1.0, 1.0);\n break;\n\n case FLIP_VERT:\n tx.translate(0, newHeight);\n tx.scale(1.0, -1.0);\n break;\n }\n\n // Create our target image we will render the rotated result to.\n BufferedImage result = createOptimalImage(src, newWidth, newHeight);\n Graphics2D g2d = result.createGraphics();\n\n\t\t/*\n\t\t * Render the resultant image to our new rotatedImage buffer, applying\n\t\t * the AffineTransform that we calculated above during rendering so the\n\t\t * pixels from the old position are transposed to the new positions in\n\t\t * the resulting image correctly.\n\t\t */\n g2d.drawImage(src, tx, null);\n g2d.dispose();\n\n if (DEBUG)\n log(0, \"Rotation Applied in %d ms, result [width=%d, height=%d]\",\n System.currentTimeMillis() - t, result.getWidth(),\n result.getHeight());\n\n // Apply any optional operations (if specified).\n if (ops != null && ops.length > 0)\n result = apply(result, ops);\n\n return result;\n }\n\n /**\n * Used to write out a useful and well-formatted log message by any piece of\n * code inside of the imgscalr library.\n * <p>\n * If a message cannot be logged (logging is disabled) then this method\n * returns immediately.\n * <p>\n * <strong>NOTE</strong>: Because Java will auto-box primitive arguments\n * into Objects when building out the <code>params</code> array, care should\n * be taken not to call this method with primitive values unless\n * {@link Scalr#DEBUG} is <code>true</code>; otherwise the VM will be\n * spending time performing unnecessary auto-boxing calculations.\n *\n * @param depth The indentation level of the log message.\n * @param message The log message in <a href=\n * \"http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax\"\n * >format string syntax</a> that will be logged.\n * @param params The parameters that will be swapped into all the place holders\n * in the original messages before being logged.\n * @see Scalr#LOG_PREFIX\n * @see Scalr#LOG_PREFIX_PROPERTY_NAME\n */\n protected static void log(int depth, String message, Object... params) {\n if (Scalr.DEBUG) {\n System.out.print(Scalr.LOG_PREFIX);\n\n for (int i = 0; i < depth; i++)\n System.out.print(\"\\t\");\n\n System.out.printf(message, params);\n System.out.println();\n }\n }\n\n /**\n * Used to create a {@link BufferedImage} with the most optimal RGB TYPE (\n * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}\n * ) capable of being rendered into from the given <code>src</code>. The\n * width and height of both images will be identical.\n * <p>\n * This does not perform a copy of the image data from <code>src</code> into\n * the result image; see {@link #copyToOptimalImage(BufferedImage)} for\n * that.\n * <p>\n * We force all rendering results into one of these two types, avoiding the\n * case where a source image is of an unsupported (or poorly supported)\n * format by Java2D causing the rendering result to end up looking terrible\n * (common with GIFs) or be totally corrupt (e.g. solid black image).\n * <p>\n * Originally reported by Magnus Kvalheim from Movellas when scaling certain\n * GIF and PNG images.\n *\n * @param src The source image that will be analyzed to determine the most\n * optimal image type it can be rendered into.\n * @return a new {@link BufferedImage} representing the most optimal target\n * image type that <code>src</code> can be rendered into.\n * @see <a\n * href=\"http://www.mail-archive.com/[email protected]/msg05621.html\">How\n * Java2D handles poorly supported image types</a>\n * @see <a\n * href=\"http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java\">Thanks\n * to Morten Nobel for implementation hint</a>\n */\n protected static BufferedImage createOptimalImage(BufferedImage src) {\n return createOptimalImage(src, src.getWidth(), src.getHeight());\n }\n\n /**\n * Used to create a {@link BufferedImage} with the given dimensions and the\n * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or\n * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from\n * the given <code>src</code>.\n * <p>\n * This does not perform a copy of the image data from <code>src</code> into\n * the result image; see {@link #copyToOptimalImage(BufferedImage)} for\n * that.\n * <p>\n * We force all rendering results into one of these two types, avoiding the\n * case where a source image is of an unsupported (or poorly supported)\n * format by Java2D causing the rendering result to end up looking terrible\n * (common with GIFs) or be totally corrupt (e.g. solid black image).\n * <p>\n * Originally reported by Magnus Kvalheim from Movellas when scaling certain\n * GIF and PNG images.\n *\n * @param src The source image that will be analyzed to determine the most\n * optimal image type it can be rendered into.\n * @param width The width of the newly created resulting image.\n * @param height The height of the newly created resulting image.\n * @return a new {@link BufferedImage} representing the most optimal target\n * image type that <code>src</code> can be rendered into.\n * @throws IllegalArgumentException if <code>width</code> or <code>height</code> are &lt; 0.\n * @see <a\n * href=\"http://www.mail-archive.com/[email protected]/msg05621.html\">How\n * Java2D handles poorly supported image types</a>\n * @see <a\n * href=\"http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java\">Thanks\n * to Morten Nobel for implementation hint</a>\n */\n protected static BufferedImage createOptimalImage(BufferedImage src,\n int width, int height) throws IllegalArgumentException {\n if (width < 0 || height < 0)\n throw new IllegalArgumentException(\"width [\" + width\n + \"] and height [\" + height + \"] must be >= 0\");\n\n return new BufferedImage(\n width,\n height,\n (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB\n : BufferedImage.TYPE_INT_ARGB)\n );\n }\n\n /**\n * Used to copy a {@link BufferedImage} from a non-optimal type into a new\n * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If\n * <code>src</code> is already of an optimal type, then it is returned\n * unmodified.\n * <p>\n * This method is meant to be used by any calling code (imgscalr's or\n * otherwise) to convert any inbound image from a poorly supported image\n * type into the 2 most well-supported image types in Java2D (\n * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}\n * ) in order to ensure all subsequent graphics operations are performed as\n * efficiently and correctly as possible.\n * <p>\n * When using Java2D to work with image types that are not well supported,\n * the results can be anything from exceptions bubbling up from the depths\n * of Java2D to images being completely corrupted and just returned as solid\n * black.\n *\n * @param src The image to copy (if necessary) into an optimally typed\n * {@link BufferedImage}.\n * @return a representation of the <code>src</code> image in an optimally\n * typed {@link BufferedImage}, otherwise <code>src</code> if it was\n * already of an optimal type.\n * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.\n */\n protected static BufferedImage copyToOptimalImage(BufferedImage src)\n throws IllegalArgumentException {\n if (src == null)\n throw new IllegalArgumentException(\"src cannot be null\");\n\n // Calculate the type depending on the presence of alpha.\n int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB\n : BufferedImage.TYPE_INT_ARGB);\n BufferedImage result = new BufferedImage(src.getWidth(),\n src.getHeight(), type);\n\n // Render the src image into our new optimal source.\n Graphics g = result.getGraphics();\n g.drawImage(src, 0, 0, null);\n g.dispose();\n\n return result;\n }\n\n /**\n * Used to determine the scaling {@link Method} that is best suited for\n * scaling the image to the targeted dimensions.\n * <p>\n * This method is intended to be used to select a specific scaling\n * {@link Method} when a {@link Method#AUTOMATIC} method is specified. This\n * method utilizes the {@link Scalr#THRESHOLD_QUALITY_BALANCED} and\n * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds when selecting which\n * method should be used by comparing the primary dimension (width or\n * height) against the threshold and seeing where the image falls. The\n * primary dimension is determined by looking at the orientation of the\n * image: landscape or square images use their width and portrait-oriented\n * images use their height.\n *\n * @param targetWidth The target width for the scaled image.\n * @param targetHeight The target height for the scaled image.\n * @param ratio A height/width ratio used to determine the orientation of the\n * image so the primary dimension (width or height) can be\n * selected to test if it is greater than or less than a\n * particular threshold.\n * @return the fastest {@link Method} suited for scaling the image to the\n * specified dimensions while maintaining a good-looking result.\n */\n protected static Method determineScalingMethod(int targetWidth,\n int targetHeight, float ratio) {\n // Get the primary dimension based on the orientation of the image\n int length = (ratio <= 1 ? targetWidth : targetHeight);\n\n // Default to speed\n Method result = Method.SPEED;\n\n // Figure out which scalingMethod should be used\n if (length <= Scalr.THRESHOLD_QUALITY_BALANCED)\n result = Method.QUALITY;\n else if (length <= Scalr.THRESHOLD_BALANCED_SPEED)\n result = Method.BALANCED;\n\n if (DEBUG)\n log(2, \"AUTOMATIC scaling method selected: %s\", result.name());\n\n return result;\n }\n\n /**\n * Used to implement a straight-forward image-scaling operation using Java\n * 2D.\n * <p>\n * This method uses the Oracle-encouraged method of\n * <code>Graphics2D.drawImage(...)</code> to scale the given image with the\n * given interpolation hint.\n *\n * @param src The image that will be scaled.\n * @param targetWidth The target width for the scaled image.\n * @param targetHeight The target height for the scaled image.\n * @param interpolationHintValue The {@link RenderingHints} interpolation value used to\n * indicate the method that {@link Graphics2D} should use when\n * scaling the image.\n * @return the result of scaling the original <code>src</code> to the given\n * dimensions using the given interpolation method.\n */\n protected static BufferedImage scaleImage(BufferedImage src,\n int targetWidth, int targetHeight, Object interpolationHintValue) {\n // Setup the rendering resources to match the source image's\n BufferedImage result = createOptimalImage(src, targetWidth,\n targetHeight);\n Graphics2D resultGraphics = result.createGraphics();\n\n // Scale the image to the new buffer using the specified rendering hint.\n resultGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,\n interpolationHintValue);\n resultGraphics.drawImage(src, 0, 0, targetWidth, targetHeight, null);\n\n // Just to be clean, explicitly dispose our temporary graphics object\n resultGraphics.dispose();\n\n // Return the scaled image to the caller.\n return result;\n }\n\n /**\n * Used to implement Chris Campbell's incremental-scaling algorithm: <a\n * href=\"http://today.java.net/pub/a/today/2007/04/03/perils\n * -of-image-getscaledinstance\n * .html\">http://today.java.net/pub/a/today/2007/04/03/perils\n * -of-image-getscaledinstance.html</a>.\n * <p>\n * Modifications to the original algorithm are variable names and comments\n * added for clarity and the hard-coding of using BICUBIC interpolation as\n * well as the explicit \"flush()\" operation on the interim BufferedImage\n * instances to avoid image leaking.\n *\n * @param src The image that will be scaled.\n * @param targetWidth The target width for the scaled image.\n * @param targetHeight The target height for the scaled image.\n * @param scalingMethod The scaling method specified by the user (or calculated by\n * imgscalr) to use for this incremental scaling operation.\n * @param interpolationHintValue The {@link RenderingHints} interpolation value used to\n * indicate the method that {@link Graphics2D} should use when\n * scaling the image.\n * @return an image scaled to the given dimensions using the given rendering\n * hint.\n */\n protected static BufferedImage scaleImageIncrementally(BufferedImage src,\n int targetWidth, int targetHeight, Method scalingMethod,\n Object interpolationHintValue) {\n boolean hasReassignedSrc = false;\n int incrementCount = 0;\n int currentWidth = src.getWidth();\n int currentHeight = src.getHeight();\n\n\t\t/*\n\t\t * The original QUALITY mode, representing Chris Campbell's algorithm,\n\t\t * is to step down by 1/2s every time when scaling the image\n\t\t * incrementally. Users pointed out that using this method to scale\n\t\t * images with noticeable straight lines left them really jagged in\n\t\t * smaller thumbnail format.\n\t\t *\n\t\t * After investigation it was discovered that scaling incrementally by\n\t\t * smaller increments was the ONLY way to make the thumbnail sized\n\t\t * images look less jagged and more accurate; almost matching the\n\t\t * accuracy of Mac's built in thumbnail generation which is the highest\n\t\t * quality resize I've come across (better than GIMP Lanczos3 and\n\t\t * Windows 7).\n\t\t *\n\t\t * A divisor of 7 was chose as using 5 still left some jaggedness in the\n\t\t * image while a divisor of 8 or higher made the resulting thumbnail too\n\t\t * soft; like our OP_ANTIALIAS convolve op had been forcibly applied to\n\t\t * the result even if the user didn't want it that soft.\n\t\t *\n\t\t * Using a divisor of 7 for the ULTRA_QUALITY seemed to be the sweet\n\t\t * spot.\n\t\t *\n\t\t * NOTE: Below when the actual fraction is used to calculate the small\n\t\t * portion to subtract from the current dimension, this is a\n\t\t * progressively smaller and smaller chunk. When the code was changed to\n\t\t * do a linear reduction of the image of equal steps for each\n\t\t * incremental resize (e.g. say 50px each time) the result was\n\t\t * significantly worse than the progressive approach used below; even\n\t\t * when a very high number of incremental steps (13) was tested.\n\t\t */\n int fraction = (scalingMethod == Method.ULTRA_QUALITY ? 7 : 2);\n\n do {\n int prevCurrentWidth = currentWidth;\n int prevCurrentHeight = currentHeight;\n\n\t\t\t/*\n\t\t\t * If the current width is bigger than our target, cut it in half\n\t\t\t * and sample again.\n\t\t\t */\n if (currentWidth > targetWidth) {\n currentWidth -= (currentWidth / fraction);\n\n\t\t\t\t/*\n\t\t\t\t * If we cut the width too far it means we are on our last\n\t\t\t\t * iteration. Just set it to the target width and finish up.\n\t\t\t\t */\n if (currentWidth < targetWidth)\n currentWidth = targetWidth;\n }\n\n\t\t\t/*\n\t\t\t * If the current height is bigger than our target, cut it in half\n\t\t\t * and sample again.\n\t\t\t */\n\n if (currentHeight > targetHeight) {\n currentHeight -= (currentHeight / fraction);\n\n\t\t\t\t/*\n\t\t\t\t * If we cut the height too far it means we are on our last\n\t\t\t\t * iteration. Just set it to the target height and finish up.\n\t\t\t\t */\n\n if (currentHeight < targetHeight)\n currentHeight = targetHeight;\n }\n\n\t\t\t/*\n\t\t\t * Stop when we cannot incrementally step down anymore.\n\t\t\t *\n\t\t\t * This used to use a || condition, but that would cause problems\n\t\t\t * when using FIT_EXACT such that sometimes the width OR height\n\t\t\t * would not change between iterations, but the other dimension\n\t\t\t * would (e.g. resizing 500x500 to 500x250).\n\t\t\t *\n\t\t\t * Now changing this to an && condition requires that both\n\t\t\t * dimensions do not change between a resize iteration before we\n\t\t\t * consider ourselves done.\n\t\t\t */\n if (prevCurrentWidth == currentWidth\n && prevCurrentHeight == currentHeight)\n break;\n\n if (DEBUG)\n log(2, \"Scaling from [%d x %d] to [%d x %d]\", prevCurrentWidth,\n prevCurrentHeight, currentWidth, currentHeight);\n\n // Render the incremental scaled image.\n BufferedImage incrementalImage = scaleImage(src, currentWidth,\n currentHeight, interpolationHintValue);\n\n\t\t\t/*\n\t\t\t * Before re-assigning our interim (partially scaled)\n\t\t\t * incrementalImage to be the new src image before we iterate around\n\t\t\t * again to process it down further, we want to flush() the previous\n\t\t\t * src image IF (and only IF) it was one of our own temporary\n\t\t\t * BufferedImages created during this incremental down-sampling\n\t\t\t * cycle. If it wasn't one of ours, then it was the original\n\t\t\t * caller-supplied BufferedImage in which case we don't want to\n\t\t\t * flush() it and just leave it alone.\n\t\t\t */\n if (hasReassignedSrc)\n src.flush();\n\n\t\t\t/*\n\t\t\t * Now treat our incremental partially scaled image as the src image\n\t\t\t * and cycle through our loop again to do another incremental\n\t\t\t * scaling of it (if necessary).\n\t\t\t */\n src = incrementalImage;\n\n\t\t\t/*\n\t\t\t * Keep track of us re-assigning the original caller-supplied source\n\t\t\t * image with one of our interim BufferedImages so we know when to\n\t\t\t * explicitly flush the interim \"src\" on the next cycle through.\n\t\t\t */\n hasReassignedSrc = true;\n\n // Track how many times we go through this cycle to scale the image.\n incrementCount++;\n } while (currentWidth != targetWidth || currentHeight != targetHeight);\n\n if (DEBUG)\n log(2, \"Incrementally Scaled Image in %d steps.\", incrementCount);\n\n\t\t/*\n\t\t * Once the loop has exited, the src image argument is now our scaled\n\t\t * result image that we want to return.\n\t\t */\n return src;\n }\n}", "public class AnimatedGifEncoder\n{\n\n protected int width; // image size\n\n protected int height;\n\n protected Color transparent = null; // transparent color if given\n\n protected int transIndex; // transparent index in color table\n\n protected int repeat = -1; // no repeat\n\n protected int delay = 0; // frame delay (hundredths)\n\n protected boolean started = false; // ready to output frames\n\n protected OutputStream out;\n\n protected BufferedImage image; // current frame\n\n protected byte[] pixels; // BGR byte array from frame\n\n protected byte[] indexedPixels; // converted frame indexed to palette\n\n protected int colorDepth; // number of bit planes\n\n protected byte[] colorTab; // RGB palette\n\n protected boolean[] usedEntry = new boolean[256]; // active palette entries\n\n protected int palSize = 7; // color table size (bits-1)\n\n protected int dispose = -1; // disposal code (-1 = use default)\n\n protected boolean closeStream = false; // close stream when finished\n\n protected boolean firstFrame = true;\n\n protected boolean sizeSet = false; // if false, get size from first frame\n\n protected int sample = 10; // default sample interval for quantizer\n\n /**\n * Sets the delay time between each frame, or changes it for subsequent frames\n * (applies to last frame added).\n *\n * @param ms int delay time in milliseconds\n */\n public void setDelay(int ms)\n {\n delay = Math.round(ms / 10.0f);\n }\n\n /**\n * Sets the GIF frame disposal code for the last added frame and any\n * subsequent frames. Default is 0 if no transparent color has been set,\n * otherwise 2.\n *\n * @param code int disposal code.\n */\n public void setDispose(int code)\n {\n if (code >= 0)\n {\n dispose = code;\n }\n }\n\n /**\n * Sets the number of times the set of GIF frames should be played. Default is\n * 1; 0 means play indefinitely. Must be invoked before the first image is\n * added.\n *\n * @param iter int number of iterations.\n * @return\n */\n public void setRepeat(int iter)\n {\n if (iter >= 0)\n {\n repeat = iter;\n }\n }\n\n /**\n * Sets the transparent color for the last added frame and any subsequent\n * frames. Since all colors are subject to modification in the quantization\n * process, the color in the final palette for each frame closest to the given\n * color becomes the transparent color for that frame. May be set to null to\n * indicate no transparent color.\n *\n * @param c Color to be treated as transparent on display.\n */\n public void setTransparent(Color c)\n {\n transparent = c;\n }\n\n /**\n * Adds next GIF frame. The frame is not written immediately, but is actually\n * deferred until the next frame is received so that timing data can be\n * inserted. Invoking <code>finish()</code> flushes all frames. If\n * <code>setSize</code> was not invoked, the size of the first image is used\n * for all subsequent frames.\n *\n * @param im BufferedImage containing frame to write.\n * @return true if successful.\n */\n public boolean addFrame(BufferedImage im)\n {\n if ((im == null) || !started)\n {\n return false;\n }\n boolean ok = true;\n try\n {\n if (!sizeSet)\n {\n // use first frame's size\n setSize(im.getWidth(), im.getHeight());\n }\n image = im;\n getImagePixels(); // convert to correct format if necessary\n analyzePixels(); // build color table & map pixels\n if (firstFrame)\n {\n writeLSD(); // logical screen descriptior\n writePalette(); // global color table\n if (repeat >= 0)\n {\n // use NS app extension to indicate reps\n writeNetscapeExt();\n }\n }\n writeGraphicCtrlExt(); // write graphic control extension\n writeImageDesc(); // image descriptor\n if (!firstFrame)\n {\n writePalette(); // local color table\n }\n writePixels(); // encode and write pixel data\n firstFrame = false;\n } catch (IOException e)\n {\n ok = false;\n }\n\n return ok;\n }\n\n /**\n * Flushes any pending data and closes output file. If writing to an\n * OutputStream, the stream is not closed.\n */\n public boolean finish()\n {\n if (!started)\n return false;\n boolean ok = true;\n started = false;\n try\n {\n out.write(0x3b); // gif trailer\n out.flush();\n if (closeStream)\n {\n out.close();\n }\n } catch (IOException e)\n {\n ok = false;\n }\n\n // reset for subsequent use\n transIndex = 0;\n out = null;\n image = null;\n pixels = null;\n indexedPixels = null;\n colorTab = null;\n closeStream = false;\n firstFrame = true;\n\n return ok;\n }\n\n /**\n * Sets frame rate in frames per second. Equivalent to\n * <code>setDelay(1000/fps)</code>.\n *\n * @param fps float frame rate (frames per second)\n */\n public void setFrameRate(float fps)\n {\n if (fps != 0f)\n {\n delay = Math.round(100f / fps);\n }\n }\n\n /**\n * Sets quality of color quantization (conversion of images to the maximum 256\n * colors allowed by the GIF specification). Lower values (minimum = 1)\n * produce better colors, but slow processing significantly. 10 is the\n * default, and produces good color mapping at reasonable speeds. Values\n * greater than 20 do not yield significant improvements in speed.\n *\n * @param quality int greater than 0.\n * @return\n */\n public void setQuality(int quality)\n {\n if (quality < 1)\n quality = 1;\n sample = quality;\n }\n\n /**\n * Sets the GIF frame size. The default size is the size of the first frame\n * added if this method is not invoked.\n *\n * @param w int frame width.\n * @param h int frame width.\n */\n public void setSize(int w, int h)\n {\n if (started && !firstFrame)\n return;\n width = w;\n height = h;\n if (width < 1)\n width = 320;\n if (height < 1)\n height = 240;\n sizeSet = true;\n }\n\n /**\n * Initiates GIF file creation on the given stream. The stream is not closed\n * automatically.\n *\n * @param os OutputStream on which GIF images are written.\n * @return false if initial write failed.\n */\n public boolean start(OutputStream os)\n {\n if (os == null)\n return false;\n boolean ok = true;\n closeStream = false;\n out = os;\n try\n {\n writeString(\"GIF89a\"); // header\n } catch (IOException e)\n {\n ok = false;\n }\n return started = ok;\n }\n\n /**\n * Initiates writing of a GIF file with the specified name.\n *\n * @param file String containing output file name.\n * @return false if open or initial write failed.\n */\n public boolean start(String file)\n {\n boolean ok = true;\n try\n {\n out = new BufferedOutputStream(new FileOutputStream(file));\n ok = start(out);\n closeStream = true;\n } catch (IOException e)\n {\n ok = false;\n }\n return started = ok;\n }\n\n /**\n * Analyzes image colors and creates color map.\n */\n protected void analyzePixels()\n {\n int len = pixels.length;\n int nPix = len / 3;\n indexedPixels = new byte[nPix];\n NeuQuant nq = new NeuQuant(pixels, len, sample);\n // initialize quantizer\n colorTab = nq.process(); // create reduced palette\n // convert map from BGR to RGB\n for (int i = 0; i < colorTab.length; i += 3)\n {\n byte temp = colorTab[i];\n colorTab[i] = colorTab[i + 2];\n colorTab[i + 2] = temp;\n usedEntry[i / 3] = false;\n }\n // map image pixels to new palette\n int k = 0;\n for (int i = 0; i < nPix; i++)\n {\n int index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff);\n usedEntry[index] = true;\n indexedPixels[i] = (byte) index;\n }\n pixels = null;\n colorDepth = 8;\n palSize = 7;\n // get closest match to transparent color if specified\n if (transparent != null)\n {\n transIndex = findClosest(transparent);\n }\n }\n\n /**\n * Returns index of palette color closest to c\n */\n protected int findClosest(Color c)\n {\n if (colorTab == null)\n return -1;\n int r = c.getRed();\n int g = c.getGreen();\n int b = c.getBlue();\n int minpos = 0;\n int dmin = 256 * 256 * 256;\n int len = colorTab.length;\n for (int i = 0; i < len; )\n {\n int dr = r - (colorTab[i++] & 0xff);\n int dg = g - (colorTab[i++] & 0xff);\n int db = b - (colorTab[i] & 0xff);\n int d = dr * dr + dg * dg + db * db;\n int index = i / 3;\n if (usedEntry[index] && (d < dmin))\n {\n dmin = d;\n minpos = index;\n }\n i++;\n }\n return minpos;\n }\n\n /**\n * Extracts image pixels into byte array \"pixels\"\n */\n protected void getImagePixels()\n {\n int w = image.getWidth();\n int h = image.getHeight();\n int type = image.getType();\n if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR))\n {\n // create new image with right size/format\n BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);\n Graphics2D g = temp.createGraphics();\n g.drawImage(image, 0, 0, null);\n image = temp;\n }\n pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();\n }\n\n /**\n * Writes Graphic Control Extension\n */\n protected void writeGraphicCtrlExt() throws IOException\n {\n out.write(0x21); // extension introducer\n out.write(0xf9); // GCE label\n out.write(4); // data block size\n int transp, disp;\n if (transparent == null)\n {\n transp = 0;\n disp = 0; // dispose = no action\n } else\n {\n transp = 1;\n disp = 2; // force clear if using transparent color\n }\n if (dispose >= 0)\n {\n disp = dispose & 7; // user override\n }\n disp <<= 2;\n\n // packed fields\n out.write(0 | // 1:3 reserved\n disp | // 4:6 disposal\n 0 | // 7 user input - 0 = none\n transp); // 8 transparency flag\n\n writeShort(delay); // delay x 1/100 sec\n out.write(transIndex); // transparent color index\n out.write(0); // block terminator\n }\n\n /**\n * Writes Image Descriptor\n */\n protected void writeImageDesc() throws IOException\n {\n out.write(0x2c); // image separator\n writeShort(0); // image position x,y = 0,0\n writeShort(0);\n writeShort(width); // image size\n writeShort(height);\n // packed fields\n if (firstFrame)\n {\n // no LCT - GCT is used for first (or only) frame\n out.write(0);\n } else\n {\n // specify normal LCT\n out.write(0x80 | // 1 local color table 1=yes\n 0 | // 2 interlace - 0=no\n 0 | // 3 sorted - 0=no\n 0 | // 4-5 reserved\n palSize); // 6-8 size of color table\n }\n }\n\n /**\n * Writes Logical Screen Descriptor\n */\n protected void writeLSD() throws IOException\n {\n // logical screen size\n writeShort(width);\n writeShort(height);\n // packed fields\n out.write((0x80 | // 1 : global color table flag = 1 (gct used)\n 0x70 | // 2-4 : color resolution = 7\n 0x00 | // 5 : gct sort flag = 0\n palSize)); // 6-8 : gct size\n\n out.write(0); // background color index\n out.write(0); // pixel aspect ratio - assume 1:1\n }\n\n /**\n * Writes Netscape application extension to define repeat count.\n */\n protected void writeNetscapeExt() throws IOException\n {\n out.write(0x21); // extension introducer\n out.write(0xff); // app extension label\n out.write(11); // block size\n writeString(\"NETSCAPE\" + \"2.0\"); // app id + auth code\n out.write(3); // sub-block size\n out.write(1); // loop sub-block id\n writeShort(repeat); // loop count (extra iterations, 0=repeat forever)\n out.write(0); // block terminator\n }\n\n /**\n * Writes color table\n */\n protected void writePalette() throws IOException\n {\n out.write(colorTab, 0, colorTab.length);\n int n = (3 * 256) - colorTab.length;\n for (int i = 0; i < n; i++)\n {\n out.write(0);\n }\n }\n\n /**\n * Encodes and writes pixel data\n */\n protected void writePixels() throws IOException\n {\n LZWEncoder encoder = new LZWEncoder(width, height, indexedPixels, colorDepth);\n encoder.encode(out);\n }\n\n /**\n * Write 16-bit value to output stream, LSB first\n */\n protected void writeShort(int value) throws IOException\n {\n out.write(value & 0xff);\n out.write((value >> 8) & 0xff);\n }\n\n /**\n * Writes string to output stream\n */\n protected void writeString(String s) throws IOException\n {\n for (int i = 0; i < s.length(); i++)\n {\n out.write((byte) s.charAt(i));\n }\n }\n}", "public class GifDecoder\n{\n\n /**\n * File read status: No errors.\n */\n public static final int STATUS_OK = 0;\n /**\n * File read status: Error decoding file (may be partially decoded)\n */\n public static final int STATUS_FORMAT_ERROR = 1;\n /**\n * File read status: Unable to open source.\n */\n public static final int STATUS_OPEN_ERROR = 2;\n protected BufferedInputStream in;\n protected int status;\n protected int width; // full image width\n\n protected int height; // full image height\n\n protected boolean gctFlag; // global color table used\n\n protected int gctSize; // size of global color table\n\n protected int loopCount = 1; // iterations; 0 = repeat forever\n\n protected int[] gct; // global color table\n\n protected int[] lct; // local color table\n\n protected int[] act; // active color table\n\n protected int bgIndex; // background color index\n\n protected int bgColor; // background color\n\n protected int lastBgColor; // previous bg color\n\n protected int pixelAspect; // pixel aspect ratio\n\n protected boolean lctFlag; // local color table flag\n\n protected boolean interlace; // interlace flag\n\n protected int lctSize; // local color table size\n\n protected int ix, iy, iw, ih; // current image rectangle\n\n protected Rectangle lastRect; // last image rect\n\n protected BufferedImage image; // current frame\n\n protected BufferedImage lastImage; // previous frame\n\n protected byte[] block = new byte[256]; // current data block\n\n protected int blockSize = 0; // block size\n\n // last graphic control extension info\n protected int dispose = 0;\n // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev\n protected int lastDispose = 0;\n protected boolean transparency = false; // use transparent color\n\n protected int delay = 0; // delay in milliseconds\n\n protected int transIndex; // transparent color index\n\n protected static final int MaxStackSize = 4096;\n // max decoder pixel stack size\n\n // LZW decoder working arrays\n protected short[] prefix;\n protected byte[] suffix;\n protected byte[] pixelStack;\n protected byte[] pixels;\n protected ArrayList<GifFrame> frames; // frames read from current file\n\n protected int frameCount;\n\n static class GifFrame\n {\n\n public GifFrame(BufferedImage im, int del)\n {\n image = im;\n delay = del;\n }\n\n public BufferedImage image;\n public int delay;\n }\n\n /**\n * Gets display duration for specified frame.\n *\n * @param n int index of frame\n * @return delay in milliseconds\n */\n public int getDelay(int n)\n {\n //\n delay = -1;\n if ((n >= 0) && (n < frameCount))\n {\n delay = frames.get(n).delay;\n }\n return delay;\n }\n\n /**\n * Gets the number of frames read from file.\n *\n * @return frame count\n */\n public int getFrameCount()\n {\n return frameCount;\n }\n\n /**\n * Gets the first (or only) image read.\n *\n * @return BufferedImage containing first frame, or null if none.\n */\n public BufferedImage getImage()\n {\n return getFrame(0);\n }\n\n /**\n * Gets the \"Netscape\" iteration count, if any.\n * A count of 0 means repeat indefinitiely.\n *\n * @return iteration count if one was specified, else 1.\n */\n public int getLoopCount()\n {\n return loopCount;\n }\n\n /**\n * Creates new frame image from current data (and previous\n * frames as specified by their disposition codes).\n */\n protected void setPixels()\n {\n // expose destination image's pixels as int array\n int[] dest =\n ((DataBufferInt) image.getRaster().getDataBuffer()).getData();\n\n // fill in starting image contents based on last image's dispose code\n if (lastDispose > 0)\n {\n if (lastDispose == 3)\n {\n // use image before last\n int n = frameCount - 2;\n if (n > 0)\n {\n lastImage = getFrame(n - 1);\n } else\n {\n lastImage = null;\n }\n }\n\n if (lastImage != null)\n {\n int[] prev =\n ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();\n System.arraycopy(prev, 0, dest, 0, width * height);\n // copy pixels\n\n if (lastDispose == 2)\n {\n // fill last image rect area with background color\n Graphics2D g = image.createGraphics();\n Color c = null;\n if (transparency)\n {\n c = new Color(0, 0, 0, 0); // assume background is transparent\n\n } else\n {\n c = new Color(lastBgColor); // use given background color\n\n }\n g.setColor(c);\n g.setComposite(AlphaComposite.Src); // replace area\n\n g.fill(lastRect);\n g.dispose();\n }\n }\n }\n\n // copy each source line to the appropriate place in the destination\n int pass = 1;\n int inc = 8;\n int iline = 0;\n for (int i = 0; i < ih; i++)\n {\n int line = i;\n if (interlace)\n {\n if (iline >= ih)\n {\n pass++;\n switch (pass)\n {\n case 2:\n iline = 4;\n break;\n case 3:\n iline = 2;\n inc = 4;\n break;\n case 4:\n iline = 1;\n inc = 2;\n }\n }\n line = iline;\n iline += inc;\n }\n line += iy;\n if (line < height)\n {\n int k = line * width;\n int dx = k + ix; // start of line in dest\n\n int dlim = dx + iw; // end of dest line\n\n if ((k + width) < dlim)\n {\n dlim = k + width; // past dest edge\n\n }\n int sx = i * iw; // start of line in source\n\n while (dx < dlim)\n {\n // map color and insert in destination\n int index = ((int) pixels[sx++]) & 0xff;\n int c = act[index];\n if (c != 0)\n {\n dest[dx] = c;\n }\n dx++;\n }\n }\n }\n }\n\n /**\n * Gets the image contents of frame n.\n *\n * @return BufferedImage representation of frame, or null if n is invalid.\n */\n public BufferedImage getFrame(int n)\n {\n BufferedImage im = null;\n if ((n >= 0) && (n < frameCount))\n {\n im = frames.get(n).image;\n }\n return im;\n }\n\n /**\n * Gets image size.\n *\n * @return GIF image dimensions\n */\n public Dimension getFrameSize()\n {\n return new Dimension(width, height);\n }\n\n /**\n * Reads GIF image from stream\n *\n * @param is BufferedInputStream containing GIF file.\n * @return read status code (0 = no errors)\n */\n public int read(BufferedInputStream is)\n {\n init();\n if (is == null) return STATUS_OPEN_ERROR;\n\n try (BufferedInputStream bis = is)\n {\n in = bis;\n readHeader();\n if (!err())\n {\n readContents();\n if (frameCount < 0)\n {\n status = STATUS_FORMAT_ERROR;\n }\n }\n } catch (Exception e)\n {\n status = STATUS_OPEN_ERROR;\n }\n return status;\n }\n\n /**\n * Reads GIF image from stream\n *\n * @param is InputStream containing GIF file.\n * @return read status code (0 = no errors)\n */\n public int read(InputStream is)\n {\n init();\n\n if (is == null) return STATUS_OPEN_ERROR;\n\n try (BufferedInputStream bis = (is instanceof BufferedInputStream) ? (BufferedInputStream) is : new BufferedInputStream(is))\n {\n in = bis;\n readHeader();\n if (!err())\n {\n readContents();\n if (frameCount < 0)\n {\n status = STATUS_FORMAT_ERROR;\n }\n }\n } catch (Exception e)\n {\n status = STATUS_OPEN_ERROR;\n }\n\n return status;\n }\n\n /**\n * Reads GIF file from specified file/URL source\n * (URL assumed if name contains \":/\" or \"file:\")\n *\n * @param name String containing source\n * @return read status code (0 = no errors)\n */\n public int read(String name)\n {\n status = STATUS_OK;\n try\n {\n name = name.trim().toLowerCase();\n if (name.contains(\"file:\") || (name.indexOf(\":/\") > 0))\n {\n URL url = new URL(name);\n in = new BufferedInputStream(url.openStream());\n } else\n {\n in = new BufferedInputStream(new FileInputStream(name));\n }\n status = read(in);\n } catch (IOException e)\n {\n status = STATUS_OPEN_ERROR;\n }\n\n return status;\n }\n\n /**\n * Decodes LZW image data into pixel array.\n * Adapted from John Cristy's ImageMagick.\n */\n protected void decodeImageData()\n {\n int NullCode = -1;\n int npix = iw * ih;\n int available,\n clear,\n code_mask,\n code_size,\n end_of_information,\n in_code,\n old_code,\n bits,\n code,\n count,\n i,\n datum,\n data_size,\n first,\n top,\n bi,\n pi;\n\n if ((pixels == null) || (pixels.length < npix))\n {\n pixels = new byte[npix]; // allocate new pixel array\n\n }\n if (prefix == null)\n {\n prefix = new short[MaxStackSize];\n }\n if (suffix == null)\n {\n suffix = new byte[MaxStackSize];\n }\n if (pixelStack == null)\n {\n pixelStack = new byte[MaxStackSize + 1];\n\n // Initialize GIF data stream decoder.\n }\n data_size = read();\n clear = 1 << data_size;\n end_of_information = clear + 1;\n available = clear + 2;\n old_code = NullCode;\n code_size = data_size + 1;\n code_mask = (1 << code_size) - 1;\n for (code = 0; code < clear; code++)\n {\n prefix[code] = 0;\n suffix[code] = (byte) code;\n }\n\n // Decode GIF pixel stream.\n\n datum = bits = count = first = top = pi = bi = 0;\n\n for (i = 0; i < npix; )\n {\n if (top == 0)\n {\n if (bits < code_size)\n {\n // Load bytes until there are enough bits for a code.\n if (count == 0)\n {\n // Read a new data block.\n count = readBlock();\n if (count <= 0)\n {\n break;\n }\n bi = 0;\n }\n datum += (((int) block[bi]) & 0xff) << bits;\n bits += 8;\n bi++;\n count--;\n continue;\n }\n\n // Get the next code.\n\n code = datum & code_mask;\n datum >>= code_size;\n bits -= code_size;\n\n // Interpret the code\n\n if ((code > available) || (code == end_of_information))\n {\n break;\n }\n if (code == clear)\n {\n // Reset decoder.\n code_size = data_size + 1;\n code_mask = (1 << code_size) - 1;\n available = clear + 2;\n old_code = NullCode;\n continue;\n }\n if (old_code == NullCode)\n {\n pixelStack[top++] = suffix[code];\n old_code = code;\n first = code;\n continue;\n }\n in_code = code;\n if (code == available)\n {\n pixelStack[top++] = (byte) first;\n code = old_code;\n }\n while (code > clear)\n {\n pixelStack[top++] = suffix[code];\n code = prefix[code];\n }\n first = ((int) suffix[code]) & 0xff;\n\n // Add a new string to the string table,\n\n if (available >= MaxStackSize)\n {\n break;\n }\n pixelStack[top++] = (byte) first;\n prefix[available] = (short) old_code;\n suffix[available] = (byte) first;\n available++;\n if (((available & code_mask) == 0) && (available < MaxStackSize))\n {\n code_size++;\n code_mask += available;\n }\n old_code = in_code;\n }\n\n // Pop a pixel off the pixel stack.\n\n top--;\n pixels[pi++] = pixelStack[top];\n i++;\n }\n\n for (i = pi; i < npix; i++)\n {\n pixels[i] = 0; // clear missing pixels\n\n }\n\n }\n\n /**\n * Returns true if an error was encountered during reading/decoding\n */\n protected boolean err()\n {\n return status != STATUS_OK;\n }\n\n /**\n * Initializes or re-initializes reader\n */\n protected void init()\n {\n status = STATUS_OK;\n frameCount = 0;\n frames = new ArrayList<>();\n gct = null;\n lct = null;\n }\n\n /**\n * Reads a single byte from the input stream.\n */\n protected int read()\n {\n int curByte = 0;\n try\n {\n curByte = in.read();\n } catch (IOException e)\n {\n status = STATUS_FORMAT_ERROR;\n }\n return curByte;\n }\n\n /**\n * Reads next variable length block from input.\n *\n * @return number of bytes stored in \"buffer\"\n */\n protected int readBlock()\n {\n blockSize = read();\n int n = 0;\n if (blockSize > 0)\n {\n try\n {\n int count = 0;\n while (n < blockSize)\n {\n count = in.read(block, n, blockSize - n);\n if (count == -1)\n {\n break;\n }\n n += count;\n }\n } catch (IOException e)\n {\n }\n\n if (n < blockSize)\n {\n status = STATUS_FORMAT_ERROR;\n }\n }\n return n;\n }\n\n /**\n * Reads color table as 256 RGB integer values\n *\n * @param ncolors int number of colors to read\n * @return int array containing 256 colors (packed ARGB with full alpha)\n */\n protected int[] readColorTable(int ncolors)\n {\n int nbytes = 3 * ncolors;\n int[] tab = null;\n byte[] c = new byte[nbytes];\n int n = 0;\n try\n {\n n = in.read(c);\n } catch (IOException e)\n {\n }\n if (n < nbytes)\n {\n status = STATUS_FORMAT_ERROR;\n } else\n {\n tab = new int[256]; // max size to avoid bounds checks\n\n int i = 0;\n int j = 0;\n while (i < ncolors)\n {\n int r = ((int) c[j++]) & 0xff;\n int g = ((int) c[j++]) & 0xff;\n int b = ((int) c[j++]) & 0xff;\n tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;\n }\n }\n return tab;\n }\n\n /**\n * Main file parser. Reads GIF content blocks.\n */\n protected void readContents()\n {\n // read GIF file content blocks\n boolean done = false;\n while (!(done || err()))\n {\n int code = read();\n switch (code)\n {\n\n case 0x2C: // image separator\n\n readImage();\n break;\n\n case 0x21: // extension\n\n code = read();\n switch (code)\n {\n case 0xf9: // graphics control extension\n\n readGraphicControlExt();\n break;\n\n case 0xff: // application extension\n\n readBlock();\n String app = \"\";\n for (int i = 0; i < 11; i++)\n {\n app += (char) block[i];\n }\n if (app.equals(\"NETSCAPE2.0\"))\n {\n readNetscapeExt();\n } else\n {\n skip(); // don't care\n\n }\n break;\n\n default: // uninteresting extension\n\n skip();\n }\n break;\n\n case 0x3b: // terminator\n\n done = true;\n break;\n\n case 0x00: // bad byte, but keep going and see what happens\n\n break;\n\n default:\n status = STATUS_FORMAT_ERROR;\n }\n }\n }\n\n /**\n * Reads Graphics Control Extension values\n */\n protected void readGraphicControlExt()\n {\n read(); // block size\n\n int packed = read(); // packed fields\n\n dispose = (packed & 0x1c) >> 2; // disposal method\n\n if (dispose == 0)\n {\n dispose = 1; // elect to keep old image if discretionary\n\n }\n transparency = (packed & 1) != 0;\n delay = readShort() * 10; // delay in milliseconds\n\n transIndex = read(); // transparent color index\n\n read(); // block terminator\n\n }\n\n /**\n * Reads GIF file header information.\n */\n protected void readHeader()\n {\n String id = \"\";\n for (int i = 0; i < 6; i++)\n {\n id += (char) read();\n }\n if (!id.startsWith(\"GIF\"))\n {\n status = STATUS_FORMAT_ERROR;\n return;\n }\n\n readLSD();\n if (gctFlag && !err())\n {\n gct = readColorTable(gctSize);\n bgColor = gct[bgIndex];\n }\n }\n\n /**\n * Reads next frame image\n */\n protected void readImage()\n {\n ix = readShort(); // (sub)image position & size\n\n iy = readShort();\n iw = readShort();\n ih = readShort();\n\n int packed = read();\n lctFlag = (packed & 0x80) != 0; // 1 - local color table flag\n\n interlace = (packed & 0x40) != 0; // 2 - interlace flag\n // 3 - sort flag\n // 4-5 - reserved\n\n lctSize = 2 << (packed & 7); // 6-8 - local color table size\n\n if (lctFlag)\n {\n lct = readColorTable(lctSize); // read table\n\n act = lct; // make local table active\n\n } else\n {\n act = gct; // make global table active\n\n if (bgIndex == transIndex)\n {\n bgColor = 0;\n }\n }\n int save = 0;\n if (transparency)\n {\n save = act[transIndex];\n act[transIndex] = 0; // set transparent color if specified\n\n }\n\n if (act == null)\n {\n status = STATUS_FORMAT_ERROR; // no color table defined\n\n }\n\n if (err())\n {\n return;\n }\n decodeImageData(); // decode pixel data\n\n skip();\n\n if (err())\n {\n return;\n }\n frameCount++;\n\n // create new image to receive frame data\n image =\n new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);\n\n setPixels(); // transfer pixel data to image\n\n frames.add(new GifFrame(image, delay)); // add image to frame list\n\n if (transparency)\n {\n act[transIndex] = save;\n }\n resetFrame();\n\n }\n\n /**\n * Reads Logical Screen Descriptor\n */\n protected void readLSD()\n {\n\n // logical screen size\n width = readShort();\n height = readShort();\n\n // packed fields\n int packed = read();\n gctFlag = (packed & 0x80) != 0; // 1 : global color table flag\n // 2-4 : color resolution\n // 5 : gct sort flag\n\n gctSize = 2 << (packed & 7); // 6-8 : gct size\n\n bgIndex = read(); // background color index\n\n pixelAspect = read(); // pixel aspect ratio\n\n }\n\n /**\n * Reads Netscape extenstion to obtain iteration count\n */\n protected void readNetscapeExt()\n {\n do\n {\n readBlock();\n if (block[0] == 1)\n {\n // loop count sub-block\n int b1 = ((int) block[1]) & 0xff;\n int b2 = ((int) block[2]) & 0xff;\n loopCount = (b2 << 8) | b1;\n }\n } while ((blockSize > 0) && !err());\n }\n\n /**\n * Reads next 16-bit value, LSB first\n */\n protected int readShort()\n {\n // read 16-bit value, LSB first\n return read() | (read() << 8);\n }\n\n /**\n * Resets frame state for reading next image.\n */\n protected void resetFrame()\n {\n lastDispose = dispose;\n lastRect = new Rectangle(ix, iy, iw, ih);\n lastImage = image;\n lastBgColor = bgColor;\n//\t\tint dispose = 0;\n//\t\tboolean transparency = false;\n//\t\tint delay = 0;\n dispose = 0;\n transparency = false;\n delay = 0;\n lct = null;\n }\n\n /**\n * Skips variable length blocks up to and including\n * next zero length block.\n */\n protected void skip()\n {\n do\n {\n readBlock();\n } while ((blockSize > 0) && !err());\n }\n}", "public class Utils {\n\n /**\n * Returns a random number from 0 to the specified.\n *\n * @param param The max number to choose.\n */\n public static int nextInt(int param) {\n return random(0, param);\n }\n\n /**\n * Calls the #getExtension(String) method using the file name of the file.\n *\n * @param f The file to get the extension of.\n * @return The extension of the file, or null if there is none.\n */\n public static String getExtension(File f) {\n return getExtension(f.getName());\n }\n\n /**\n * Gets the extension of a file.\n *\n * @param fileName Name of the file to get the extension of.\n * @return The file's extension (ex: \".png\" or \".wav\"), or null if there is none.\n */\n public static String getExtension(String fileName) {\n String ext = null;\n int i = fileName.lastIndexOf('.');\n int len = fileName.length();\n int after = len - i;\n if (i > 0 && (i < len - 1) && after < 5) {//has to be near the end\n ext = fileName.substring(i).toLowerCase();\n }\n return ext;\n }\n\n /**\n * Sets the extension of a file to the specified extension.\n * <p>\n * This can also be used as an assurance that the extension of the\n * file is the specified extension.\n * <p>\n * It's expected that this method will be called before any file saving is\n * done.\n *\n * @param fileName The name of the file to change the extension of.\n * @param extension The extension (ex: \".png\" or \".wav\") for the file.\n * @return The filename with the new extension.\n */\n public static String setExtension(String fileName, String extension) {\n String ext = getExtension(fileName);\n if (ext != null) {\n if (!ext.equalsIgnoreCase(extension)) {\n fileName = fileName.substring(0, fileName.indexOf(ext)) + extension;\n }\n } else {\n fileName = fileName + extension;\n }\n return fileName;\n }\n\n /**\n * Converts a font to string. Only really used in the Settings GUI.\n * (Font#toString() was too messy for me, and fuck making a wrapper class.\n *\n * @return The name, size, and style of the font.\n */\n public static String fontToString(Font f) {\n String toRet = \"\";\n if (f != null) {\n String type;\n if (f.isBold()) {\n type = f.isItalic() ? \"Bold Italic\" : \"Bold\";\n } else {\n type = f.isItalic() ? \"Italic\" : \"Plain\";\n }\n toRet = f.getName() + \",\" + f.getSize() + \",\" + type;\n }\n return toRet;\n }\n\n /**\n * Converts a formatted string (@see #fontToString()) into a font.\n *\n * @param fontString The string to be turned into a font.\n * @return The font.\n */\n public static Font stringToFont(String fontString) {\n String[] toFont = fontString.substring(fontString.indexOf('[') + 1, fontString.length() - 1).split(\",\");\n Font f = new Font(\"Calibri\", Font.PLAIN, 18);\n if (toFont.length == 4) {\n String name = \"Calibri\";\n int size = 18;\n int type = Font.PLAIN;\n for (String keyValPair : toFont) {\n String[] split = keyValPair.split(\"=\");\n String key = split[0];\n String val = split[1];\n switch (key) {\n case \"name\":\n name = val;\n break;\n case \"style\":\n switch (val) {\n case \"plain\":\n type = Font.PLAIN;\n break;\n case \"italic\":\n type = Font.ITALIC;\n break;\n case \"bolditalic\":\n type = Font.BOLD + Font.ITALIC;\n break;\n case \"bold\":\n type = Font.BOLD;\n break;\n default:\n type = Font.PLAIN;\n break;\n }\n break;\n case \"size\":\n try {\n size = Integer.parseInt(val);\n } catch (Exception e) {\n size = 18;\n }\n break;\n default:\n break;\n }\n }\n f = new Font(name, type, size);\n }\n return f;\n }\n\n\n /**\n * Adds a single string to an array of strings, first checking to see if the array contains it.\n *\n * @param toAdd The string(s) to add to the array.\n * @param array The array to add the string to.\n * @return The array of Strings.\n */\n public static String[] addStringsToArray(String[] array, String... toAdd) {\n ArrayList<String> list = new ArrayList<>();\n Collections.addAll(list, array);\n checkAndAdd(list, toAdd);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Compares two arrays of Strings and adds the non-repeating ones to the same one.\n *\n * @param list List of strings to compare to.\n * @param toAdd String(s) to add to the list.\n */\n public static void checkAndAdd(ArrayList<String> list, String... toAdd) {\n for (String s : toAdd) {\n if (!list.contains(s)) {\n list.add(s);\n }\n }\n }\n\n /**\n * Checks individual files one by one like #areFilesGood(String...) and\n * returns the good and legitimate files.\n *\n * @param files The path(s) to the file(s) to check.\n * @return The array of paths to files that actually exist.\n * @see #areFilesGood(String...) for determining if files exist.\n */\n public static String[] checkFiles(String... files) {\n ArrayList<String> list = new ArrayList<>();\n for (String s : files) {\n if (areFilesGood(s)) {\n list.add(s);\n }\n }\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Checks to see if the file(s) is (are) actually existing and non-blank.\n *\n * @param files The path(s) to the file(s) to check.\n * @return true if (all) the file(s) exist(s)\n * @see #checkFiles(String...) For removing bad files and adding the others anyway.\n */\n public static boolean areFilesGood(String... files) {\n int i = 0;\n for (String s : files) {\n File test = new File(s);\n if (test.exists() && test.length() > 0) i++;\n }\n return i == files.length;\n }\n\n /**\n * Logs the chat to a file.\n *\n * @param message The chat separated by newline characters.\n * @param channel The channel the chat was in.\n * @param type The int that determines what the logger should do.\n * 0 = boot\n * 1 = append (clear chat)\n * 2 = shutdown\n */\n public static void logChat(String[] message, String channel, int type) {\n if (channel.startsWith(\"#\")) channel = channel.substring(1);\n try {\n PrintWriter out = new PrintWriter(new BufferedWriter(\n new FileWriter(new File(Settings.logDir.getAbsolutePath() + File.separator + channel + \".txt\"), true)));\n if (type == 0) {\n out.println(\"====================== \" + Settings.date + \" ======================\");\n }\n if (message != null && !(message.length == 0 || (message.length == 1 && message[0].equalsIgnoreCase(\"\")))) {\n for (String s : message) {\n if (s != null && !s.equals(\"\") && !s.equals(\"\\n\")) {\n out.println(s);\n }\n }\n }\n if (type == 2) {\n out.println(\"====================== End of \" + Settings.date + \" ======================\");\n }\n out.close();\n } catch (IOException e) {\n GUIMain.log(e);\n }\n }\n\n /**\n * Removes the last file extension from a path.\n * <p>\n * Note that if the string contains multiple extensions, this will only remove the last one.\n * <p>\n * Ex: \"portal.png.exe.java\" becomes \"portal.png.exe\" after this method returns.\n *\n * @param s The path to a file, or the file name with its extension.\n * @return The file/path name without the extension.\n */\n public static String removeExt(String s) {\n int pos = s.lastIndexOf(\".\");\n if (pos == -1) return s;\n return s.substring(0, pos);\n }\n\n /**\n * Checks to see if the input is IRC-worthy of printing.\n *\n * @param input The input in question.\n * @return The given input if it checks out, otherwise nothing.\n */\n public static String checkText(String input) {\n input = input.trim();\n return !input.isEmpty() ? input : \"\";\n }\n\n /**\n * Returns a number between a given minimum and maximum (exclusive).\n *\n * @param min The minimum number to generate on.\n * @param max The non-inclusive maximum number to generate on.\n * @return Some random number between the given numbers.\n */\n public static int random(int min, int max) {\n return min + (max == min ? 0 : new Random().nextInt(max - min));\n }\n\n /**\n * Generates a color from the #hashCode() of any java.lang.Object.\n * <p>\n * Author - Dr_Kegel from Gocnak's stream.\n *\n * @param seed The Hashcode of the object you want dynamic color for.\n * @return The Color of the object's hash.\n */\n public static Color getColorFromHashcode(final int seed) {\n /* We do some bit hacks here\n hashCode has 32 bit, we use every bit as a random source */\n final int HUE_BITS = 12, HUE_MASK = ((1 << HUE_BITS) - 1);\n final int SATURATION_BITS = 8, SATURATION_MASK = ((1 << SATURATION_BITS) - 1);\n final int BRIGHTNESS_BITS = 12, BRIGHTNESS_MASK = ((1 << BRIGHTNESS_BITS) - 1);\n int t = seed;\n /*\n * We want the full hue spectrum, that means all colors of the color\n\t\t * circle\n\t\t */\n /* [0 .. 1] */\n final float h = (t & HUE_MASK) / (float) HUE_MASK;\n t >>= HUE_BITS;\n final float s = (t & SATURATION_MASK) / (float) SATURATION_MASK;\n t >>= SATURATION_BITS;\n final float b = (t & BRIGHTNESS_MASK) / (float) BRIGHTNESS_MASK;\n /* some tweaks that nor black nor white can be reached */\n /* at the moment h,s,b are in the range of [0 .. 1) */\n /* For s and b this is restricted to [0.75 .. 1) at the moment. */\n return Color.getHSBColor(h, s * 0.25f + 0.75f, b * 0.25f + 0.75f);\n }\n\n /**\n * Returns the SimpleAttributeSet for a specified URL.\n *\n * @param URL The link to make into a URL.\n * @return The SimpleAttributeSet of the URL.\n */\n public static SimpleAttributeSet URLStyle(String URL) {\n SimpleAttributeSet attrs = new SimpleAttributeSet();\n StyleConstants.setForeground(attrs, new Color(43, 162, 235));\n StyleConstants.setFontFamily(attrs, Settings.font.getValue().getFamily());\n StyleConstants.setFontSize(attrs, Settings.font.getValue().getSize());\n StyleConstants.setUnderline(attrs, true);\n attrs.addAttribute(HTML.Attribute.HREF, URL);\n return attrs;\n }\n\n /**\n * Credit: TDuva\n *\n * @param URL The URL to check\n * @return True if the URL can be formed, else false\n */\n public static boolean checkURL(String URL) {\n try {\n new URI(URL);\n } catch (Exception ignored) {\n return false;\n }\n return true;\n }\n\n /**\n * Checks if the given integer is within the range of any of the key=value\n * pairs of the Map (inclusive).\n * <p>\n * Credit: TDuva\n *\n * @param i The integer to check.\n * @param ranges The map of the ranges to check.\n * @return true if the given int is within the range set, else false\n */\n public static boolean inRanges(int i, Map<Integer, Integer> ranges) {\n for (Map.Entry<Integer, Integer> range : ranges.entrySet()) {\n if (i >= range.getKey() && i <= range.getValue()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Converts a given int to the correct millis form, except for 0.\n *\n * @param given Integer to convert.\n * @return The correct Integer in milliseconds.\n */\n public static int handleInt(int given) {\n if (given < 1000 && given > 0) {// not in millis\n given = given * 1000; //convert to millis\n }\n return given;\n }\n\n /**\n * Gets a time (in seconds) from a parsable string.\n *\n * @param toParse The string to parse.\n * @return A time (in seconds) as an integer.\n */\n public static int getTime(String toParse) {\n int toRet;\n if (toParse.contains(\"m\")) {\n String toParseSub = toParse.substring(0, toParse.indexOf(\"m\"));\n try {\n toRet = Integer.parseInt(toParseSub) * 60;\n if (toParse.contains(\"s\")) {\n toParseSub = toParse.substring(toParse.indexOf(\"m\") + 1, toParse.indexOf(\"s\"));\n toRet += Integer.parseInt(toParseSub);\n }\n } catch (Exception e) {\n toRet = -1;\n }\n\n } else {\n if (toParse.contains(\"s\")) {\n toParse = toParse.substring(0, toParse.indexOf('s'));\n }\n try {\n toRet = Integer.parseInt(toParse);\n } catch (Exception e) {\n toRet = -1;\n }\n }\n return toRet;\n }\n\n /**\n * Adds a command to the command map.\n * <p>\n * To do this in chat, simply type !addcommand command message\n * More examples at https://bit.ly/1366RwM\n *\n * @param s The string from the chat.\n * @return true if added, false if fail\n */\n public static Response addCommands(String s) {\n Response toReturn = new Response();\n String[] split = s.split(\" \");\n if (GUIMain.commandSet != null) {\n try {\n String name = split[1];//name of the command, [0] is \"addcommand\"\n if (name.startsWith(\"!\")) name = name.substring(1);\n if (getCommand(name) != null) {\n toReturn.setResponseText(\"Failed to add command, !\" + name + \" already exists!\");\n return toReturn;\n }\n ArrayList<String> arguments = new ArrayList<>();\n if (s.contains(\" | \")) {//command with arguments\n StringTokenizer st = new StringTokenizer(s.substring(0, s.indexOf(\" | \")), \" \");\n while (st.hasMoreTokens()) {\n String work = st.nextToken();\n if (work.startsWith(\"%\") && work.endsWith(\"%\")) {\n arguments.add(work);\n }\n }\n }\n int bingo;\n if (!arguments.isEmpty()) {\n bingo = s.indexOf(\" | \") + 3;//message comes after the pipe separator\n } else {\n int bingoIndex = s.indexOf(\" \", s.indexOf(\" \") + 1);\n if (bingoIndex == -1) {\n toReturn.setResponseText(\"Failed to add command; there is no command content!\");\n return toReturn;\n }\n bingo = bingoIndex + 1;//after second space is the message without arguments\n }\n String[] message = s.substring(bingo).split(\"]\");\n Command c = new Command(name, message);\n if (!arguments.isEmpty()) c.addArguments(arguments.toArray(new String[arguments.size()]));\n if (GUIMain.commandSet.add(c)) {\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully added command \\\"!\" + name + \"\\\"\");\n }\n } catch (Exception e) {\n toReturn.setResponseText(\"Failed to add command due to Exception: \" + e.getMessage());\n }\n }\n return toReturn;\n }\n\n /**\n * Removes a command from the command map.\n *\n * @param key The !command trigger, or key.\n * @return true if removed, else false\n */\n public static Response removeCommands(String key) {\n Response toReturn = new Response();\n if (GUIMain.commandSet != null && key != null) {\n Command c = getCommand(key);\n if (c != null) {\n if (GUIMain.commandSet.remove(c)) {\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully removed command \\\"\" + key + \"\\\"\");\n }\n } else {\n toReturn.setResponseText(\"Failed to remove command, \" + key + \" does not exist!\");\n }\n }\n return toReturn;\n }\n\n /**\n * Tests to see if the tab of the given index is selected.\n *\n * @param tabIndex The index of the chat pane.\n * @return True if the t, else false.\n */\n public static boolean isTabSelected(int tabIndex) {\n return !GUIMain.chatPanes.isEmpty() && GUIMain.channelPane.getSelectedIndex() == tabIndex;\n }\n\n /**\n * Checks to see if a chat pane tab of a given name is visible.\n *\n * @param name The name of the chat pane.\n * @return True if the tab is visible in the TabbedPane, else false.\n */\n public static boolean isTabVisible(String name) {\n if (!GUIMain.chatPanes.isEmpty()) {\n Set<String> keys = GUIMain.chatPanes.keySet();\n for (String s : keys) {\n ChatPane cp = GUIMain.getChatPane(s);\n if (cp.getChannel().equalsIgnoreCase(name)) {\n return cp.isTabVisible();\n }\n }\n }\n return false;\n }\n\n /**\n * Gets a chat pane of the given index.\n *\n * @param index The index of the tab.\n * @return The chat pane if it exists on the index, or null.\n */\n public static ChatPane getChatPane(int index) {\n if (GUIMain.chatPanes != null && !GUIMain.chatPanes.isEmpty()) {\n Set<String> keys = GUIMain.chatPanes.keySet();\n for (String s : keys) {\n ChatPane cp = GUIMain.getChatPane(s);\n if (cp.isTabVisible() && cp.getIndex() == index) return cp;\n }\n }\n return null;\n }\n\n /**\n * Gets the combined chat pane of the given index.\n *\n * @param index The index of the tab.\n * @return The combined chat pane if it exists, or null.\n */\n public static CombinedChatPane getCombinedChatPane(int index) {\n if (!GUIMain.combinedChatPanes.isEmpty()) {\n for (CombinedChatPane cp : GUIMain.combinedChatPanes) {\n if (cp.getIndex() == index) return cp;\n }\n }\n return null;\n }\n\n /**\n * Get the Command from the given !<string> trigger.\n *\n * @param key The !command trigger, or key.\n * @return The Command that the key relates to, or null if there is no command.\n */\n public static Command getCommand(String key) {\n if (GUIMain.commandSet != null && key != null) {\n for (Command c1 : GUIMain.commandSet) {\n if (key.equals(c1.getTrigger())) {\n return c1;\n }\n }\n }\n return null;\n }\n\n /**\n * Gets the console command if the user met the trigger and permission of it.\n *\n * @param key The name of the command.\n * @param channel The channel the user is in.\n * @return The console command, or null if the user didn't meet the requirements.\n */\n public static ConsoleCommand getConsoleCommand(String key, String channel, User u) {\n String master = Settings.accountManager.getUserAccount().getName();\n if (!channel.contains(master)) return null;\n if (u != null) {\n for (ConsoleCommand c : GUIMain.conCommands) {\n if (key.equalsIgnoreCase(c.getTrigger())) {\n int conPerm = c.getClassPermission();\n if (conPerm == -1) {\n List<String> certainPerms = c.getCertainPermissions();\n if (certainPerms.contains(u.getNick()))\n return c;\n } else {//int class permission\n if (Permissions.hasAtLeast(Permissions.getUserPermissions(u, channel), conPerm)) {\n return c;\n }\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Checks to see if a given channel is the main Botnak user's channel.\n *\n * @param channel The channel to check.\n * @return true if indeed the channel, otherwise false.\n */\n public static boolean isMainChannel(String channel) {\n return Settings.accountManager.getUserAccount() != null &&\n (channel.replaceAll(\"#\", \"\").equalsIgnoreCase(Settings.accountManager.getUserAccount().getName()));\n }\n\n /**\n * Gets the String value of the integer permission.\n *\n * @param permission The permission to get the String representation of.\n * @return The String representation of the permission.\n */\n public static String getPermissionString(int permission) {\n return (permission > 0 ? (permission > 1 ? (permission > 2 ? (permission > 3 ?\n \"Only the Broadcaster\" :\n \"Only Mods and the Broadcaster\") :\n \"Donators, Mods, and the Broadcaster\") :\n \"Subscribers, Donators, Mods, and the Broadcaster\") :\n \"Everyone\");\n }\n\n /**\n * Sets the permission of a console command based on the input received.\n * <p>\n * Ex:\n * !setpermission mod 0\n * >Everybody can now mod each other\n * <p>\n * !setpermission mod gocnak,gmansoliver\n * >Only Gocnak and Gmansoliver can mod people\n * <p>\n * etc.\n * <p>\n * Note: This WILL reset the permissions and /then/ set it to specified.\n * If you wish to add another name, you will have to retype the ones already\n * allowed!\n *\n * @param mess The entire message to dissect.\n */\n public static Response setCommandPermission(String mess) {\n Response toReturn = new Response();\n if (mess == null) {\n toReturn.setResponseText(\"Failed to set command permission, message is null!\");\n return toReturn;\n }\n String[] split = mess.split(\" \");\n String trigger = split[1];\n for (ConsoleCommand c : GUIMain.conCommands) {\n if (trigger.equalsIgnoreCase(c.getTrigger())) {\n int classPerm;\n String[] certainPerm = null;\n try {\n classPerm = Integer.parseInt(split[2]);\n } catch (Exception e) {\n classPerm = -1;\n certainPerm = split[2].split(\",\");\n }\n c.setCertainPermission(certainPerm);\n c.setClassPermission(classPerm);\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully set the command permission for \" + trigger + \" !\");\n break;\n }\n }\n return toReturn;\n }\n\n /**\n * Gets the SimpleAttributeSet with the correct color for the message.\n * Cycles through all of the keywords, so the first keyword it matches is the color.\n *\n * @param message The message to dissect.\n * @return The set with the correct color.\n */\n public static SimpleAttributeSet getSetForKeyword(String message) {\n SimpleAttributeSet setToRet = new SimpleAttributeSet(GUIMain.norm);\n Set<String> keys = GUIMain.keywordMap.keySet();\n //case doesnt matter\n keys.stream().filter(\n s -> message.toLowerCase().contains(s.toLowerCase())).forEach(\n s -> StyleConstants.setForeground(setToRet, GUIMain.keywordMap.get(s)));\n return setToRet;\n }\n\n /**\n * Checks to see if the message contains a keyword.\n *\n * @param message The message to check.\n * @return True if the message contains a keyword, else false.\n */\n public static boolean mentionsKeyword(String message) {\n Set<String> keys = GUIMain.keywordMap.keySet();\n for (String s : keys) {\n if (message.toLowerCase().contains(s.toLowerCase())) {//case doesnt matter\n return true;\n }\n }\n return false;\n }\n\n /**\n * Handles the adding/removing of a keyword and the colors.\n *\n * @param mess The entire message to dissect.\n */\n public static Response handleKeyword(String mess) {\n Response toReturn = new Response();\n if (mess == null || \"\".equals(mess)) {\n toReturn.setResponseText(\"Failed to handle keyword, the message is null!\");\n return toReturn;\n }\n String[] split = mess.split(\" \");\n if (split.length > 1) {\n String trigger = split[0];\n String word = split[1];\n if (trigger.equalsIgnoreCase(\"addkeyword\")) {\n String color = mess.substring(mess.indexOf(\" \", mess.indexOf(\" \") + 1) + 1);\n Color c = getColor(color, null);\n if (!c.equals(Color.white)) {\n GUIMain.keywordMap.put(word, c);\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully added keyword \\\"\" + word + \"\\\" !\");\n } else {\n toReturn.setResponseText(\"Failed to add keyword, the color cannot be white!\");\n }\n } else if (trigger.equalsIgnoreCase(\"removekeyword\")) {\n Set<String> keys = GUIMain.keywordMap.keySet();\n for (String s : keys) {\n if (s.equalsIgnoreCase(word)) {\n GUIMain.keywordMap.remove(s);\n toReturn.wasSuccessful();\n toReturn.setResponseText(\"Successfully removed keyword \\\"\" + word + \"\\\" !\");\n return toReturn;\n }\n }\n toReturn.setResponseText(\"Failed to remove keyword, \\\"\" + word + \"\\\" does not exist!\");\n }\n } else {\n toReturn.setResponseText(\"Failed to handle keyword, the keyword is null!\");\n }\n return toReturn;\n }\n\n /**\n * Generates a pseudo-random color that works for Botnak.\n *\n * @return The randomly generated color.\n */\n public static Color getRandomColor() {\n return new Color(random(100, 256), random(100, 256), random(100, 256));\n }\n\n /**\n * Gets the color from the given string. Supports hexadecimal, RGB, and color\n * name.\n *\n * @param message The message to dissect.\n * @param fallback The fallback color to set to if the parsing failed. Defaults to white if null.\n * @return The parsed color from the message, or the fallback color if parsing failed.\n */\n public static Color getColor(String message, Color fallback) {\n Color toRet = (fallback == null ? new Color(255, 255, 255) : fallback);\n String[] split = message.split(\" \");\n if (split.length > 1) { //R G B\n int R;\n int G;\n int B;\n try {\n R = Integer.parseInt(split[0]);\n } catch (NumberFormatException e) {\n R = 0;\n }\n try {\n G = Integer.parseInt(split[1]);\n } catch (NumberFormatException e) {\n G = 0;\n }\n try {\n B = Integer.parseInt(split[2]);\n } catch (NumberFormatException e) {\n B = 0;\n }\n if (checkInts(R, G, B)) toRet = new Color(R, G, B);\n } else {\n try {\n //this is for hexadecimal\n Color toCheck = Color.decode(split[0]);\n if (checkColor(toCheck)) toRet = toCheck;\n } catch (Exception e) {\n //didn't parse it right, so it may be a name of a color\n for (NamedColor nc : Constants.namedColors) {\n if (split[0].equalsIgnoreCase(nc.getName())) {\n toRet = nc.getColor();\n break;\n }\n }\n if (split[0].equalsIgnoreCase(\"random\")) {\n toRet = getRandomColor();\n }\n }\n }\n return toRet;\n }\n\n\n /**\n * Sets a color to the user based on either a R G B value in their message\n * or a standard color from the Color class.\n *\n * @param user User to change the color for.\n * @param mess Their message.\n */\n public static Response handleColor(final User user, String mess, Color old)\n {\n Response toReturn = new Response();\n if (mess != null)\n {\n //mess = \"!setcol r g b\" or \"!setcol #cd4fd5\"\n //so let's send just the second part.\n Color newColor = getColor(mess.substring(mess.indexOf(\" \") + 1), old);\n if (!newColor.equals(old)) {\n GUIMain.userColMap.put(user.getUserID(), newColor);\n toReturn.setResponseText(\"Successfully set color for user \" + user.getDisplayName() + \" !\");\n toReturn.wasSuccessful();\n } else {\n toReturn.setResponseText(\"Failed to update color, it may be too dark!\");\n }\n } else {\n toReturn.setResponseText(\"Failed to update user color, user or message is null!\");\n }\n return toReturn;\n }\n\n /**\n * Gets a color from the given user, whether it be\n * 1. From the manually-set User Color map.\n * 2. From their Twitch color set on the website.\n * 3. The generated color from their name's hash code.\n *\n * @param u The user to get the color of.\n * @return The color of the user.\n */\n public static Color getColorFromUser(User u) {\n Color c;\n String name = u.getNick();\n if (u.getColor() != null) {\n if (GUIMain.userColMap.containsKey(name)) {\n c = GUIMain.userColMap.get(name);\n } else {\n c = u.getColor();\n if (!Utils.checkColor(c)) {\n c = Utils.getColorFromHashcode(name.hashCode());\n }\n }\n } else {//temporarily assign their color as randomly generated\n c = Utils.getColorFromHashcode(name.hashCode());\n }\n return c;\n }\n\n /**\n * Checks a color to see if it will show up in botnak.\n *\n * @param c The color to check.\n * @return True if the color is not null, and shows up in botnak.\n */\n public static boolean checkColor(Color c) {\n return c != null && checkInts(c.getRed(), c.getGreen(), c.getBlue());\n }\n\n /**\n * Checks if the red, green, and blue show up in Botnak,\n * using the standard Luminance formula.\n *\n * @param r Red value\n * @param g Green value\n * @param b Blue value\n * @return true if the Integers meet the specification.\n */\n public static boolean checkInts(int r, int g, int b) {\n double luma = (0.3 * (double) r) + (0.6 * (double) g) + (0.1 * (double) b);\n return luma > (double) 35;\n }\n\n /**\n * Checks to see if the regex is valid.\n *\n * @param toCheck The regex to check.\n * @return <tt>true</tt> if valid regex.\n */\n public static boolean checkRegex(String toCheck) {\n try {\n Pattern.compile(toCheck);\n return true;\n } catch (Exception e) {\n GUIMain.log(e);\n return false;\n }\n }\n\n /**\n * Checks the file name to see if Windows will store it properly.\n *\n * @param toCheck The name to check.\n * @return true if the name is invalid.\n */\n public static boolean checkName(String toCheck) {\n Matcher m = Constants.PATTERN_FILE_NAME_EXCLUDE.matcher(toCheck);\n return m.find();\n }\n\n /**\n * Parses a buffered reader and adds what is read to the provided StringBuilder.\n *\n * @param toRead The stream to read.\n * @param builder The builder to add to.\n */\n public static void parseBufferedReader(BufferedReader toRead, StringBuilder builder, boolean includeNewLine) {\n try (BufferedReader toReadr = toRead) {\n String line;\n while ((line = toReadr.readLine()) != null) {\n builder.append(line);\n if (includeNewLine) builder.append(\"\\n\");\n }\n } catch (Exception e) {\n GUIMain.log(\"Failed to read buffered reader due to exception: \");\n GUIMain.log(e);\n }\n }\n\n /**\n * One to many methods required creating a BufferedReader just to read one line from it.\n * This method does that and saves the effort of writing the code elsewhere.\n *\n * @param input The InputStream to read from.\n * @return The string read from the input.\n */\n public static String createAndParseBufferedReader(InputStream input) {\n return createAndParseBufferedReader(input, false);\n }\n\n public static String createAndParseBufferedReader(InputStream input, boolean includeNewLines)\n {\n String toReturn = \"\";\n try (InputStreamReader inputStreamReader = new InputStreamReader(input, Charset.forName(\"UTF-8\"));\n BufferedReader br = new BufferedReader(inputStreamReader)) {\n StringBuilder sb = new StringBuilder();\n parseBufferedReader(br, sb, includeNewLines);\n toReturn = sb.toString();\n } catch (Exception e) {\n GUIMain.log(\"Could not parse buffered reader due to exception: \");\n GUIMain.log(e);\n }\n return toReturn;\n }\n\n /**\n * Override for the #createAndParseBufferedReader(InputStream) method for just simple URLs.\n * @param URL The URL to try to open.\n * @return The parsed buffered reader if successful, otherwise an empty string.\n */\n public static String createAndParseBufferedReader(String URL)\n {\n try\n {\n return createAndParseBufferedReader(new URL(URL).openStream());\n } catch (Exception e)\n {\n GUIMain.log(\"Could not parse buffered reader due to exception: \");\n GUIMain.log(e);\n }\n return \"\";\n }\n\n /**\n * Opens a web page in the default web browser on the system.\n *\n * @param URL The URL to open.\n */\n public static void openWebPage(String URL) {\n try {\n Desktop desktop = Desktop.getDesktop();\n URI uri = new URL(URL).toURI();\n desktop.browse(uri);\n } catch (Exception ev) {\n GUIMain.log(\"Failed openWebPage due to exception: \");\n GUIMain.log(ev);\n }\n }\n\n /**\n * Caps a number between two given numbers.\n *\n * @param numLesser The lower-bound (inclusive) number to compare against.\n * @param numHigher The higher-bound (inclusive) number to compare against.\n * @param toCompare The number to check and perhaps cap.\n * @param <E> Generics, used for making one method for all number types.\n * @return If the number is within the two bounds, the number is returned.\n * Otherwise, return the supplied number bound that the number is closer to.\n */\n public static <E extends Number> E capNumber(E numLesser, E numHigher, E toCompare) {\n E toReturn = toCompare;\n if (toCompare.floatValue() > numHigher.floatValue()) toReturn = numHigher;//floats are the most precise here\n else if (toCompare.floatValue() < numLesser.floatValue()) toReturn = numLesser;\n return toReturn;\n }\n\n /**\n * Parses Twitch's tags for an IRC message and spits them out into a HashMap.\n *\n * @param tagLine The tags line to parse\n * @param map The output map to put the tags into\n */\n public static void parseTagsToMap(String tagLine, Map<String, String> map)\n {\n if (tagLine != null)\n {\n String[] parts = tagLine.split(\";\");\n for (String part : parts)\n {\n String[] objectPair = part.split(\"=\");\n //Don't add this key/pair value if there is no value.\n if (objectPair.length <= 1) continue;\n map.put(objectPair[0], objectPair[1].replaceAll(\"\\\\\\\\s\", \" \"));\n }\n }\n }\n\n public static void populateComboBox(JComboBox<String> channelsBox)\n {\n channelsBox.removeAllItems();\n if (GUIMain.bot == null || GUIMain.bot.getBot() == null) return;\n\n List<String> channels = GUIMain.bot.getBot().getChannels();\n\n for (String s : channels)\n channelsBox.addItem(s.replaceAll(\"#\", \"\"));\n\n channelsBox.setSelectedItem(GUIMain.getCurrentPane().getChannel());\n }\n}", "public class Settings {\n\n //accounts\n public static AccountManager accountManager = null;\n public static ChannelManager channelManager = null;\n\n\n //donations\n public static DonationManager donationManager = null;\n public static boolean loadedDonationSounds = false;\n public static SubscriberManager subscriberManager = null;\n public static boolean loadedSubSounds = false;\n\n\n //directories\n public static File defaultDir = new File(FileSystemView.getFileSystemView().getDefaultDirectory().getAbsolutePath()\n + File.separator + \"Botnak\");\n public static File tmpDir = new File(defaultDir + File.separator + \"_temp\");\n public static File faceDir = new File(defaultDir + File.separator + \"Faces\");\n public static File nameFaceDir = new File(defaultDir + File.separator + \"NameFaces\");\n public static File twitchFaceDir = new File(defaultDir + File.separator + \"TwitchFaces\");\n public static File frankerFaceZDir = new File(defaultDir + File.separator + \"FrankerFaceZ\");\n public static File subIconsDir = new File(defaultDir + File.separator + \"SubIcons\");\n public static File subSoundDir = new File(defaultDir + File.separator + \"SubSounds\");\n public static File donationSoundDir = new File(defaultDir + File.separator + \"DonationSounds\");\n public static File logDir = new File(defaultDir + File.separator + \"Logs\");\n //files\n public static File accountsFile = new File(defaultDir + File.separator + \"acc.ini\");\n public static File tabsFile = new File(defaultDir + File.separator + \"tabs.txt\");\n public static File soundsFile = new File(defaultDir + File.separator + \"sounds.txt\");\n public static File faceFile = new File(defaultDir + File.separator + \"faces.txt\");\n public static File twitchFaceFile = new File(defaultDir + File.separator + \"twitchfaces.txt\");\n public static File userColFile = new File(defaultDir + File.separator + \"usercols.txt\");\n public static File commandsFile = new File(defaultDir + File.separator + \"commands.txt\");\n public static File ccommandsFile = new File(defaultDir + File.separator + \"chatcom.txt\");\n public static File defaultsFile = new File(defaultDir + File.separator + \"defaults.ini\");\n public static File lafFile = new File(defaultDir + File.separator + \"laf.txt\");\n public static File windowFile = new File(defaultDir + File.separator + \"window.txt\");\n public static File keywordsFile = new File(defaultDir + File.separator + \"keywords.txt\");\n public static File donorsFile = new File(defaultDir + File.separator + \"donors.txt\");\n public static File donationsFile = new File(defaultDir + File.separator + \"donations.txt\");\n public static File subsFile = new File(defaultDir + File.separator + \"subs.txt\");\n\n //appearance\n public static String lookAndFeel = \"lib.jtattoo.com.jtattoo.plaf.hifi.HiFiLookAndFeel\";\n //Graphite = \"lib.jtattoo.com.jtattoo.plaf.graphite.GraphiteLookAndFeel\"\n\n public static String date;\n\n\n //System Tray\n public static Setting<Boolean> stShowMentions = new Setting<>(\"ST_DisplayDonations\", false, Boolean.class);\n public static Setting<Boolean> stShowDonations = new Setting<>(\"ST_DisplayMentions\", false, Boolean.class);\n public static Setting<Boolean> stShowActivity = new Setting<>(\"ST_DisplayActivity\", false, Boolean.class);\n public static Setting<Boolean> stMuted = new Setting<>(\"\", false, Boolean.class);\n public static Setting<Boolean> stUseSystemTray = new Setting<>(\"ST_UseSystemTray\", false, Boolean.class);\n public static Setting<Boolean> stShowSubscribers = new Setting<>(\"ST_DisplaySubscribers\", false, Boolean.class);\n public static Setting<Boolean> stShowNewFollowers = new Setting<>(\"ST_DisplayFollowers\", false, Boolean.class);\n public static Setting<Boolean> stShowReconnecting = new Setting<>(\"ST_DisplayReconnects\", false, Boolean.class);\n\n //Bot Reply\n public static Setting<Boolean> botAnnounceSubscribers = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowYTVideoDetails = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowTwitchVODDetails = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowPreviousSubSound = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botShowPreviousDonSound = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n public static Setting<Boolean> botUnshortenURLs = new Setting<>(\"\"/*TODO*/, true, Boolean.class);\n\n public static Setting<Boolean> ffzFacesEnable = new Setting<>(\"\", true, Boolean.class);\n public static Setting<Boolean> ffzFacesUseAll = new Setting<>(\"\", false, Boolean.class);\n public static Setting<Boolean> actuallyClearChat = new Setting<>(\"\", false, Boolean.class);\n public static Setting<Boolean> showDonorIcons = new Setting<>(\"\", true, Boolean.class);\n public static Setting<Boolean> showTabPulses = new Setting<>(\"\", true, Boolean.class);\n public static Setting<Boolean> trackDonations = new Setting<>(\"TrackDonations\", false, Boolean.class);\n public static Setting<Boolean> trackFollowers = new Setting<>(\"TrackFollowers\", false, Boolean.class);\n\n public static Setting<Boolean> cleanupChat = new Setting<>(\"ClearChat\", true, Boolean.class);\n public static Setting<Boolean> logChat = new Setting<>(\"LogChat\", false, Boolean.class);\n\n\n //Icons TODO are these needed anymore?\n public static Setting<Boolean> useMod = new Setting<>(\"UseMod\", false, Boolean.class);\n public static Setting<Boolean> useAdmin = new Setting<>(\"UseAdmin\", false, Boolean.class);\n public static Setting<Boolean> useStaff = new Setting<>(\"UseStaff\", false, Boolean.class);\n public static Setting<Boolean> useBroad = new Setting<>(\"UseBroad\", false, Boolean.class);\n public static Setting<URL> modIcon = new Setting<>(\"CustomMod\", Settings.class.getResource(\"/image/mod.png\"), URL.class);\n public static Setting<URL> broadIcon = new Setting<>(\"CustomBroad\", Settings.class.getResource(\"/image/broad.png\"), URL.class);\n public static Setting<URL> adminIcon = new Setting<>(\"CustomAdmin\", Settings.class.getResource(\"/image/mod.png\"), URL.class);\n public static Setting<URL> staffIcon = new Setting<>(\"CustomStaff\", Settings.class.getResource(\"/image/mod.png\"), URL.class);\n public static Setting<URL> turboIcon = new Setting<>(\"\", Settings.class.getResource(\"/image/turbo.png\"), URL.class);\n\n public static Setting<Boolean> autoReconnectAccounts = new Setting<>(\"\", true, Boolean.class);\n\n\n public static Setting<Float> soundVolumeGain = new Setting<>(\"\"/*TODO*/, 100f, Float.class);\n public static Setting<Integer> faceMaxHeight = new Setting<>(\"FaceMaxHeight\", 20, Integer.class);\n public static Setting<Integer> chatMax = new Setting<>(\"MaxChat\", 100, Integer.class);\n public static Setting<Integer> botReplyType = new Setting<>(\"BotReplyType\", 0, Integer.class);\n //0 = none, 1 = botnak user only, 2 = everyone\n\n public static Setting<String> lastFMAccount = new Setting<>(\"LastFMAccount\", \"\", String.class);\n public static Setting<String> defaultSoundDir = new Setting<>(\"SoundDir\", \"\", String.class);\n public static Setting<String> defaultFaceDir = new Setting<>(\"FaceDir\", \"\", String.class);\n\n public static Setting<String> donationClientID = new Setting<>(\"DCID\", \"\", String.class);\n public static Setting<String> donationAuthCode = new Setting<>(\"DCOAUTH\", \"\", String.class);\n public static Setting<Boolean> scannedInitialDonations = new Setting<>(\"RanInitDonations\", true, Boolean.class);\n public static Setting<Boolean> scannedInitialSubscribers = new Setting<>(\"RanInitSub\", false, Boolean.class);\n public static Setting<Integer> soundEngineDelay = new Setting<>(\"SoundEngineDelay\", 10000, Integer.class);\n public static Setting<Integer> soundEnginePermission = new Setting<>(\"SoundEnginePerm\", 1, Integer.class);\n\n public static Setting<Boolean> alwaysOnTop = new Setting<>(\"AlwaysOnTop\", false, Boolean.class);\n\n public static Setting<Font> font = new Setting<>(\"Font\", new Font(\"Calibri\", Font.PLAIN, 18), Font.class);\n\n public static Setting<Double> donorCutoff = new Setting<>(\"DonorCutoff\", 2.50, Double.class);\n public static Setting<Integer> cheerDonorCutoff = new Setting<>(\"CheerDonorCutoff\", 250, Integer.class);\n\n private static ArrayList<Setting> settings;\n\n public static Window WINDOW = new Window();\n public static LookAndFeel LAF = new LookAndFeel();\n public static TabState TAB_STATE = new TabState();\n public static Subscribers SUBSCRIBERS = new Subscribers();\n public static Donations DONATIONS = new Donations();\n public static Donors DONORS = new Donors();\n public static Sounds SOUNDS = new Sounds();\n public static Commands COMMANDS = new Commands();\n public static UserColors USER_COLORS = new UserColors();\n public static TwitchFaces TWITCH_FACES = new TwitchFaces();\n public static Faces FACES = new Faces();\n public static Keywords KEYWORDS = new Keywords();\n\n public static void init() {\n long time = System.currentTimeMillis();\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd-MM-yy\");\n date = sdf.format(new Date(time));\n defaultDir.mkdirs();\n // This clears the temp directory\n if (tmpDir.exists())\n ShutdownHook.deleteTempOnExit();\n tmpDir.mkdirs();\n faceDir.mkdirs();\n nameFaceDir.mkdirs();\n twitchFaceDir.mkdirs();\n subIconsDir.mkdirs();\n subSoundDir.mkdirs();\n donationSoundDir.mkdirs();\n //collection for bulk saving/loading\n //(otherwise it would have been a bunch of hardcode...)\n settings = new ArrayList<>();\n try {\n Field[] fields = Settings.class.getDeclaredFields();\n for (Field f : fields) {\n if (f.getType().getName().equals(Setting.class.getName())) {\n settings.add((Setting) f.get(null));\n }\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n /**\n * \"After the fact\":\n * These change listeners are used to update the main GUI upon the setting change.\n */\n soundEngineDelay.addChangeListener(GUIMain.instance::updateSoundDelay);\n soundEnginePermission.addChangeListener(GUIMain.instance::updateSoundPermission);\n botReplyType.addChangeListener(GUIMain.instance::updateBotReplyPerm);\n font.addChangeListener(f -> {\n StyleConstants.setFontFamily(GUIMain.norm, f.getFamily());\n StyleConstants.setFontSize(GUIMain.norm, f.getSize());\n StyleConstants.setBold(GUIMain.norm, f.isBold());\n StyleConstants.setItalic(GUIMain.norm, f.isItalic());\n });\n alwaysOnTop.addChangeListener(GUIMain.instance::updateAlwaysOnTopStatus);\n }\n\n /**\n * This void loads everything Botnak will use, and sets the appropriate settings.\n */\n public static void load() {\n if (Utils.areFilesGood(WINDOW.getFile().getAbsolutePath())) WINDOW.load();\n accountManager = new AccountManager();\n channelManager = new ChannelManager();\n accountManager.start();\n donationManager = new DonationManager();\n subscriberManager = new SubscriberManager();\n if (Utils.areFilesGood(accountsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading accounts...\");\n loadPropData(0);\n }\n if (Utils.areFilesGood(defaultsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading defaults...\");\n loadPropData(1);\n }\n if (Utils.areFilesGood(tabsFile.getAbsolutePath()) && accountManager.getUserAccount() != null) {\n GUIMain.log(\"Loading tabs...\");\n TAB_STATE.load();\n GUIMain.channelPane.setSelectedIndex(TabState.startIndex);\n GUIMain.log(\"Loaded tabs!\");\n }\n if (Utils.areFilesGood(soundsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading sounds...\");\n SOUNDS.load();\n GUIMain.log(\"Loaded sounds!\");\n }\n if (subSoundDir.exists())\n {\n String[] dirList = subSoundDir.list();\n if (dirList != null && dirList.length > 0)\n {\n GUIMain.log(\"Loading sub sounds...\");\n doLoadSubSounds();\n }\n }\n if (donationSoundDir.exists())\n {\n String[] dirList = donationSoundDir.list();\n if (dirList != null && dirList.length > 0)\n {\n GUIMain.log(\"Loading donation sounds...\");\n doLoadDonationSounds();\n }\n }\n if (Utils.areFilesGood(userColFile.getAbsolutePath())) {\n GUIMain.log(\"Loading user colors...\");\n USER_COLORS.load();\n GUIMain.log(\"Loaded user colors!\");\n }\n if (Utils.areFilesGood(donorsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading donors...\");\n DONORS.load();\n GUIMain.log(\"Loaded donors!\");\n }\n if (Utils.areFilesGood(donationsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading donations...\");\n DONATIONS.load();//these are stored locally\n if (Donations.mostRecent != null) {\n donationManager.setLastDonation(Donations.mostRecent);\n GUIMain.log(String.format(\"Most recent donation: %s for %s\", Donations.mostRecent.getFromWho(),\n DonationManager.getCurrencyFormat().format(Donations.mostRecent.getAmount())));\n }\n if (!Donations.donations.isEmpty()) {\n donationManager.fillDonations(Donations.donations);\n Donations.donations.clear();\n Donations.donations = null;\n Donations.mostRecent = null;\n GUIMain.log(\"Loaded donations!\");\n }\n }\n //checks online for offline donations and adds them\n if (donationManager.canCheck() && scannedInitialDonations.getValue()) {\n ThreadEngine.submit(() ->\n {\n donationManager.checkDonations(false);\n donationManager.ranFirstCheck = true;\n });\n }\n if (!scannedInitialDonations.getValue()) {\n ThreadEngine.submit(() ->\n {\n donationManager.scanInitialDonations(0);\n scannedInitialDonations.setValue(true);\n });\n }\n if (accountManager.getUserAccount() != null && accountManager.getUserAccount().getOAuth().canReadSubscribers())\n {\n if (!scannedInitialSubscribers.getValue() && accountManager.getUserAccount() != null) {\n subscriberManager.scanInitialSubscribers(accountManager.getUserAccount().getName(),\n accountManager.getUserAccount().getOAuth(), 0, new HashSet<>());\n }\n }\n if (Utils.areFilesGood(subsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading subscribers...\");\n SUBSCRIBERS.load();\n if (Subscribers.mostRecent != null) {\n subscriberManager.setLastSubscriber(Subscribers.mostRecent);\n //GUIMain.log(\"Most recent subscriber: \" + Subscribers.mostRecent.getName());\n }\n if (!Subscribers.subscribers.isEmpty()) subscriberManager.fillSubscribers(Subscribers.subscribers);\n Subscribers.subscribers.clear();\n Subscribers.subscribers = null;\n Subscribers.mostRecent = null;\n GUIMain.log(\"Loaded subscribers!\");\n }\n if (Utils.areFilesGood(commandsFile.getAbsolutePath())) {\n GUIMain.log(\"Loading text commands...\");\n COMMANDS.load();\n GUIMain.log(\"Loaded text commands!\");\n }\n if (subIconsDir.exists()) {\n File[] subIcons = subIconsDir.listFiles();\n if (subIcons != null && subIcons.length > 0) {\n GUIMain.log(\"Loading subscriber icons...\");\n loadSubIcons(subIcons);\n }\n }\n File[] nameFaces = nameFaceDir.listFiles();\n if (nameFaces != null && nameFaces.length > 0) {\n GUIMain.log(\"Loading name faces...\");\n loadNameFaces(nameFaces);\n }\n if (ffzFacesEnable.getValue()) {\n frankerFaceZDir.mkdirs();\n File[] files = frankerFaceZDir.listFiles();\n if (files != null && files.length > 0) {\n GUIMain.log(\"Loading FrankerFaceZ faces...\");\n loadFFZFaces(files);\n }\n }\n if (keywordsFile.exists()) {\n GUIMain.log(\"Loading keywords...\");\n KEYWORDS.load();\n } else {\n if (accountManager.getUserAccount() != null) {\n GUIMain.keywordMap.put(accountManager.getUserAccount().getName(), Color.orange);\n }\n }\n GUIMain.log(\"Loading console commands...\");\n loadConsoleCommands();//has to be out of the check for files for first time boot\n if (Utils.areFilesGood(faceFile.getAbsolutePath())) {\n GUIMain.log(\"Loading custom faces...\");\n FACES.load();\n FaceManager.doneWithFaces = true;\n GUIMain.log(\"Loaded custom faces!\");\n }\n GUIMain.log(\"Loading default Twitch faces...\");\n if (Utils.areFilesGood(twitchFaceFile.getAbsolutePath())) {\n TWITCH_FACES.load();\n }\n FaceManager.loadDefaultFaces();\n }\n\n /**\n * This handles saving all the settings that need saved.\n */\n public static void save() {\n LAF.save();\n WINDOW.save();\n if (accountManager.getUserAccount() != null || accountManager.getBotAccount() != null) savePropData(0);\n savePropData(1);\n if (!SoundEngine.getEngine().getSoundMap().isEmpty()) SOUNDS.save();\n if (!FaceManager.faceMap.isEmpty()) FACES.save();\n if (!FaceManager.twitchFaceMap.isEmpty()) TWITCH_FACES.save();\n TAB_STATE.save();\n if (!GUIMain.userColMap.isEmpty()) USER_COLORS.save();\n if (GUIMain.loadedCommands()) COMMANDS.save();\n if (!GUIMain.keywordMap.isEmpty()) KEYWORDS.save();\n if (!donationManager.getDonors().isEmpty()) DONORS.save();\n if (!donationManager.getDonations().isEmpty()) DONATIONS.save();\n if (!subscriberManager.getSubscribers().isEmpty()) SUBSCRIBERS.save();\n saveConCommands();\n }\n\n /**\n * *********VOIDS*************\n */\n\n public static void loadPropData(int type) {\n Properties p = new Properties();\n if (type == 0) {//accounts\n try {\n p.load(new FileInputStream(accountsFile));\n String userNorm = p.getProperty(\"UserNorm\", \"\").toLowerCase();\n String userNormPass = p.getProperty(\"UserNormPass\", \"\");\n String status = p.getProperty(\"CanStatus\", \"false\");\n String commercial = p.getProperty(\"CanCommercial\", \"false\");\n if (!userNorm.equals(\"\") && !userNormPass.equals(\"\") && userNormPass.contains(\"oauth\")) {\n boolean stat = Boolean.parseBoolean(status);\n if (!stat) {\n GUIMain.instance.updateStatusOption.setEnabled(false);\n GUIMain.instance.updateStatusOption.setToolTipText(\"Enable \\\"Edit Title and Game\\\" in the Authorize GUI to use this feature.\");\n }\n boolean ad = Boolean.parseBoolean(commercial);\n if (!ad) {\n GUIMain.instance.runAdMenu.setEnabled(false);\n GUIMain.instance.runAdMenu.setToolTipText(\"Enable \\\"Play Commercials\\\" in the Authorize GUI to use this feature.\");\n }\n boolean subs = Boolean.parseBoolean(p.getProperty(\"CanParseSubscribers\", \"false\"));\n boolean followed = Boolean.parseBoolean(p.getProperty(\"CanParseFollowedStreams\", \"false\"));\n if (followed) trackFollowers.setValue(true);\n accountManager.setUserAccount(new Account(userNorm, new OAuth(userNormPass, stat, ad, subs, followed)));\n }\n String userBot = p.getProperty(\"UserBot\", \"\").toLowerCase();\n String userBotPass = p.getProperty(\"UserBotPass\", \"\");\n if (!userBot.equals(\"\") && !userBotPass.equals(\"\") && userBotPass.contains(\"oauth\")) {\n accountManager.setBotAccount(new Account(userBot, new OAuth(userBotPass, false, false, false, false)));\n }\n if (accountManager.getUserAccount() != null) {\n accountManager.addTask(new Task(null, Task.Type.CREATE_VIEWER_ACCOUNT, null));\n }\n if (accountManager.getBotAccount() != null) {\n accountManager.addTask(new Task(null, Task.Type.CREATE_BOT_ACCOUNT, null));\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n if (type == 1) {//defaults\n try {\n p.load(new FileInputStream(defaultsFile));\n settings.forEach(s -> s.load(p));\n if (logChat.getValue()) logDir.mkdirs();\n GUIMain.log(\"Loaded defaults!\");\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n }\n\n public static void savePropData(int type) {\n Properties p = new Properties();\n File writerFile = null;\n String detail = \"\";\n switch (type) {\n case 0:\n Account user = accountManager.getUserAccount();\n Account bot = accountManager.getBotAccount();\n if (user != null) {\n OAuth key = user.getOAuth();\n p.put(\"UserNorm\", user.getName());\n p.put(\"UserNormPass\", key.getKey());\n p.put(\"CanStatus\", String.valueOf(key.canSetTitle()));\n p.put(\"CanCommercial\", String.valueOf(key.canPlayAd()));\n p.put(\"CanParseSubscribers\", String.valueOf(key.canReadSubscribers()));\n p.put(\"CanParseFollowedStreams\", String.valueOf(key.canReadFollowed()));\n }\n if (bot != null) {\n OAuth key = bot.getOAuth();\n p.put(\"UserBot\", bot.getName());\n p.put(\"UserBotPass\", key.getKey());\n }\n writerFile = accountsFile;\n detail = \"Account Info\";\n break;\n case 1:\n settings.forEach(s -> s.save(p));\n writerFile = defaultsFile;\n detail = \"Defaults/Other Settings\";\n break;\n default:\n break;\n }\n if (writerFile != null) {\n try {\n p.store(new FileWriter(writerFile), detail);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n } else {\n GUIMain.log(\"Failed to store settings due to some unforseen exception!\");\n }\n }\n\n\n /**\n * Sounds\n */\n private static class Sounds extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\", 3);\n String[] split2add = split[2].split(\",\");//files\n int perm = 0;\n try {\n perm = Integer.parseInt(split[1]);\n } catch (NumberFormatException e) {\n GUIMain.log(split[0] + \" has a problem. Making it public.\");\n }\n SoundEngine.getEngine().getSoundMap().put(split[0].toLowerCase(), new Sound(perm, split2add));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n Iterator<Map.Entry<String, Sound>> keys = SoundEngine.getEngine().getSoundMap().entrySet().iterator();\n StringBuilder sb = new StringBuilder();\n while (keys.hasNext()) {\n Map.Entry<String, Sound> entry = keys.next();\n sb.append(entry.getKey());\n sb.append(\",\");\n sb.append(entry.getValue().getPermission());\n for (String sound : entry.getValue().getSounds().data) {\n sb.append(\",\");\n sb.append(sound);\n }\n pw.println(sb.toString());\n sb.setLength(0);\n }\n }\n\n @Override\n public File getFile() {\n return soundsFile;\n }\n }\n\n\n /**\n * User Colors\n */\n public static class UserColors extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n GUIMain.userColMap.put(Long.parseLong(split[0]), new Color(Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3])));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n for (Map.Entry<Long, Color> entry : GUIMain.userColMap.entrySet())\n {\n Color col = entry.getValue();\n pw.println(String.format(\"%d,%d,%d,%d\", entry.getKey(), col.getRed(), col.getGreen(), col.getBlue()));\n }\n }\n\n @Override\n public File getFile() {\n return userColFile;\n }\n }\n\n /**\n * Normal faces\n */\n public static class Faces extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n // name name/regex path\n FaceManager.faceMap.put(split[0], new Face(split[1], split[2]));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n FaceManager.faceMap.keySet().stream().filter(s -> s != null && FaceManager.faceMap.get(s) != null).forEach(s -> {\n Face fa = FaceManager.faceMap.get(s);\n pw.println(s + \",\" + fa.getRegex() + \",\" + fa.getFilePath());\n });\n }\n\n @Override\n public File getFile() {\n return faceFile;\n }\n }\n\n /**\n * Twitch Faces\n */\n public static class TwitchFaces extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n try {\n String[] split = line.split(\",\");\n int emoteID = Integer.parseInt(split[0]);\n TwitchFace tf = new TwitchFace(split[1],\n new File(twitchFaceDir + File.separator + String.valueOf(emoteID) + \".png\").getAbsolutePath(),\n Boolean.parseBoolean(split[2]));\n FaceManager.twitchFaceMap.put(emoteID, tf);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n FaceManager.twitchFaceMap.keySet().stream().filter(s -> s != null && FaceManager.twitchFaceMap.get(s) != null)\n .forEach(s -> {\n TwitchFace fa = FaceManager.twitchFaceMap.get(s);\n pw.println(s + \",\" + fa.getRegex() + \",\" + Boolean.toString(fa.isEnabled()));\n });\n }\n\n @Override\n public File getFile() {\n return twitchFaceFile;\n }\n }\n\n\n /**\n * Commands\n * <p>\n * trigger[message (content)[arguments?\n */\n public static class Commands extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n String[] contents = split[1].split(\"]\");\n Command c = new Command(split[0], contents);\n if (split.length > 2) {\n c.addArguments(split[2].split(\",\"));\n }\n GUIMain.commandSet.add(c);\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n for (Command next : GUIMain.commandSet) {\n if (next != null) {\n String name = next.getTrigger();\n String[] contents = next.getMessage().data;\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < contents.length; i++) {\n sb.append(contents[i]);\n if (i != (contents.length - 1)) sb.append(\"]\");\n }\n pw.print(name + \"[\" + sb.toString());\n if (next.hasArguments()) {\n pw.print(\"[\");\n for (int i = 0; i < next.countArguments(); i++) {\n pw.print(next.getArguments().get(i));\n if (i != (next.countArguments() - 1)) pw.print(\",\");\n }\n }\n pw.println();\n }\n }\n }\n\n @Override\n public File getFile() {\n return commandsFile;\n }\n }\n\n /**\n * Console Commands\n */\n public static void saveConCommands() {\n try (PrintWriter br = new PrintWriter(ccommandsFile)) {\n GUIMain.conCommands.forEach(br::println);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n private static ConsoleCommand.Action getAction(String key) {\n ConsoleCommand.Action act = null;\n for (ConsoleCommand.Action a : ConsoleCommand.Action.values()) {\n if (a.toString().equalsIgnoreCase(key)) {\n act = a;\n break;\n }\n }\n return act;\n }\n\n public static void loadConsoleCommands() {\n Set<ConsoleCommand> hardcoded = new HashSet<>();\n hardcoded.add(new ConsoleCommand(\"addface\", ConsoleCommand.Action.ADD_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"changeface\", ConsoleCommand.Action.CHANGE_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removeface\", ConsoleCommand.Action.REMOVE_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"toggleface\", ConsoleCommand.Action.TOGGLE_FACE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addsound\", ConsoleCommand.Action.ADD_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"changesound\", ConsoleCommand.Action.CHANGE_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removesound\", ConsoleCommand.Action.REMOVE_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setsound\", ConsoleCommand.Action.SET_SOUND_DELAY, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"togglesound\", ConsoleCommand.Action.TOGGLE_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"stopsound\", ConsoleCommand.Action.STOP_SOUND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"stopallsounds\", ConsoleCommand.Action.STOP_ALL_SOUNDS, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addkeyword\", ConsoleCommand.Action.ADD_KEYWORD, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removekeyword\", ConsoleCommand.Action.REMOVE_KEYWORD, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setcol\", ConsoleCommand.Action.SET_USER_COL, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setpermission\", ConsoleCommand.Action.SET_COMMAND_PERMISSION, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addcommand\", ConsoleCommand.Action.ADD_TEXT_COMMAND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removecommand\", ConsoleCommand.Action.REMOVE_TEXT_COMMAND, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"adddonation\", ConsoleCommand.Action.ADD_DONATION, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setsoundperm\", ConsoleCommand.Action.SET_SOUND_PERMISSION, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setnameface\", ConsoleCommand.Action.SET_NAME_FACE, Permissions.Permission.SUBSCRIBER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removenameface\", ConsoleCommand.Action.REMOVE_NAME_FACE, Permissions.Permission.SUBSCRIBER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"playad\", ConsoleCommand.Action.PLAY_ADVERT, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"settitle\", ConsoleCommand.Action.SET_STREAM_TITLE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"title\", ConsoleCommand.Action.SEE_STREAM_TITLE, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"setgame\", ConsoleCommand.Action.SET_STREAM_GAME, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"game\", ConsoleCommand.Action.SEE_STREAM_GAME, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"startraffle\", ConsoleCommand.Action.START_RAFFLE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"addrafflewinner\", ConsoleCommand.Action.ADD_RAFFLE_WINNER, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"stopraffle\", ConsoleCommand.Action.STOP_RAFFLE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"removerafflewinner\", ConsoleCommand.Action.REMOVE_RAFFLE_WINNER, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"winners\", ConsoleCommand.Action.SEE_WINNERS, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"startpoll\", ConsoleCommand.Action.START_POLL, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"vote\", ConsoleCommand.Action.VOTE_POLL, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"pollresult\", ConsoleCommand.Action.POLL_RESULT, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"cancelpoll\", ConsoleCommand.Action.CANCEL_POLL, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"song\", ConsoleCommand.Action.NOW_PLAYING, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"soundstate\", ConsoleCommand.Action.SEE_SOUND_STATE, Permissions.Permission.MODERATOR.permValue, null));\n hardcoded.add(new ConsoleCommand(\"uptime\", ConsoleCommand.Action.SHOW_UPTIME, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"lastsubsound\", ConsoleCommand.Action.SEE_PREV_SOUND_SUB, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"lastdonationsound\", ConsoleCommand.Action.SEE_PREV_SOUND_DON, Permissions.Permission.VIEWER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"botreply\", ConsoleCommand.Action.SEE_OR_SET_REPLY_TYPE, Permissions.Permission.BROADCASTER.permValue, null));\n hardcoded.add(new ConsoleCommand(\"volume\", ConsoleCommand.Action.SEE_OR_SET_VOLUME, Permissions.Permission.MODERATOR.permValue, null));\n\n if (Utils.areFilesGood(ccommandsFile.getAbsolutePath())) {\n try (InputStreamReader isr = new InputStreamReader(ccommandsFile.toURI().toURL().openStream());\n BufferedReader br = new BufferedReader(isr)) {\n\n String line;\n while ((line = br.readLine()) != null) {\n String[] split = line.split(\"\\\\[\");\n ConsoleCommand.Action a = getAction(split[1]);\n int classPerm;\n try {\n classPerm = Integer.parseInt(split[2]);\n } catch (Exception e) {\n classPerm = -1;\n }\n List<String> customUsers = new ArrayList<>();\n if (!split[3].equalsIgnoreCase(\"null\")) {\n customUsers.addAll(Arrays.asList(split[3].split(\",\")));\n }\n GUIMain.conCommands.add(new ConsoleCommand(split[0], a, classPerm, customUsers));\n }\n\n // Did we miss any commands?\n if (GUIMain.conCommands.size() != hardcoded.size()) {\n //this ensures every hard coded ConCommand is loaded for Botnak\n hardcoded.stream().filter(con -> !GUIMain.conCommands.contains(con)).forEach(GUIMain.conCommands::add);\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n else { //first time boot/reset/deleted file etc.\n GUIMain.conCommands.addAll(hardcoded);\n }\n GUIMain.log(\"Loaded console commands!\");\n }\n\n\n /**\n * Keywords\n */\n public static class Keywords extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n int r, g, b;\n try {\n r = Integer.parseInt(split[1]);\n } catch (Exception e) {\n r = 255;\n }\n try {\n g = Integer.parseInt(split[2]);\n } catch (Exception e) {\n g = 255;\n }\n try {\n b = Integer.parseInt(split[3]);\n } catch (Exception e) {\n b = 255;\n }\n GUIMain.keywordMap.put(split[0], new Color(r, g, b));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n Set<String> keys = GUIMain.keywordMap.keySet();\n keys.stream().filter(Objects::nonNull).forEach(word ->\n {\n Color c = GUIMain.keywordMap.get(word);\n pw.println(word + \",\" + c.getRed() + \",\" + c.getGreen() + \",\" + c.getBlue());\n });\n }\n\n @Override\n public File getFile() {\n return keywordsFile;\n }\n }\n\n /**\n * Donors\n */\n public static class Donors extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\",\");\n double amount;\n try {\n amount = Double.parseDouble(split[1]);\n } catch (Exception e) {\n amount = 0.0;\n }\n donationManager.getDonors().add(new Donor(split[0], amount));\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n donationManager.getDonors().forEach(pw::println);\n }\n\n @Override\n public File getFile() {\n return donorsFile;\n }\n }\n\n\n /**\n * Donations.\n */\n public static class Donations extends AbstractFileSave {\n\n private static HashSet<Donation> donations = new HashSet<>();\n private static Donation mostRecent = null;\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n double amount;\n try {\n amount = Double.parseDouble(split[3]);\n } catch (Exception e) {\n amount = 0.0;\n }\n Donation d = new Donation(split[0], split[1], split[2], amount, Date.from(Instant.parse(split[4])));\n if ((mostRecent == null || mostRecent.compareTo(d) > 0) && !d.getDonationID().equals(\"LOCAL\"))\n mostRecent = d;\n donations.add(d);\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n donationManager.getDonations().stream().sorted().forEach(pw::println);\n }\n\n @Override\n public File getFile() {\n return donationsFile;\n }\n }\n\n\n /**\n * Subscribers of your own channel\n * <p>\n * Saves each subscriber with the first date Botnak meets them\n * and each month check to see if they're still subbed, if not, make them an ex-subscriber\n */\n private static class Subscribers extends AbstractFileSave {\n\n private static Set<Subscriber> subscribers = new HashSet<>();\n private static Subscriber mostRecent = null;\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n Subscriber s = new Subscriber(Long.parseLong(split[0]), LocalDateTime.parse(split[1]), Boolean.parseBoolean(split[2]), Integer.parseInt(split[3]));\n subscribers.add(s);\n if (mostRecent == null || mostRecent.compareTo(s) > 0) mostRecent = s;\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n subscriberManager.getSubscribers().values().stream().sorted().forEach(pw::println);\n }\n\n @Override\n public File getFile() {\n return subsFile;\n }\n }\n\n\n /**\n * Tab State\n * <p>\n * This is for opening back up to the correct tab, with the correct pane showing.\n * This also handles saving the combined tabs.\n * Format:\n * <p>\n * Single:\n * bool bool string\n * single[ selected[ name\n * <p>\n * Combined:\n * bool boolean String String String[] (split(\",\"))\n * single[ selected[ activeChannel[ title[ every,channel,in,it,separated,by,commas\n * <p>\n * No spaces though.\n * <p>\n * Single tabs can be invisible if they are in a combined tab.\n */\n private static class TabState extends AbstractFileSave {\n\n public static int startIndex = 0;\n\n @Override\n public void handleLineLoad(String line) {\n String[] split = line.split(\"\\\\[\");\n boolean isSingle = Boolean.parseBoolean(split[0]);\n boolean isSelected = Boolean.parseBoolean(split[1]);\n if (isSingle) {\n String channel = split[2];\n if (accountManager.getUserAccount() != null) {\n String channelName = \"#\" + channel;\n GUIMain.channelSet.add(channelName);\n }\n ChatPane cp = ChatPane.createPane(channel);\n GUIMain.chatPanes.put(cp.getChannel(), cp);\n GUIMain.channelPane.insertTab(cp.getChannel(), null, cp.getScrollPane(), null, cp.getIndex());\n if (isSelected) startIndex = cp.getIndex();\n } else {\n String activeChannel = split[2];\n String title = split[3];\n String[] channels = split[4].split(\",\");\n ArrayList<ChatPane> cps = new ArrayList<>();\n for (String c : channels) {\n if (accountManager.getUserAccount() != null) {\n String channelName = \"#\" + c;\n GUIMain.channelSet.add(channelName);\n }\n ChatPane cp = ChatPane.createPane(c);\n GUIMain.chatPanes.put(cp.getChannel(), cp);\n cps.add(cp);\n }\n CombinedChatPane ccp = CombinedChatPane.createCombinedChatPane(cps.toArray(new ChatPane[cps.size()]));\n GUIMain.channelPane.insertTab(ccp.getTabTitle(), null, ccp.getScrollPane(), null, ccp.getIndex());\n ccp.setCustomTitle(title);\n if (isSelected) startIndex = ccp.getIndex();\n if (!activeChannel.equalsIgnoreCase(\"all\")) {\n ccp.setActiveChannel(activeChannel);\n ccp.setActiveScrollPane(activeChannel);\n }\n GUIMain.combinedChatPanes.add(ccp);\n }\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n int currentSelectedIndex = GUIMain.channelPane.getSelectedIndex();\n for (int i = 1; i < GUIMain.channelPane.getTabCount() - 1; i++) {\n ChatPane current = Utils.getChatPane(i);\n if (current != null) {\n if (current.isTabVisible()) {\n boolean selected = current.getIndex() == currentSelectedIndex;\n pw.println(\"true[\" + String.valueOf(selected) + \"[\" + current.getChannel());\n }\n } else {\n CombinedChatPane cc = Utils.getCombinedChatPane(i);\n if (cc != null) {\n //all the panes in them should be set to false\n //their indexes are technically going to be -1\n boolean selected = cc.getIndex() == currentSelectedIndex;\n pw.print(\"false[\" + String.valueOf(selected) + \"[\" + cc.getActiveChannel() + \"[\" + cc.getTabTitle() + \"[\");\n pw.print(cc.getChannels().stream().collect(Collectors.joining(\",\")));\n pw.println();\n }\n }\n }\n }\n\n @Override\n public File getFile() {\n return tabsFile;\n }\n }\n\n /**\n * Look and Feel\n */\n public static class LookAndFeel extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n if (line.contains(\"jtattoo\")) lookAndFeel = line;\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n pw.println(lookAndFeel);\n }\n\n @Override\n public File getFile() {\n return lafFile;\n }\n }\n\n /**\n * Window Location and Size\n */\n private static class Window extends AbstractFileSave {\n\n @Override\n public void handleLineLoad(String line) {\n String[] parts = line.substring(1).split(\",\");\n String first = parts[0];\n String second = parts[1];\n if (line.startsWith(\"p\")) {\n try {\n int x = Integer.parseInt(first);\n int y = Integer.parseInt(second);\n GUIMain.instance.setLocation(x, y);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n } else if (line.startsWith(\"s\")) {\n try {\n double w = Double.parseDouble(first);\n double h = Double.parseDouble(second);\n GUIMain.instance.setSize((int) w, (int) h);\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n }\n\n @Override\n public void handleLineSave(PrintWriter pw) {\n pw.println(\"p\" + GUIMain.instance.getLocationOnScreen().x + \",\" + GUIMain.instance.getLocationOnScreen().y);\n pw.println(\"s\" + GUIMain.instance.getSize().getWidth() + \",\" + GUIMain.instance.getSize().getHeight());\n }\n\n\n @Override\n public File getFile() {\n return windowFile;\n }\n }\n\n //Other methods that don't follow standardization\n\n /**\n * Name faces\n */\n public static void loadNameFaces(File[] nameFaces) {\n try {\n for (File nameFace : nameFaces) {\n if (nameFace.isDirectory()) continue;\n String userID = Utils.removeExt(nameFace.getName());\n FaceManager.nameFaceMap.put(Long.parseLong(userID), new Face(userID, nameFace.getAbsolutePath()));\n }\n GUIMain.log(\"Loaded name faces!\");\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n private static void doLoadSubSounds() {\n loadSubSounds();\n loadedSubSounds = true;\n GUIMain.log(\"Loaded sub sounds!\");\n }\n\n public static void loadSubSounds() {\n loadShuffleSet(subSoundDir, SoundEngine.getEngine().getSubStack());\n }\n\n private static void doLoadDonationSounds() {\n loadDonationSounds();\n loadedDonationSounds = true;\n GUIMain.log(\"Loaded donation sounds!\");\n }\n\n public static void loadDonationSounds() {\n loadShuffleSet(donationSoundDir, SoundEngine.getEngine().getDonationStack());\n }\n\n private static void loadShuffleSet(File directory, Deque<Sound> stack) {\n try {\n File[] files = directory.listFiles();\n if (files != null && files.length > 0) {\n ArrayList<Sound> sounds = new ArrayList<>();\n for (File f : files) {\n sounds.add(new Sound(5, f.getAbsolutePath()));\n }\n Collections.shuffle(sounds);\n stack.addAll(sounds);\n }\n } catch (Exception e) {\n GUIMain.log(e);\n }\n }\n\n /**\n * Sub icons\n */\n public static void loadSubIcons(File[] subIconFiles) {\n for (File f : subIconFiles) {\n FaceManager.subIconMap.put(Utils.removeExt(f.getName()), f.getAbsolutePath());\n }\n }\n\n /**\n * FrankerFaceZ\n * <p>\n * We can be a little more broad about this saving, since it's a per-channel basis\n */\n public static void loadFFZFaces(File[] channels) {\n for (File channel : channels) {\n if (channel.isDirectory() && channel.length() > 0) {\n File[] faces = channel.listFiles();\n if (faces != null) {\n ArrayList<FrankerFaceZ> loadedFaces = new ArrayList<>();\n for (File face : faces) {\n if (face != null) {\n loadedFaces.add(new FrankerFaceZ(face.getName(), face.getAbsolutePath(), true));\n }\n }\n FaceManager.ffzFaceMap.put(channel.getName(), loadedFaces);\n } else {\n channel.delete();\n }\n }\n }\n }\n}" ]
import gui.ChatPane; import gui.forms.GUIMain; import lib.scalr.Scalr; import util.AnimatedGifEncoder; import util.GifDecoder; import util.Utils; import util.settings.Settings; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL;
icon = sizeIcon(ChatPane.class.getResource("/image/silver.png")); break; case DONOR_HIGH: icon = sizeIcon(ChatPane.class.getResource("/image/gold.png")); break; case DONOR_INSANE: icon = sizeIcon(ChatPane.class.getResource("/image/diamond.png")); break; case GLOBAL_MOD: icon = sizeIcon(ChatPane.class.getResource("/image/globalmod.png")); break; case CHEER_BIT_AMT_RED: icon = sizeGifIcon(ChatPane.class.getResource("/image/bits_red.gif"), i.name()); break; case CHEER_BIT_AMT_BLUE: icon = sizeGifIcon(ChatPane.class.getResource("/image/bits_blue.gif"), i.name()); break; case CHEER_BIT_AMT_GREEN: icon = sizeGifIcon(ChatPane.class.getResource("/image/bits_green.gif"), i.name()); break; case CHEER_BIT_AMT_PURPLE: icon = sizeGifIcon(ChatPane.class.getResource("/image/bits_purple.gif"), i.name()); break; case CHEER_BIT_AMT_GRAY: icon = sizeGifIcon(ChatPane.class.getResource("/image/bits_gray.gif"), i.name()); break; case CHEER_1_99: icon = sizeIcon(ChatPane.class.getResource("/image/bits_tier_gray.png")); break; case CHEER_100_999: icon = sizeIcon(ChatPane.class.getResource("/image/bits_tier_purple.png")); break; case CHEER_1K_4K: icon = sizeIcon(ChatPane.class.getResource("/image/bits_tier_green.png")); break; case CHEER_5K_9K: icon = sizeIcon(ChatPane.class.getResource("/image/bits_tier_blue.png")); break; case CHEER_10K_99K: icon = sizeIcon(ChatPane.class.getResource("/image/bits_tier_red.png")); break; case CHEER_100K: icon = sizeIcon(ChatPane.class.getResource("/image/bits_tier_orange.png")); break; case NONE: default: break; } return new BotnakIcon(i, icon); } /** * Resize an icon to match the chat font size. This has the * effect of allowing users to submit images of any size. * * @param image the image URL * @return ImageIcon the resized image */ public static ImageIcon sizeIcon(URL image) { ImageIcon icon; try { BufferedImage img = ImageIO.read(image); int size = Settings.font.getValue().getSize(); img = Scalr.resize(img, Scalr.Method.ULTRA_QUALITY, size, size); icon = new ImageIcon(img); icon.getImage().flush(); return icon; } catch (Exception e) { icon = new ImageIcon(image); } return icon; } public static ImageIcon sizeGifIcon(URL image, String name) { ImageIcon icon; File temp = new File(Settings.tmpDir + File.separator + Utils.setExtension(name, ".gif")); //Only size this if we haven't already if (temp.exists()) { icon = new ImageIcon(temp.getAbsolutePath()); } else { try { InputStream is = image.openStream(); GifDecoder decoder = new GifDecoder(); int status = decoder.read(is); if (status == 0) { AnimatedGifEncoder age = new AnimatedGifEncoder(); age.setRepeat(0); age.setQuality(1); FileOutputStream fos = new FileOutputStream(temp); age.start(fos); int n = decoder.getFrameCount(); int size = Settings.font.getValue().getSize(); for (int i = 0; i < n; i++) { BufferedImage scaled = Scalr.resize(decoder.getFrame(i), Scalr.Method.ULTRA_QUALITY, size, size); age.addFrame(scaled); if (decoder.getDelay(i) == 0) { age.setDelay(100); } else { age.setDelay(decoder.getDelay(i)); } } age.finish(); fos.close(); icon = new ImageIcon(temp.getAbsolutePath()); } else {
GUIMain.log("sizeGifIcon failed to read the input gif! Status: " + status);
1
marcocor/smaph
src/main/java/it/unipi/di/acube/smaph/learn/featurePacks/BindingFeaturePack.java
[ "public class QueryInformation {\n\tpublic boolean includeSourceNormalSearch;\n\tpublic boolean includeSourceWikiSearch;\n\tpublic boolean includeSourceSnippets;\n\tpublic Double webTotalNS;\n\tpublic List<String> allBoldsNS;\n\tpublic HashMap<Integer, Integer> idToRankNS;\n\tpublic List<Pair<String, Integer>> boldsAndRankNS;\n\tpublic int resultsCountNS;\n\tpublic double webTotalWS;\n\tpublic List<Pair<String, Integer>> boldsAndRankWS;\n\tpublic HashMap<Integer, Integer> idToRankWS;\n\tpublic HashMap<Tag, List<String>> entityToBoldsSA;\n\tpublic HashMap<Tag, List<String>> entityToMentionsSA;\n\tpublic HashMap<Tag, List<Integer>> entityToRanksSA;\n\tpublic HashMap<Tag, List<HashMap<String, Double>>> entityToAdditionalInfosSA;\n\tpublic Set<Tag> candidatesSA;\n\tpublic Set<Tag> candidatesNS;\n\tpublic Set<Tag> candidatesWS;\n\t\n\tprivate Set<Tag> allCandidates = null;\n\t\n\tpublic Set<Tag> allCandidates() {\n\t\tif (allCandidates == null){\n\t\t\tallCandidates= new HashSet<Tag>();\n\t\t\tif (includeSourceSnippets)\n\t\t\t\tallCandidates.addAll(candidatesSA);\n\t\t\tif (includeSourceNormalSearch)\n\t\t\t\tallCandidates.addAll(candidatesNS);\n\t\t\tif (includeSourceWikiSearch)\n\t\t\t\tallCandidates.addAll(candidatesWS);\n\t\t}\n\t\treturn allCandidates;\n\t}\n}", "public class SmaphUtils {\n\tprivate final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());\n\tpublic static final String BASE_DBPEDIA_URI = \"http://dbpedia.org/resource/\";\n\tpublic static final String BASE_WIKIPEDIA_URI = \"http://en.wikipedia.org/wiki/\";\n\tpublic static final String WIKITITLE_ENDPAR_REGEX = \"\\\\s*\\\\([^\\\\)]*\\\\)\\\\s*$\";\n\n\t/**\n\t * For each word of bold, finds the word in query that has the minimum edit\n\t * distance, normalized by the word length. Returns the average of those\n\t * distances.\n\t * \n\t * @param query\n\t * a query.\n\t * @param bold\n\t * a bold.\n\t * @return the averaged normalized word-by-word edit distance of bold\n\t * against query.\n\t */\n\tpublic static double getMinEditDist(String query, String bold) {\n\t\treturn getMinEditDist(query, bold, null);\n\t}\n\n\t/**\n\t * For each word of bold, finds the word in query that has the minimum edit\n\t * distance, normalized by the word length. Put that word in minTokens.\n\t * Returns the average of those distances.\n\t * \n\t * @param query\n\t * a query.\n\t * @param bold\n\t * a bold.\n\t * @param minTokens\n\t * the tokens of query having minimum edit distance.\n\t * @return the averaged normalized word-by-word edit distance of bold\n\t * against query.\n\t */\n\tpublic static double getMinEditDist(String query, String bold,\n\t\t\tList<String> minTokens) {\n\t\tList<String> tokensQ = tokenize(query);\n\t\tList<String> tokensB = tokenize(bold);\n\n\t\tif (tokensB.size() == 0 || tokensQ.size() == 0)\n\t\t\treturn 1;\n\n\t\tfloat avgMinDist = 0;\n\t\tfor (String tokenB : tokensB) {\n\t\t\tfloat minDist = Float.MAX_VALUE;\n\t\t\tString bestQToken = null;\n\t\t\tfor (String tokenQ : tokensQ) {\n\t\t\t\tfloat relLev = getNormEditDistance(tokenB, tokenQ);\n\t\t\t\tif (relLev < minDist) {\n\t\t\t\t\tminDist = relLev;\n\t\t\t\t\tbestQToken = tokenQ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (minTokens != null)\n\t\t\t\tminTokens.add(bestQToken);\n\t\t\tavgMinDist += minDist;\n\t\t}\n\t\treturn avgMinDist / tokensB.size();\n\t}\n\n\t/**\n\t * @param tokenB\n\t * a word.\n\t * @param tokenQ\n\t * another word.\n\t * @return the normalized edit distance between tokenB and tokenQ.\n\t */\n\tpublic static float getNormEditDistance(String tokenB, String tokenQ) {\n\t\tif (tokenQ.isEmpty() || tokenB.isEmpty())\n\t\t\treturn 1;\n\t\tint lev = StringUtils.getLevenshteinDistance(tokenB, tokenQ);\n\t\treturn (float) lev / (float) Math.max(tokenB.length(), tokenQ.length());\n\t}\n\n\tpublic static float getNormEditDistanceLC(String tokenB, String tokenQ) {\n\t\ttokenB = tokenB.replaceAll(\"\\\\W+\", \" \").toLowerCase();\n\t\ttokenQ = tokenQ.replaceAll(\"\\\\W+\", \" \").toLowerCase();\n\t\treturn getNormEditDistance(tokenB, tokenQ);\n\t}\n\n\tpublic static double weightedGeometricAverage(double[] vals, double[] weights) {\n\t\tif (vals.length != weights.length)\n\t\t\tthrow new IllegalArgumentException();\n\n\t\tdouble num = 0;\n\t\tdouble denum = 0;\n\n\t\tfor (int i = 0; i < vals.length; i++) {\n\t\t\tnum += Math.log(vals[i]) * weights[i];\n\t\t\tdenum += weights[i];\n\t\t}\n\n\t\treturn Math.exp(num / denum);\n\t}\n\n\t/**\n\t * @param title\n\t * the title of a Wikipedia page.\n\t * @return true iff the title is that of a regular page.\n\t */\n\tpublic static boolean acceptWikipediaTitle(String title) {\n\t\t// TODO: this can definitely be done in a cleaner way.\n\t\treturn !(title.startsWith(\"Talk:\") || title.startsWith(\"Special:\")\n\t\t\t\t|| title.startsWith(\"Portal:\")\n\t\t\t\t|| title.startsWith(\"Wikipedia:\")\n\t\t\t\t|| title.startsWith(\"Template:\")\n\t\t\t\t|| title.startsWith(\"Wikipedia_talk:\")\n\t\t\t\t|| title.startsWith(\"File:\") || title.startsWith(\"User:\")\n\t\t\t\t|| title.startsWith(\"Category:\") || title.startsWith(\"List\") || title\n\t\t\t\t.contains(\"(disambiguation)\"));\n\t}\n\n\t/**\n\t * @param ftrCount\n\t * the number of features.\n\t * @param excludedFeatures\n\t * the features that have to be excluded from the feature list.\n\t * @return a vector containing all feature ids from 1 to ftrCount\n\t * (included), except those in excludedFeatures.\n\t */\n\tpublic static int[] getAllFtrVect(int ftrCount, int[] excludedFeatures) {\n\t\tArrays.sort(excludedFeatures);\n\t\tVector<Integer> res = new Vector<>();\n\t\tfor (int i = 1; i < ftrCount + 1; i++)\n\t\t\tif (Arrays.binarySearch(excludedFeatures, i) < 0)\n\t\t\t\tres.add(i);\n\t\treturn ArrayUtils.toPrimitive(res.toArray(new Integer[] {}));\n\t}\n\n\t/**\n\t * @param ftrCount\n\t * the number of features.\n\t * @return a vector containing all feature ids from 1 to ftrCount (included.\n\t */\n\tpublic static int[] getAllFtrVect(int ftrCount) {\n\t\treturn getAllFtrVect(ftrCount, new int[0]);\n\t}\n\n\t/**\n\t * @param base\n\t * @param ftrId\n\t * @return a new feature vector composed by base with the addition of ftrId.\n\t */\n\tpublic static int[] addFtrVect(int[] base, int ftrId) {\n\t\tif (base == null)\n\t\t\treturn new int[] { ftrId };\n\t\telse {\n\t\t\tif (ArrayUtils.contains(base, ftrId))\n\t\t\t\tthrow new IllegalArgumentException(\"Trying to add a feature to a vector that already contains it.\");\n\t\t\tint[] newVect = new int[base.length + 1];\n\t\t\tSystem.arraycopy(base, 0, newVect, 0, base.length);\n\t\t\tnewVect[newVect.length - 1] = ftrId;\n\t\t\tArrays.sort(newVect);\n\t\t\treturn newVect;\n\t\t}\n\t}\n\n\t/**\n\t * @param features\n\t * @param ftrToRemove\n\t * @return a new feature vector composed by base without ftrId.\n\t */\n\tpublic static int[] removeFtrVect(int[] features, int ftrToRemove) {\n\t\tint[] newFtrVect = new int[features.length -1];\n\t\tint j=0;\n\t\tfor (int i=0; i<features.length; i++)\n\t\t\tif (features[i] == ftrToRemove)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tnewFtrVect[j++] = features[i];\n\t\tif (j != newFtrVect.length)\n\t\t\tthrow new IllegalArgumentException(\"Feature \"+ ftrToRemove+\" is not present and cannot be removed.\");\n\t\tArrays.sort(newFtrVect);\n\t\treturn newFtrVect;\n\t}\n\n\t/**\n\t * @param ftrVectorStr a list of comma-separated integers (e.g. 1,5,6,7)\n\t * @return a feature vector with features provided as input.\n\t */\n\tpublic static int[] strToFeatureVector(String ftrVectorStr) {\n\t\tif (ftrVectorStr.isEmpty())\n\t\t\treturn new int[] {};\n\t\tString[] tokens = ftrVectorStr.split(\",\");\n\t\tint[] ftrVect = new int[tokens.length];\n\t\tfor (int j = 0; j < tokens.length; j++)\n\t\t\tftrVect[j] = Integer.parseInt(tokens[j]);\n\t\tArrays.sort(ftrVect);\n\t\treturn ftrVect;\n\t}\n\n\t/**\n\t * Turns a list of pairs <b,r>, where b is a bold and r is the position in\n\t * which the bold occurred, to the list of bolds and the hashmap between a\n\t * position and the list of bolds occurring in that position.\n\t * \n\t * @param boldAndRanks\n\t * a list of pairs <b,r>, where b is a bold and r is the position\n\t * in which the bold occurred.\n\t * @param positions\n\t * where to store the mapping between a position (rank) and all\n\t * bolds that appear in that position.\n\t * @param bolds\n\t * where to store the bolds.\n\t */\n\tpublic static void mapRankToBoldsLC(\n\t\t\tList<Pair<String, Integer>> boldAndRanks,\n\t\t\tHashMap<Integer, HashSet<String>> positions, HashSet<String> bolds) {\n\n\t\tfor (Pair<String, Integer> boldAndRank : boldAndRanks) {\n\t\t\tString spot = boldAndRank.first.toLowerCase();\n\t\t\tint rank = boldAndRank.second;\n\t\t\tif (bolds != null)\n\t\t\t\tbolds.add(spot);\n\t\t\tif (positions != null) {\n\t\t\t\tif (!positions.containsKey(rank))\n\t\t\t\t\tpositions.put(rank, new HashSet<String>());\n\t\t\t\tpositions.get(rank).add(spot);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Turns a list of pairs <b,r>, where b is a bold and r is the position in\n\t * which the bold occurred, to a mapping from a bold to the positions in\n\t * which the bolds occurred.\n\t * \n\t * @param boldAndRanks\n\t * a list of pairs <b,r>, where b is a bold and r is the position\n\t * in which the bold occurred.\n\t * @return a mapping from a bold to the positions in which the bold\n\t * occurred.\n\t */\n\tpublic static HashMap<String, HashSet<Integer>> findPositionsLC(\n\t\t\tList<Pair<String, Integer>> boldAndRanks) {\n\t\tHashMap<String, HashSet<Integer>> positions = new HashMap<>();\n\t\tfor (Pair<String, Integer> boldAndRank : boldAndRanks) {\n\t\t\tString bold = boldAndRank.first.toLowerCase();\n\t\t\tint rank = boldAndRank.second;\n\t\t\tif (!positions.containsKey(bold))\n\t\t\t\tpositions.put(bold, new HashSet<Integer>());\n\t\t\tpositions.get(bold).add(rank);\n\t\t}\n\t\treturn positions;\n\t}\n\n\t/**\n\t * Given a string, replaces all words with their stemmed version.\n\t * \n\t * @param str\n\t * a string.\n\t * @param stemmer\n\t * the stemmer.\n\t * @return str with all words stemmed.\n\t */\n\tprivate static String stemString(String str, EnglishStemmer stemmer) {\n\t\tString stemmedString = \"\";\n\t\tString[] words = str.split(\"\\\\s+\");\n\t\tfor (int i = 0; i < words.length; i++) {\n\t\t\tString word = words[i];\n\t\t\tstemmer.setCurrent(word);\n\t\t\tstemmer.stem();\n\t\t\tstemmedString += stemmer.getCurrent();\n\t\t\tif (i != words.length)\n\t\t\t\tstemmedString += \" \";\n\t\t}\n\t\treturn stemmedString;\n\t}\n\n\t/**\n\t * Compress a string with GZip.\n\t * \n\t * @param str\n\t * the string.\n\t * @return the compressed string.\n\t * @throws IOException\n\t * if something went wrong during compression.\n\t */\n\tpublic static byte[] compress(String str) throws IOException {\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tGZIPOutputStream gzip = new GZIPOutputStream(out);\n\t\tgzip.write(str.getBytes(\"utf-8\"));\n\t\tgzip.close();\n\t\treturn out.toByteArray();\n\t}\n\n\t/**\n\t * Decompress a GZipped string.\n\t * \n\t * @param compressed\n\t * the sequence of bytes\n\t * @return the decompressed string.\n\t * @throws IOException\n\t * if something went wrong during decompression.\n\t */\n\tpublic static String decompress(byte[] compressed) throws IOException {\n\t\tGZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(\n\t\t\t\tcompressed));\n\t\treturn new String(IOUtils.toByteArray(gis), \"utf-8\");\n\t}\n\n\tpublic static List<String> tokenize(String text) {\n\t\tint start = -1;\n\t\tVector<String> tokens = new Vector<>();\n\t\tfor (int i = 0; i < text.length(); i++) {\n\t\t\tif (Character.isWhitespace(text.charAt(i))) {\n\t\t\t\tif (start != -1) {\n\t\t\t\t\ttokens.add(text.substring(start, i));\n\t\t\t\t\tstart = -1;\n\t\t\t\t}\n\t\t\t} else if (start == -1)\n\t\t\t\tstart = i;\n\t\t}\n\t\tif (start != -1)\n\t\t\ttokens.add(text.substring(start));\n\n\t\treturn tokens;\n\t}\n\n\tpublic static List<Pair<Integer, Integer>> findTokensPosition(String text) {\n\t\ttext = text.replaceAll(\"\\\\W\", \" \").replaceAll(\"\\\\s\", \" \");\n\t\tList<Pair<Integer, Integer>> positions = new Vector<>();\n\t\tint idx = 0;\n\t\twhile (idx < text.length()) {\n\t\t\twhile (idx < text.length() && text.charAt(idx) == ' ')\n\t\t\t\tidx++;\n\t\t\tif (idx == text.length())\n\t\t\t\tbreak;\n\t\t\tint start = idx;\n\t\t\twhile (idx < text.length() && text.charAt(idx) != ' ')\n\t\t\t\tidx++;\n\t\t\tint end = idx;\n\t\t\tpositions.add(new Pair<>(start, end));\n\t\t}\n\t\treturn positions;\n\t}\n\n\tpublic static List<String> findSegmentsStrings(String text) {\n\t\tVector<String> words = new Vector<String>();\n\t\tfor (Pair<Integer, Integer> startEnd : findTokensPosition(text))\n\t\t\twords.add(text.substring(startEnd.first, startEnd.second));\n\t\tVector<String> segments = new Vector<String>();\n\t\tfor (int start = 0; start < words.size(); start++) {\n\t\t\tfor (int end = 0; end < words.size(); end++){\n\t\t\t\tif (start <= end) {\n\t\t\t\t\tString segment = \"\";\n\t\t\t\t\tfor (int i = start; i <= end; i++) {\n\t\t\t\t\t\tsegment += words.get(i);\n\t\t\t\t\t\tif (i != end)\n\t\t\t\t\t\t\tsegment += \" \";\n\t\t\t\t\t}\n\t\t\t\t\tsegments.add(segment);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn segments;\n\t}\n\n\tpublic static List<Pair<Integer, Integer>> findSegments(String text) {\n\t\tList<Pair<Integer, Integer>> tokens = findTokensPosition(text);\n\t\tList<Pair<Integer, Integer>> segments = new Vector<>();\n\t\tfor (int n= 1; n<=tokens.size(); n++)\n\t\t\tfor (int i=0;i<=tokens.size()-n;i++)\n\t\t\t\tsegments.add(new Pair<Integer, Integer>(tokens.get(i).first, tokens.get(i+n-1).second));\n\t\treturn segments;\n\t}\n\n\tprivate static void addBIOToken(int n, char token, String sequence,\n\t\t\tList<String> sequences, int limit) {\n\t\tif (limit >= 0 && sequences.size() >= limit)\n\t\t\treturn;\n\t\tsequence += token;\n\t\tif (n > 0) {\n\t\t\taddBIOToken(n - 1, 'B', sequence, sequences, limit);\n\t\t\tif (token != 'O')\n\t\t\t\taddBIOToken(n - 1, 'I', sequence, sequences, limit);\n\t\t\taddBIOToken(n - 1, 'O', sequence, sequences, limit);\n\t\t} else\n\t\t\tsequences.add(sequence);\n\t}\n\n\tpublic static List<String> getBioSequences(int n, int limit) {\n\t\tList<String> sequences = new Vector<>();\n\t\taddBIOToken(n - 1, 'B', \"\", sequences, limit);\n\t\taddBIOToken(n - 1, 'O', \"\", sequences, limit);\n\t\treturn sequences;\n\t}\n\n\tpublic static List<List<Pair<Integer, Integer>>> getSegmentations(\n\t\t\tString query, int maxBioSequence) {\n\t\tList<Pair<Integer, Integer>> qTokens = findTokensPosition(query);\n\t\tList<List<Pair<Integer, Integer>>> segmentations = new Vector<>();\n\t\tList<String> bioSequences = getBioSequences(qTokens.size(),\n\t\t\t\tmaxBioSequence);\n\t\tfor (String bioSequence : bioSequences) {\n\t\t\tint start = -1;\n\t\t\tint end = -1;\n\t\t\tList<Pair<Integer, Integer>> segmentation = new Vector<>();\n\t\t\tfor (int i = 0; i < qTokens.size(); i++) {\n\t\t\t\tPair<Integer, Integer> token = qTokens.get(i);\n\t\t\t\tif (start >= 0\n\t\t\t\t\t\t&& (bioSequence.charAt(i) == 'B' || bioSequence\n\t\t\t\t\t\t.charAt(i) == 'O')) {\n\t\t\t\t\tsegmentation.add(new Pair<Integer, Integer>(start, end));\n\t\t\t\t\tstart = -1;\n\t\t\t\t}\n\t\t\t\tif (bioSequence.charAt(i) == 'B'\n\t\t\t\t\t\t|| bioSequence.charAt(i) == 'I') {\n\t\t\t\t\tif (start == -1)\n\t\t\t\t\t\tstart = token.first;\n\t\t\t\t\tend = token.second;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (start != -1)\n\t\t\t\tsegmentation.add(new Pair<Integer, Integer>(start, end));\n\t\t\tsegmentations.add(segmentation);\n\t\t}\n\t\treturn segmentations;\n\t}\n\n\tpublic static HashMap<Tag, String[]> getEntitiesToBoldsList(\n\t\t\tHashMap<Tag, List<String>> tagToBolds, Set<Tag> entityToKeep) {\n\t\tHashMap<Tag, String[]> res = new HashMap<>();\n\t\tfor (Tag t : tagToBolds.keySet())\n\t\t\tif (entityToKeep == null || entityToKeep.contains(t))\n\t\t\t\tres.put(t, tagToBolds.get(t).toArray(new String[]{}));\n\t\treturn res;\n\t}\n\n\tpublic static HashMap<Tag, String> getEntitiesToTitles(\n\t\t\tSet<Tag> acceptedEntities, WikipediaInterface wikiApi) {\n\t\tHashMap<Tag, String> res = new HashMap<>();\n\t\tfor (Tag t : acceptedEntities)\n\t\t\ttry {\n\t\t\t\tres.put(t, wikiApi.getTitlebyId(t.getConcept()));\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\treturn res;\n\t}\n\n\tpublic static int getNonAlphanumericCharCount(String str) {\n\t\tint count = 0;\n\t\tfor (char c : str.toCharArray())\n\t\t\tif (!((c >= 'a' &&c <= 'z') || (c >= 'A' &&c <= 'Z') || (c >= '0' &&c <= '9') || c == ' '))\n\t\t\t\tcount ++;\n\t\treturn count;\n\t}\n\n\tpublic static class ComparePairsByFirstElement<E extends Serializable, T extends Comparable<T> & Serializable> implements Comparator<Pair<T, E>> {\n\t\t@Override\n\t\tpublic int compare(Pair<T, E> o1, Pair<T, E> o2) {\n\t\t\treturn o1.first.compareTo(o2.first);\n\t\t}\n\t}\n\n\tpublic static class ComparePairsBySecondElement<E extends Serializable, T extends Comparable<T> & Serializable> implements Comparator<Pair<E, T>> {\n\t\t@Override\n\t\tpublic int compare(Pair<E, T> o1, Pair<E, T> o2) {\n\t\t\treturn o1.second.compareTo(o2.second);\n\t\t}\n\t}\n\n\t/**\n\t * @param tokensA\n\t * @param tokensB\n\t * @return true if tokensA is a strict sublist of tokensB (i.e. |tokensA| < |tokensB| and there are two indexes i and j s.t. tokensA.equals(tokensB.subList(i, j))).\n\t */\n\tpublic static boolean isSubToken(List<String> tokensA, List<String> tokensB){\n\t\tif (tokensA.size() >= tokensB.size())\n\t\t\treturn false;\n\t\tfor (int i=0 ; i<=tokensB.size() - tokensA.size(); i++)\n\t\t\tif (tokensA.equals(tokensB.subList(i, i+tokensA.size())))\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\n\t/**\n\t * @param bolds\n\t * a list of bolds\n\t * @param bold\n\t * a bold\n\t * @return the proportion between the number of times bold appears in the\n\t * list and the number of times in which shorter bolds having at\n\t * least one word in common appear in the list.\n\t */\n\tpublic static double getFragmentation(List<String> bolds, String bold) {\n\t\tint boldCount = 0;\n\t\tint fragmentsCount = 0;\n\t\tList<String> tokensBold = tokenize(stemString(bold, new EnglishStemmer()));\n\n\t\tfor (String b : bolds) {\n\t\t\tList<String> tokensB = tokenize(stemString(b, new EnglishStemmer()));\n\t\t\tif (tokensBold.equals(tokensB))\n\t\t\t\tboldCount++;\n\t\t\telse {\n\t\t\t\tif (isSubToken(tokensB, tokensBold))\n\t\t\t\t\tfragmentsCount ++;\n\t\t\t\t/*if (tokensB.size() < tokensBold.size()) {\n\t\t\t\t\tboolean found = false;\n\t\t\t\t\tfor (String tokenB : tokensB)\n\t\t\t\t\t\tfor (String tokenBold : tokensBold)\n\t\t\t\t\t\t\tif (tokenB.equals(tokenBold)) {\n\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\tif (found)\n\t\t\t\t\t\tfragmentsCount++;\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t\tif (boldCount == 0)\n\t\t\treturn 0.0;\n\t\treturn (double) boldCount / (double) (Math.pow(fragmentsCount, 1.4) + boldCount);\n\t}\n\n\t/**\n\t * @param bolds\n\t * a list of bolds\n\t * @param bold\n\t * a bold\n\t * @return the proportion between the number of times bold appears in the\n\t * list and the number of times in which longer bolds containing all\n\t * words of bold appear in the list.\n\t */\n\tpublic static double getAggregation(List<String> bolds, String bold) {\n\t\tint boldCount = 0;\n\t\tint fragmentsCount = 0;\n\t\tList<String> tokensBold = tokenize(stemString(bold, new EnglishStemmer()));\n\n\t\tfor (String b : bolds) {\n\t\t\tList<String> tokensB = tokenize(stemString(b, new EnglishStemmer()));\n\t\t\tif (tokensBold.equals(tokensB))\n\t\t\t\tboldCount++;\n\t\t\telse {\n\t\t\t\tif (isSubToken(tokensBold, tokensB))\n\t\t\t\t\tfragmentsCount ++;\n\t\t\t\t/*if (tokensB.size() > tokensBold.size()) {\n\t\t\t\t\tboolean cover = true;\n\t\t\t\t\tfor (String tokenBold : tokensBold)\n\t\t\t\t\t\tif (!tokensB.contains(tokenBold)){\n\t\t\t\t\t\t\tcover = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tif (cover)\n\t\t\t\t\t\tfragmentsCount++;\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t\tif (boldCount == 0)\n\t\t\treturn 0.0;\n\t\treturn (double) boldCount / (double) (Math.pow(fragmentsCount, 1.4) + boldCount);\n\t}\n\n\n\tpublic static List<String> boldPairsToListLC(\n\t\t\tList<Pair<String, Integer>> boldAndRanks) {\n\t\tList<String> res = new Vector<>();\n\t\tfor (Pair<String, Integer> boldAndRank : boldAndRanks)\n\t\t\tres.add(boldAndRank.first.toLowerCase());\n\t\treturn res;\n\t}\n\n\n\n\tpublic static Triple<Double, Double, Double> getMinMaxAvg(List<Double> values) {\n\t\tif (values.isEmpty())\n\t\t\treturn new ImmutableTriple<Double, Double, Double>(0.0, 0.0, 0.0);\n\n\t\tdouble minVal = Double.POSITIVE_INFINITY;\n\t\tdouble maxVal = Double.NEGATIVE_INFINITY;\n\t\tdouble avgVal = 0.0;\n\t\tfor (double v : values) {\n\t\t\tminVal = Math.min(v, minVal);\n\t\t\tmaxVal = Math.max(v, maxVal);\n\t\t\tavgVal += v / values.size();\n\t\t}\n\n\t\treturn new ImmutableTriple<Double, Double, Double>(minVal, maxVal,\n\t\t\t\tavgVal);\n\t}\n\n\tpublic static HashSet<ScoredAnnotation> collapseBinding(\n\t\t\tHashSet<ScoredAnnotation> binding) {\n\t\tif (binding.size() <= 1)\n\t\t\treturn binding;\n\n\t\tHashSet<ScoredAnnotation> res = new HashSet<>();\n\t\tVector<ScoredAnnotation> bindingOrdered = new Vector<>(binding);\n\t\tCollections.sort(bindingOrdered);\n\t\tScoredAnnotation firstEqual = bindingOrdered.get(0);\n\t\tfloat score = 0f;\n\t\tint equalCount = 0;\n\t\tfor (int i = 0; i < bindingOrdered.size(); i++) {\n\t\t\tScoredAnnotation nextAnn = (i == bindingOrdered.size() - 1) ? null\n\t\t\t\t\t: bindingOrdered.get(i + 1);\n\t\t\tScoredAnnotation annI = bindingOrdered.get(i);\n\t\t\tscore += annI.getScore();\n\t\t\tequalCount++;\n\t\t\tif (nextAnn == null\n\t\t\t\t\t|| nextAnn.getConcept() != firstEqual.getConcept()) {\n\t\t\t\tres.add(new ScoredAnnotation(firstEqual.getPosition(), annI\n\t\t\t\t\t\t.getPosition()\n\t\t\t\t\t\t+ annI.getLength()\n\t\t\t\t\t\t- firstEqual.getPosition(), firstEqual.getConcept(),\n\t\t\t\t\t\tscore / equalCount));\n\t\t\t\tfirstEqual = nextAnn;\n\t\t\t\tscore = 0;\n\t\t\t\tequalCount = 0;\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n\tpublic static <T> List<T> sorted(Collection<T> c, Comparator<T> comp) {\n\t\tList<T> list = new ArrayList<T>(c);\n\t\tCollections.sort(list, comp);\n\t\treturn list;\n\t}\n\tpublic static <T extends Comparable<? super T>> List<T> sorted(Collection<T> c) {\n\t\treturn sorted(c, null);\n\t}\n\n\tpublic static String removeTrailingParenthetical(String title) {\n\t\treturn title.replaceAll(WIKITITLE_ENDPAR_REGEX, \"\");\n\t}\n\n\tpublic static JSONObject httpQueryJson(String urlAddr) {\n\t\tString resultStr = null;\n\t\ttry {\n\t\t\tURL url = new URL(urlAddr);\n\t\t\tHttpURLConnection conn = (HttpURLConnection) url.openConnection();\n\t\t\tconn.setRequestMethod(\"GET\");\n\n\t\t\tif (conn.getResponseCode() != 200) {\n\t\t\t\tScanner s = new Scanner(conn.getErrorStream())\n\t\t\t\t.useDelimiter(\"\\\\A\");\n\t\t\t\tLOG.error(\"Got HTTP error {}. Message is: {}\",\n\t\t\t\t\t\tconn.getResponseCode(), s.next());\n\t\t\t\ts.close();\n\t\t\t}\n\n\t\t\tScanner s = new Scanner(conn.getInputStream())\n\t\t\t.useDelimiter(\"\\\\A\");\n\t\t\tresultStr = s.hasNext() ? s.next() : \"\";\n\n\t\t\treturn new JSONObject(resultStr);\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static double computeAvgRank(List<Integer> positions, int resultsCount) {\n\t\tif (resultsCount==0) return 1;\n\t\tfloat avg = 0;\n\t\tfor (int pos : positions)\n\t\t\tavg += (float)pos/(float)resultsCount;\n\t\tavg += resultsCount - positions.size();\n\n\t\tavg /= resultsCount;\n\t\treturn avg;\n\t}\n\n\tpublic static double getFrequency(int occurrences, int resultsCount) {\n\t\treturn (float) occurrences / (float) resultsCount;\n\t}\n\n\tpublic static <T1, T2> HashMap<T1, T2> inverseMap(HashMap<T2, T1> map) {\n\t\treturn (HashMap<T1, T2>) map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));\n\t}\n\n\tprivate static void populateBindingsRec(List<Tag> chosenCandidates, List<List<Tag>> candidates, List<List<Tag>> bindings,\n\t\t\tint maxBindings) {\n\t\tif (maxBindings > 0 && bindings.size() >= maxBindings)\n\t\t\treturn;\n\t\tif (chosenCandidates.size() == candidates.size()) {\n\t\t\tbindings.add(new Vector<Tag>(chosenCandidates));\n\t\t\treturn;\n\t\t}\n\t\tList<Tag> candidatesToExpand = candidates.get(chosenCandidates.size());\n\t\tfor (Tag candidate : candidatesToExpand) {\n\t\t\tList<Tag> nextChosenCandidates = new Vector<>(chosenCandidates);\n\t\t\tnextChosenCandidates.add(candidate);\n\t\t\tpopulateBindingsRec(nextChosenCandidates, candidates, bindings, maxBindings);\n\t\t}\n\t}\n\n\t/**\n\t * @param candidates for each segment, the list of candidates it may be linked to\n\t * @param maxBindings the maximum number of returned bindings (ignored if less than 1)\n\t * @return the possible bindings for a single segmentations\n\t */\n\tpublic static List<List<Tag>> getBindings(List<List<Tag>> candidates, int maxBindings) {\n\t\tList<List<Tag>> bindings = new Vector<List<Tag>>();\n\t\tList<Tag> chosenCandidates = new Vector<Tag>();\n\t\tpopulateBindingsRec(chosenCandidates, candidates, bindings, maxBindings);\n\t\treturn bindings;\n\t}\n\n\tpublic static String getDBPediaURI(String title) {\n\t\treturn BASE_DBPEDIA_URI + WikipediaInterface.normalize(title);\n\t}\n\n\tpublic static String getWikipediaURI(String title) {\n\t\ttry {\n\t\t\treturn BASE_WIKIPEDIA_URI + URLEncoder.encode(title, \"utf8\").replace(\"+\", \"%20\");\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static void exportToNif(A2WDataset ds, String baseUri, WikipediaInterface wikiApi, OutputStream outputStream) {\n\t\tList<org.aksw.gerbil.transfer.nif.Document> documents = new Vector<>();\n\n\t\tfor (int i = 0; i < ds.getSize(); i++) {\n\t\t\tString text = ds.getTextInstanceList().get(i);\n\t\t\torg.aksw.gerbil.transfer.nif.Document d = new DocumentImpl(text, baseUri + \"/doc\" + i);\n\n\t\t\tfor (it.unipi.di.acube.batframework.data.Annotation a : ds.getA2WGoldStandardList().get(i)) {\n\t\t\t\tString title;\n\t\t\t\ttry {\n\t\t\t\t\ttitle = wikiApi.getTitlebyId(a.getConcept());\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t\td.addMarking(new NamedEntity(a.getPosition(), a.getLength(), getDBPediaURI(title)));\n\t\t\t}\n\t\t\tdocuments.add(d);\n\t\t}\n\t\tNIFWriter writer = new TurtleNIFWriter();\n\t\twriter.writeNIF(documents, outputStream);\n\t}\n}", "public class WATRelatednessComputer implements Serializable {\n\tprivate final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static WATRelatednessComputer instance = new WATRelatednessComputer();\n\tprivate Object2DoubleOpenHashMap<Pair<Integer,Integer>> cacheJaccard = new Object2DoubleOpenHashMap<>();\n\tprivate Object2DoubleOpenHashMap<Pair<Integer,Integer>> cacheMW = new Object2DoubleOpenHashMap<>();\n\tprivate Object2DoubleOpenHashMap<String> cacheLp = new Object2DoubleOpenHashMap<>();\n\tprivate static long flushCounter = 0;\n\tprivate static final int FLUSH_EVERY = 1000;\n\tprivate static final String URL_TEMPLATE_JACCARD = \"%s/relatedness/graph?gcube-token=%s&ids=%d&ids=%d&relatedness=jaccard\";\n\tprivate static final String URL_TEMPLATE_MW = \"%s/relatedness/graph?gcube-token=%s&ids=%d&ids=%d&relatedness=mw\";\n\tprivate static final String URL_TEMPLATE_SPOT = \"%s/sf/sf?gcube-token=%s&text=%s\";\n\tprivate static String baseUri = \"https://wat.d4science.org/wat\";\n\tprivate static String gcubeToken = null;\n\tprivate static String resultsCacheFilename = null;\n\t\n\tpublic static void setBaseUri(String watBaseUri){\n\t\tbaseUri = watBaseUri;\n\t}\n\t\n\tpublic static void setGcubeToken(String watGcubeToken){\n\t\tgcubeToken = watGcubeToken;\n\t}\n\t\n\tprivate synchronized void increaseFlushCounter()\n\t\t\tthrows FileNotFoundException, IOException {\n\t\tflushCounter++;\n\t\tif ((flushCounter % FLUSH_EVERY) == 0)\n\t\t\tflush();\n\t}\n\n\tpublic static synchronized void flush() throws FileNotFoundException,\n\t\t\tIOException {\n\t\tif (flushCounter > 0 && resultsCacheFilename != null) {\n\t\t\tLOG.info(\"Flushing relatedness cache... \");\n\t\t\tnew File(resultsCacheFilename).createNewFile();\n\t\t\tObjectOutputStream oos = new ObjectOutputStream(\n\t\t\t\t\tnew FileOutputStream(resultsCacheFilename));\n\t\t\toos.writeObject(instance);\n\t\t\toos.close();\n\t\t\tLOG.info(\"Flushing relatedness cache done.\");\n\t\t}\n\t}\n\t\n\tpublic static void setCache(String cacheFilename)\n\t\t\tthrows FileNotFoundException, IOException, ClassNotFoundException {\n\t\tif (resultsCacheFilename != null\n\t\t\t\t&& resultsCacheFilename.equals(cacheFilename))\n\t\t\treturn;\n\t\tLOG.info(\"Loading relatedness cache...\");\n\t\tresultsCacheFilename = cacheFilename;\n\t\tif (new File(resultsCacheFilename).exists()) {\n\t\t\tObjectInputStream ois = new ObjectInputStream(new FileInputStream(\n\t\t\t\t\tresultsCacheFilename));\n\t\t\tinstance = (WATRelatednessComputer) ois.readObject();\n\t\t\tois.close();\n\t\t}\n\t}\n\n\tprivate double queryJsonRel(int wid1, int wid2, String urlTemplate) {\n\t\tString url = String.format(urlTemplate, baseUri, gcubeToken, wid1, wid2);\n\t\tLOG.info(url);\n\t\tJSONObject obj = SmaphUtils.httpQueryJson(url);\n\t\ttry {\n\t\t\tincreaseFlushCounter();\n\t\t\tdouble rel = obj.getJSONArray(\"pairs\").getJSONObject(0).getDouble(\"relatedness\");\n\t\t\tLOG.debug(\" -> \" + rel);\n\t\t\treturn rel;\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tprivate double getGenericRelatedness(int wid1, int wid2, Object2DoubleOpenHashMap<Pair<Integer,Integer>> cache, String url){\n\t\tif (wid2 < wid1) {\n\t\t\tint tmp = wid2;\n\t\t\twid2 = wid1;\n\t\t\twid2 = tmp;\n\t\t}\n\t\tPair <Integer,Integer> p = new Pair<Integer,Integer>(wid1,wid2);\n\t\tif (!cache.containsKey(p))\n\t\t\tcache.put(p, queryJsonRel(wid1, wid2, url));\n\t\t\t\n\t\treturn cache.getDouble(p);\n\t}\n\t\n\tpublic static double getJaccardRelatedness(int wid1, int wid2) {\n\t\tif (wid1 == wid2) return 1.0;\n\t\treturn instance.getGenericRelatedness(wid1, wid2, instance.cacheJaccard, URL_TEMPLATE_JACCARD);\n\t}\n\n\tpublic static double getMwRelatedness(int wid1, int wid2) {\n\t\tif (wid1 == wid2) return 1.0;\n\t\treturn instance.getGenericRelatedness(wid1, wid2, instance.cacheMW, URL_TEMPLATE_MW);\n\t}\n\n\tpublic static double getLp(String anchor) {\n\t\tif (!instance.cacheLp.containsKey(anchor))\n\t\t\tinstance.cacheLp.put(anchor, queryJsonLp(anchor));\n\t\treturn instance.cacheLp.get(anchor);\n\t}\n\n\tprivate static double queryJsonLp(String anchor) {\n\t\tString url;\n\t\ttry {\n\t\t\turl = String.format(URL_TEMPLATE_SPOT, baseUri, gcubeToken, URLEncoder.encode(anchor, \"utf-8\"));\n\t\t} catch (UnsupportedEncodingException e1) {\n\t\t\te1.printStackTrace();\n\t\t\tthrow new RuntimeException(e1);\n\t\t}\n\t\t\n\t\tLOG.debug(\"Querying {}\", url);\n\t\t\n\t\tJSONObject obj = SmaphUtils.httpQueryJson(url);\n\t\t\n\t\ttry {\n\t\t\tinstance.increaseFlushCounter();\n\t\t\treturn obj.getDouble(\"link_probability\");\n\t\t} catch (Exception e1) {\n\t\t\te1.printStackTrace();\n\t\t\tthrow new RuntimeException(e1);\n\t\t}\n\t}\n\n}", "public class EntityToAnchors {\n\tpublic static final String DEFAULT_INPUT = \"./data/anchors.tsv\";\n\tpublic static final String DATASET_FILENAME = \"./mapdb/e2a.db\";\n\n\tprivate DB db;\n\t/**\n\t * entity -> anchor-IDs\n\t */\n\tprivate HTreeMap<Integer, int[]> entityToAnchorIDs;\n\t\n\t/**\n\t * entity -> frequencies of anchor-ID for entity\n\t */\n\tprivate HTreeMap<Integer,int[]> entityToFreqs;\n\t\n\t/**\n\t * From anchor to anchor-ID\n\t */\n\tprivate HTreeMap<String, Integer> anchorToAid;\n\t\n\t/**\n\t * From anchor-ID to snchor\n\t */\n\tprivate HTreeMap<Integer, String> aidToAnchor;\n\t\n\t/**\n\t * anchor-ID -> how many times the anchor has been seen \n\t */\n\tprivate HTreeMap<Integer, Integer> anchorToOccurrences;\t\n\t\n\tprivate static Logger logger = LoggerFactory.getLogger(EntityToAnchors.class.getName());\n\n\tpublic static EntityToAnchors fromDB(String datasetFilename) {\n\t\tlogger.info(\"Opening E2A database.\");\n\t\tDB db = DBMaker.fileDB(datasetFilename).fileMmapEnable().readOnly().closeOnJvmShutdown().make();\n\t\tEntityToAnchors e2a = new EntityToAnchors(db);\n\t\tlogger.info(\"Loading E2A database done.\");\n\t\treturn e2a;\n\t}\n\n\tprivate EntityToAnchors(DB db) {\n\t\tthis.db = db;\n\t\tentityToAnchorIDs = db.hashMap(\"entityToAnchorIDs\", Serializer.INTEGER, Serializer.INT_ARRAY).createOrOpen();\n\t\tentityToFreqs = db.hashMap(\"entityToFreqs\", Serializer.INTEGER, Serializer.INT_ARRAY).createOrOpen();\n\t\tanchorToAid = db.hashMap(\"anchorToAid\", Serializer.STRING, Serializer.INTEGER).createOrOpen();\n\t\taidToAnchor = db.hashMap(\"aidToAnchor\", Serializer.INTEGER, Serializer.STRING).createOrOpen();\n\t\tanchorToOccurrences = db.hashMap(\"anchorToOccurrences\", Serializer.INTEGER, Serializer.INTEGER).createOrOpen();\n\t}\n\n\tprivate static void createDB(String file) throws FileNotFoundException,\n\t\t\tIOException {\n\t\t\n\t\tInputStream inputStream = new FileInputStream(file);\n\t\tBufferedReader buffered = new BufferedReader(new InputStreamReader(\n\t\t\t\tinputStream, \"UTF-8\"));\n\n\t\tlogger.info(\"Building database...\");\n\t\tEntityToAnchors mdb = new EntityToAnchors(DBMaker.fileDB(DATASET_FILENAME).fileMmapEnable().closeOnJvmShutdown().make());\n\n\t\tlong count = 0;\n\t\tlong processedMbs = 0;\n\t\tInt2ObjectOpenHashMap<Int2IntArrayMap> entityToAnchorIDToFreqBuffer = new Int2ObjectOpenHashMap<Int2IntArrayMap>();\n\t\t\n\t\tint lastAnchorId = 0;\n\t\tString line = null;\n\t\twhile ((line = buffered.readLine()) != null) {\n\t\t\tcount += line.length();\n\t\t\tif (count > processedMbs * (10 * 1024 * 1024))\n\t\t\t\tlogger.info(String.format(\"Read %d MiB.\", 10*(processedMbs++)));\n\t\t\t\n\t\t\tString[] tokens = line.split(\"\\t\");\n\t\t\tif (tokens.length != 3){\n\t\t\t\tbuffered.close();\n\t\t\t\tthrow new RuntimeException(\"Read line: [\" + line + \"] should have three tokens.\");\n\t\t\t}\n\t\t\t\n\t\t\tString anchor = tokens[0].toLowerCase();\n\t\t\tint freq = Integer.parseInt(tokens[2]);\n\n\t\t\tif (!mdb.anchorToAid.containsKey(anchor)){\n\t\t\t\tmdb.anchorToAid.put(anchor, lastAnchorId);\n\t\t\t\tmdb.aidToAnchor.put(lastAnchorId, anchor);\n\t\t\t\tlastAnchorId++;\n\t\t\t}\n\t\t\t\t\n\t\t\tInteger aId = mdb.anchorToAid.get(anchor);\n\t\t\t\n\t\t\tint pageId = Integer.parseInt(tokens[1]);\n\n\t\t\tInt2IntArrayMap aidToFreqMap = entityToAnchorIDToFreqBuffer.get(pageId);\n\t\t\tif (aidToFreqMap == null){\n\t\t\t\taidToFreqMap = new Int2IntArrayMap();\n\t\t\t\tentityToAnchorIDToFreqBuffer.put(pageId, aidToFreqMap);\n\t\t\t}\n\t\t\tif (!aidToFreqMap.containsKey(aId))\n\t\t\t\taidToFreqMap.put(aId.intValue(), freq);\n\t\t\telse\n\t\t\t\taidToFreqMap.put(aId.intValue(), freq + aidToFreqMap.get(aId)); //increase the occurrence for anchor by freq (this should only happen for anchors with different case, same content.)\n\t\t\t\n\t\t\tif (!mdb.anchorToOccurrences.containsKey(aId))\n\t\t\t\tmdb.anchorToOccurrences.put(aId, 0);\n\t\t\tmdb.anchorToOccurrences.put(aId, mdb.anchorToOccurrences.get(aId) + freq);\n\t\t}\n\t\tbuffered.close();\n\t\tlogger.info(String.format(\"Finished reading %s (%.1f MBs)\", file, count / 1024.0 / 1024.0));\n\t\t\n\t\tlogger.info(\"Copying entity-to-anchor mappings in db...\");\n\t\tint c = 0;\n\t\tfor ( int id : entityToAnchorIDToFreqBuffer.keySet()){\n\t\t\tif (++c % 1000000 == 0)\n\t\t\t\tlogger.info(String.format(\"Copied %d entity-to-anchor mappings.\", c));\n\t\t\tInt2IntArrayMap anchorToFreq = entityToAnchorIDToFreqBuffer.get(id);\n\t\t\tint[] anchors = new int[anchorToFreq.size()];\n\t\t\tint[] frequencies = new int[anchorToFreq.size()];\n\t\t\tint idx=0;\n\t\t\tfor (Entry<Integer, Integer> p : anchorToFreq.entrySet()){\n\t\t\t\tanchors[idx] = p.getKey();\n\t\t\t\tfrequencies[idx] = p.getValue();\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\tmdb.entityToAnchorIDs.put(id, anchors);\n\t\t\tmdb.entityToFreqs.put(id, frequencies);\n\t\t}\n\t\t\n\t\tlogger.info(\"Committing changes...\");\n\t\tmdb.db.commit();\n\n\t\tlogger.info(\"Closing db...\");\n\t\tmdb.db.close();\n\t}\n\t\n\tpublic String idToAnchor(int aId){\n\t\tString anchor = aidToAnchor.get(Integer.valueOf(aId));\n\t\tif (anchor == null)\n\t\t\tthrow new RuntimeException(\"Anchor-ID \"+aId+\"not present.\");\n\t\treturn anchor;\n\t}\n\t\n\tpublic boolean containsId(int id){\n\t\treturn entityToAnchorIDs.containsKey(id);\n\t}\n\n\tpublic List<Pair<String, Integer>> getAnchors(int id, double keepFreq) {\n\t\tif (!containsId(id))\n\t\t\tthrow new RuntimeException(\"Anchors for page id=\" + id\n\t\t\t\t\t+ \" not found.\");\n\t\tint[] anchors = entityToAnchorIDs.get(id);\n\t\tint[] freqs = entityToFreqs.get(id);\n\n\t\tint totalFreq = 0;\n\t\tList<Pair<Integer, Integer>> anchorsAndFreq = new Vector<>();\n\t\tfor (int i=0; i<anchors.length; i++){\n\t\t\ttotalFreq += freqs[i];\n\t\t\tanchorsAndFreq.add(new Pair<Integer, Integer>(anchors[i], freqs[i]));\n\t\t}\n\n\t\tCollections.sort(anchorsAndFreq, new SmaphUtils.ComparePairsBySecondElement<Integer, Integer>());\n\n\t\tint gathered = 0;\n\t\tList<Pair<String, Integer>> res = new Vector<Pair<String, Integer>>();\n\t\tfor (int i = anchorsAndFreq.size() - 1; i >= 0; i--)\n\t\t\tif (gathered >= keepFreq * totalFreq)\n\t\t\t\tbreak;\n\t\t\telse {\n\t\t\t\tint aid = anchorsAndFreq.get(i).first;\n\t\t\t\tint freq = anchorsAndFreq.get(i).second;\n\t\t\t\tres.add(new Pair<String, Integer>(idToAnchor(aid), freq));\n\t\t\t\tgathered += freq;\n\t\t\t}\n\t\treturn res;\n\t}\n\n\tpublic List<Pair<String, Integer>> getAnchors(int id) {\n\t\tif (!containsId(id))\n\t\t\tthrow new RuntimeException(\"Anchors for page id=\" + id\n\t\t\t\t\t+ \" not found.\");\n\t\tint[] anchors = entityToAnchorIDs.get(id);\n\t\tint[] freqs = entityToFreqs.get(id);\n\t\t\n\t\tList<Pair<String, Integer>> res = new Vector<Pair<String,Integer>>();\n\t\tfor (int i=0; i<anchors.length; i++)\n\t\t\tres.add(new Pair<String, Integer>(idToAnchor(anchors[i]), freqs[i]));\n\t\treturn res;\n\t}\n\t\n\tpublic int getAnchorGlobalOccurrences(String anchor){\n\t\tInteger aId = anchorToAid.get(anchor);\n\t\tif (aId == null)\n\t\t\tthrow new RuntimeException(\"Anchor \"+anchor+\"not present.\");\n\t\treturn anchorToOccurrences.get(aId);\n\t}\n\t\n\tpublic double getCommonness(String anchor, int entity){\n\t\tif (!anchorToAid.containsKey(anchor))\n\t\t\treturn 0.0;\n\t\treturn ((double)getFrequency(anchor, entity)) / getAnchorGlobalOccurrences(anchor);\n\t}\n\n\tpublic double getCommonness(String anchor, int entity, int occurrences){\n\t\treturn ((double) occurrences) / getAnchorGlobalOccurrences(anchor);\n\t}\n\n\tprivate int getFrequency(String anchor, int entity) {\n\t\tif (!containsId(entity))\n\t\t\tthrow new RuntimeException(\"Anchors for page id=\" + entity\n\t\t\t\t\t+ \" not found.\");\n\t\tif (!anchorToAid.containsKey(anchor))\n\t\t\tthrow new RuntimeException(\"Anchors \"+anchor+\" not present.\");\n\t\tint aid = anchorToAid.get(anchor);\n\t\t\n\t\tint[] anchors = entityToAnchorIDs.get(entity);\n\t\tint[] freqs = entityToFreqs.get(entity);\n\t\t\n\t\tfor (int i=0; i<anchors.length; i++)\n\t\t\tif (anchors[i] == aid)\n\t\t\t\treturn freqs[i];\n\t\treturn 0;\n\t}\n\n\tpublic void dumpJson(String file) throws IOException, JSONException {\n\t\tFileWriter fw = new FileWriter(file);\n\t\tJSONWriter wr = new JSONWriter(fw);\n\t\twr.object();\n\t\tfor (int pageid : entityToAnchorIDs.getKeys()) {\n\t\t\twr.key(Integer.toString(pageid)).array();\n\t\t\tList<Pair<String, Integer>> anchorAndFreqs = getAnchors(pageid);\n\t\t\tfor (Pair<String, Integer> p: anchorAndFreqs)\n\t\t\t\twr.object().key(p.first).value(p.second).endObject();\n\t\t\twr.endArray();\n\t\t}\n\t\twr.endObject();\n\t\tfw.close();\n\t}\n\n\tpublic static void main(String[] args) throws Exception{\n\t\tlogger.info(\"Creating E2A database... \");\n\t\tcreateDB(args.length > 0 ? args[0] : DEFAULT_INPUT);\n\t\tlogger.info(\"Done.\");\n\t}\n}", "public class WikipediaToFreebase {\n\tprivate Map<String, String> map;\n\tprivate Map<String, String> labels;\n\n\tpublic static WikipediaToFreebase open(String file) {\n\t\treturn new WikipediaToFreebase(file);\n\t}\n\n\tprivate WikipediaToFreebase(String file) {\n\t\tDB db = DBMaker.fileDB(file).fileMmapEnable().readOnly().closeOnJvmShutdown().make();\n\t\tmap = db.hashMap(\"index\", Serializer.STRING, Serializer.STRING).createOrOpen();\n\t\tlabels = db.hashMap(\"label\", Serializer.STRING, Serializer.STRING).createOrOpen();\n\t}\n\n\tpublic String getLabel(String wikiid) {\n\t\twikiid = wikiid.replaceAll(\" \", \"_\");\n\t\tString freebase = map.get(wikiid);\n\t\tif (freebase == null)\n\t\t\treturn null;\n\n\t\tString label = labels.get(freebase);\n\t\treturn label;\n\t}\n\n\tpublic boolean hasEntity(String wikilabel) {\n\t\twikilabel = wikilabel.replaceAll(\" \", \"_\");\n\t\treturn map.containsKey(wikilabel);\n\t}\n\n\tpublic String getFreebaseId(String wikilabel) {\n\t\twikilabel = wikilabel.replaceAll(\" \", \"_\");\n\t\tString freebase = map.get(wikilabel);\n\t\treturn freebase;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tWikipediaToFreebase w2f = new WikipediaToFreebase(\"mapdb/freebase.db\");\n\t\tSystem.out.println(w2f.getFreebaseId(\"Diego_Maradona\"));\n\t\tSystem.out.println(w2f.getLabel(\"Diego_Maradona\"));\n\t\tSystem.out.println(w2f.getFreebaseId(\"East Ridge High School (Minnesota)\"));\n\t\tSystem.out.println(w2f.getLabel(\"East Ridge High School (Minnesota)\"));\n\t}\n\n}" ]
import it.unipi.di.acube.batframework.data.Annotation; import it.unipi.di.acube.batframework.utils.Pair; import it.unipi.di.acube.batframework.utils.WikipediaInterface; import it.unipi.di.acube.smaph.QueryInformation; import it.unipi.di.acube.smaph.SmaphUtils; import it.unipi.di.acube.smaph.WATRelatednessComputer; import it.unipi.di.acube.smaph.datasets.wikiAnchors.EntityToAnchors; import it.unipi.di.acube.smaph.datasets.wikitofreebase.WikipediaToFreebase; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Vector; import org.apache.commons.lang3.tuple.Triple;
package it.unipi.di.acube.smaph.learn.featurePacks; public class BindingFeaturePack extends FeaturePack<HashSet<Annotation>> { private static final long serialVersionUID = 1L; private static String[] ftrNames = null; public BindingFeaturePack( HashSet<Annotation> binding, String query, QueryInformation qi, WikipediaInterface wikiApi, WikipediaToFreebase w2f, EntityToAnchors e2a, HashMap<Annotation, HashMap<String, Double>> debugAnnotationFeatures, HashMap<String, Double> debugBindingFeatures){ super(getFeatures(binding, query, qi, wikiApi, w2f, e2a, debugAnnotationFeatures, debugBindingFeatures)); } public BindingFeaturePack() { super(null); } @Override public String[] getFeatureNames() { return getFeatureNamesStatic(); } public static String[] getFeatureNamesStatic() { if (ftrNames == null) { List<String> ftrNamesVect = new Vector<>(); for (String ftrName : AnnotationFeaturePack .getFeatureNamesStatic()) if (ftrName.startsWith("found_")) { ftrNamesVect.add("count_" + ftrName); } else { ftrNamesVect.add("min_" + ftrName); ftrNamesVect.add("max_" + ftrName); ftrNamesVect.add("avg_" + ftrName); } ftrNamesVect.add("min_relatedness"); ftrNamesVect.add("max_relatedness"); ftrNamesVect.add("avg_relatedness"); ftrNamesVect.add("query_tokens"); ftrNamesVect.add("annotation_count"); ftrNamesVect.add("covered_tokens"); ftrNamesVect.add("min_relatedness_mw"); ftrNamesVect.add("max_relatedness_mw"); ftrNamesVect.add("avg_relatedness_mw"); ftrNamesVect.add("segments_lp_sum"); ftrNamesVect.add("segments_lp_avg"); ftrNamesVect.add("webtotal"); ftrNamesVect.add("bolds_number"); ftrNamesVect.add("distinct_bolds"); ftrNamesVect.add("bolds_query_mined_avg"); ftrNames = ftrNamesVect.toArray(new String[] {}); } return ftrNames; } @Override public void checkFeatures(HashMap<String, Double> features) { String[] ftrNames = getFeatureNames(); for (String ftrName : features.keySet()) if (!Arrays.asList(ftrNames).contains(ftrName)) throw new RuntimeException("Feature " + ftrName + " does not exist!"); } /** * Given a list of feature vectors, return a single * feature vector (in hashmap form). This vector will contain the max, * min, and avg of for [0,1] features and the sum for counting features. * * @param allFtrVects * @return a single representation */ private static HashMap<String, Double> collapseFeatures( List<HashMap<String, Double>> allFtrVects) { // count feature presence HashMap<String, Integer> ftrCount = new HashMap<>(); for (HashMap<String, Double> ftrVectToMerge : allFtrVects) for (String ftrName : ftrVectToMerge.keySet()) { if (!ftrCount.containsKey(ftrName)) ftrCount.put(ftrName, 0); ftrCount.put(ftrName, ftrCount.get(ftrName) + 1); } // compute min, max, avg, count HashMap<String, Double> entitySetFeatures = new HashMap<>(); // Initialize sources count features to 0.0 for (String ftrName : new EntityFeaturePack().getFeatureNames()) if (ftrName.startsWith("found_")) { String key = "count_" + ftrName; entitySetFeatures.put(key, 0.0); } for (HashMap<String, Double> ftrVectToMerge : allFtrVects) { for (String ftrName : ftrVectToMerge.keySet()) { if (ftrName.startsWith("found_")) { String key = "count_" + ftrName; entitySetFeatures.put(key, entitySetFeatures.get(key) + ftrVectToMerge.get(ftrName)); } else { if (!entitySetFeatures.containsKey("min_" + ftrName)) entitySetFeatures.put("min_" + ftrName, Double.POSITIVE_INFINITY); if (!entitySetFeatures.containsKey("max_" + ftrName)) entitySetFeatures.put("max_" + ftrName, Double.NEGATIVE_INFINITY); if (!entitySetFeatures.containsKey("avg_" + ftrName)) entitySetFeatures.put("avg_" + ftrName, 0.0); double ftrValue = ftrVectToMerge.get(ftrName); entitySetFeatures.put("min_" + ftrName, Math.min( entitySetFeatures.get("min_" + ftrName), ftrValue)); entitySetFeatures.put("max_" + ftrName, Math.max( entitySetFeatures.get("max_" + ftrName), ftrValue)); entitySetFeatures.put("avg_" + ftrName, entitySetFeatures.get("avg_" + ftrName) + ftrValue / ftrCount.get(ftrName)); } } } return entitySetFeatures; } private static HashMap<String, Double> getFeatures( HashSet<Annotation> binding, String query, QueryInformation qi, WikipediaInterface wikiApi, WikipediaToFreebase w2f, EntityToAnchors e2a, HashMap<Annotation, HashMap<String, Double>> debugAnnotationFeatures, HashMap<String, Double> debugBindingFeatures) { List<HashMap<String, Double>> allAnnotationsFeatures = new Vector<>(); for (Annotation ann : binding) { HashMap<String, Double> annFeatures = AnnotationFeaturePack .getFeaturesStatic(ann, query, qi, wikiApi, w2f, e2a); allAnnotationsFeatures.add(annFeatures); if (debugAnnotationFeatures != null) debugAnnotationFeatures.put(ann, annFeatures); } /* HashSet<Tag> selectedEntities = new HashSet<>(); for (Annotation ann : binding) selectedEntities.add(new Tag(ann.getConcept())); List<HashMap<String, Double>> allEntitiesFeatures = new Vector<>(); for (Tag t : selectedEntities) allEntitiesFeatures.addAll(qi.entityToFtrVects.get(t)); */ HashMap<String, Double> bindingFeatures = collapseFeatures( allAnnotationsFeatures); /*Vector<Double> mutualInfos = new Vector<>(); for (Annotation a : binding) { Tag t = new Tag(a.getConcept()); double minED = 1.0; if (entitiesToBolds.containsKey(t)) for (String bold : entitiesToBolds.get(t)) minED = Math.min(SmaphUtils.getMinEditDist( query.substring(a.getPosition(), a.getPosition() + a.getLength()), bold), minED); mutualInfos.add(mutualInfo); } */ /*Triple<Double, Double, Double> minMaxAvgMI = getMinMaxAvg(mutualInfos); features.put("min_mutual_info", minMaxAvgMI.getLeft()); features.put("avg_mutual_info", minMaxAvgMI.getRight()); features.put("max_mutual_info", minMaxAvgMI.getMiddle());*/
bindingFeatures.put("query_tokens", (double) SmaphUtils.tokenize(query).size());
1
xoxefdp/farmacia
src/Vista/VistaUnidadesDeMedida.java
[ "public interface CerrarVentana {\r\n \r\n public abstract void cerrarVentana();\r\n}", "public interface AceptarCancelar { \r\n \r\n public abstract void aceptar();\r\n \r\n public abstract void cancelar();\r\n}", "public class OyenteAceptar implements ActionListener{\r\n \r\n AceptarCancelar eventoAceptar;\r\n \r\n public OyenteAceptar(AceptarCancelar accionAceptar){\r\n eventoAceptar = accionAceptar;\r\n }\r\n \r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n eventoAceptar.aceptar();\r\n } \r\n}", "public class OyenteCancelar implements ActionListener{\r\n \r\n AceptarCancelar eventoCancelar;\r\n \r\n public OyenteCancelar(AceptarCancelar accionCancelar){\r\n eventoCancelar = accionCancelar;\r\n }\r\n\r\n @Override\r\n public void actionPerformed(ActionEvent e) {\r\n eventoCancelar.cancelar();\r\n }\r\n}", "public class Botonera extends JPanel{ \r\n JButton[] botones;\r\n JPanel cuadroBotonera;\r\n \r\n public Botonera(int botonesBotonera){\r\n cuadroBotonera = new JPanel();\r\n cuadroBotonera.setLayout(new FlowLayout());\r\n \r\n if (botonesBotonera == 2) {\r\n botones = new JButton[2];\r\n botones[0] = new JButton(\"Aceptar\");\r\n cuadroBotonera.add(botones[0]);\r\n botones[1] = new JButton(\"Cancelar\");\r\n cuadroBotonera.add(botones[1]);\r\n }\r\n if (botonesBotonera == 3) {\r\n botones = new JButton[3];\r\n botones[0] = new JButton(\"Incluir\"); \r\n cuadroBotonera.add(botones[0]); \r\n botones[1] = new JButton(\"Modificar\");\r\n cuadroBotonera.add(botones[1]); \r\n botones[2] = new JButton(\"Eliminar\");\r\n cuadroBotonera.add(botones[2]);\r\n }\r\n add(cuadroBotonera);\r\n }\r\n\r\n public void adherirEscucha(int posBoton, ActionListener escucha){\r\n if (posBoton >= 0 && posBoton <= 2){\r\n botones[posBoton].addActionListener(escucha); \r\n }\r\n if (posBoton >= 0 && posBoton <= 1){\r\n botones[posBoton].addActionListener(escucha);\r\n }\r\n }\r\n}\r" ]
import Control.CerrarVentana; import Control.AceptarCancelar; import Control.OyenteAceptar; import Control.OyenteCancelar; import Vista.Formatos.Botonera; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextField;
package Vista; /** * * @author José Diaz */ public class VistaUnidadesDeMedida extends JDialog implements AceptarCancelar, ActionListener, CerrarVentana{ private Container contenedor; private JPanel udm; private JTextField text; private Botonera botonera; public VistaUnidadesDeMedida(){ setTitle("Unidad de Medida"); setModal(true); udm = new JPanel(); udm.setBorder(BorderFactory.createTitledBorder("Descripcion")); text = new JTextField(20); udm.add(text); add(udm, BorderLayout.NORTH); botonera = new Botonera(2); add(botonera, BorderLayout.SOUTH);
botonera.adherirEscucha(0,new OyenteAceptar(this));
2
indvd00m/java-ascii-render
ascii-render/src/main/java/com/indvd00m/ascii/render/elements/Rectangle.java
[ "public class Point implements IPoint {\n\n\tprotected int x;\n\tprotected int y;\n\n\tpublic Point(int x, int y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\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 hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\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\tPoint other = (Point) obj;\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(\"Point [x=\");\n\t\tbuilder.append(x);\n\t\tbuilder.append(\", y=\");\n\t\tbuilder.append(y);\n\t\tbuilder.append(\"]\");\n\t\treturn builder.toString();\n\t}\n\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 IContext {\n\n\t/**\n\t * Width of context.\n\t *\n\t * @return\n\t */\n\tint getWidth();\n\n\t/**\n\t * Height of context.\n\t *\n\t * @return\n\t */\n\tint getHeight();\n\n\t/**\n\t * Layers list.\n\t *\n\t * @return\n\t */\n\tList<ILayer> getLayers();\n\n\t/**\n\t * Search first element of {@code E} type (or successors of {@code E})\n\t *\n\t * @param clazz\n\t * @return\n\t */\n\t<E extends IElement> E lookup(Class<E> clazz);\n\n\t/**\n\t * Search first element of {@code E} type (optionally including successors)\n\t *\n\t * @param clazz\n\t * @return\n\t */\n\t<E extends IElement> E lookup(Class<E> clazz, boolean includeSuccessors);\n\n\t/**\n\t * Search all elements of {@code E} type (or successors of {@code E}). If elements not found, empty list will be\n\t * returned.\n\t *\n\t * @param clazz\n\t * @return\n\t */\n\t<E extends IElement> List<E> lookupAll(Class<E> clazz);\n\n\t/**\n\t * Search all elements of {@code E} type (optionally including successors). If elements not found, empty list will\n\t * be returned.\n\t *\n\t * @param clazz\n\t * @return\n\t */\n\t<E extends IElement> List<E> lookupAll(Class<E> clazz, boolean includeSuccessors);\n\n\t/**\n\t * Search first element of {@code E} type (or successors of {@code E}) in layer.\n\t *\n\t * @param clazz\n\t * @param layer\n\t * @return\n\t */\n\t<E extends IElement> E lookup(Class<E> clazz, ILayer layer);\n\n\t/**\n\t * Search first element of {@code E} type (optionally including successors) in layer.\n\t *\n\t * @param clazz\n\t * @param layer\n\t * @return\n\t */\n\t<E extends IElement> E lookup(Class<E> clazz, boolean includeSuccessors, ILayer layer);\n\n\t/**\n\t * Search all elements of {@code E} type (or successors of {@code E}) in layer. If elements not found, empty list\n\t * will be returned.\n\t *\n\t * @param clazz\n\t * @param layer\n\t * @return\n\t */\n\t<E extends IElement> List<E> lookupAll(Class<E> clazz, ILayer layer);\n\n\t/**\n\t * Search all elements of {@code E} type (optionally including successors) in layer. If elements not found, empty\n\t * list will be returned.\n\t *\n\t * @param clazz\n\t * @param layer\n\t * @return\n\t */\n\t<E extends IElement> List<E> lookupAll(Class<E> clazz, boolean includeSuccessors, ILayer layer);\n\n\t/**\n\t * Search first layer which contains {@code element}.\n\t *\n\t * @param element\n\t * @return\n\t */\n\tILayer lookupLayer(IElement element);\n\n\t/**\n\t * Search all layers which contains {@code element}. If layers not found, empty list will be returned.\n\t *\n\t * @param element\n\t * @return\n\t */\n\tList<ILayer> lookupLayers(IElement element);\n\n\t/**\n\t * Search object with type {@code T} (or successors of {@code T}) and identificator {@code typedId}. See\n\t * {@link ITypedIdentified}.\n\t *\n\t * @param type\n\t * @param typedId\n\t * @return\n\t */\n\t<T extends ITypedIdentified<T>> T lookupTyped(Class<T> type, int typedId);\n\n\t/**\n\t * Search object with type {@code T} (optionally including successors) and identificator {@code typedId}. See\n\t * {@link ITypedIdentified}.\n\t *\n\t * @param type\n\t * @param typedId\n\t * @param includeSuccessors\n\t * @return\n\t * @param <T>\n\t */\n\t<T extends ITypedIdentified<T>> T lookupTyped(Class<T> type, int typedId, boolean includeSuccessors);\n\n\t/**\n\t * Search objects with type {@code T} (or successors of {@code T}). If objects not found, empty list will be\n\t * returned. See {@link ITypedIdentified}.\n\t *\n\t * @param type\n\t * @return\n\t */\n\t<T extends ITypedIdentified<T>> List<T> lookupTyped(Class<T> type);\n\n\t/**\n\t * Search objects with type {@code T} (optionally including successors). If objects not found, empty list will be\n\t * returned. See {@link ITypedIdentified}.\n\t *\n\t * @param type\n\t * @param includeSuccessors\n\t * @return\n\t * @param <T>\n\t */\n\t<T extends ITypedIdentified<T>> List<T> lookupTyped(Class<T> type, boolean includeSuccessors);\n\n\t/**\n\t * @param element\n\t * @return true, if this context contains {@code element}.\n\t */\n\tboolean contains(IElement element);\n\n\t/**\n\t * Transform point coordinates from {@code source} coordinate system to {@code target} coordinate system.\n\t *\n\t * @param point\n\t * @param source\n\t * @param target\n\t * @return\n\t */\n\tIPoint transform(IPoint point, ILayer source, ILayer target);\n\n\t/**\n\t * Transform point coordinates from {@code source} coordinate system to {@code target} coordinate system.\n\t *\n\t * @param point\n\t * @param source\n\t * @param target\n\t * @return\n\t */\n\tIPoint transform(IPoint point, IElement source, IElement target);\n\n}", "public interface IElement {\n\n\t/**\n\t * Draw element in canvas.\n\t *\n\t * @param canvas\n\t * @param context\n\t * @return Anchor point for this element in relative coordinates of his layer. If element was not be drawn, null\n\t * must be returned.\n\t */\n\tIPoint draw(ICanvas canvas, IContext context);\n\n}", "public interface IPoint {\n\n\tint getX();\n\n\tint getY();\n\n}" ]
import com.indvd00m.ascii.render.Point; import com.indvd00m.ascii.render.api.ICanvas; import com.indvd00m.ascii.render.api.IContext; import com.indvd00m.ascii.render.api.IElement; import com.indvd00m.ascii.render.api.IPoint;
package com.indvd00m.ascii.render.elements; /** * Rectangle of a particular width and height. * * @author indvd00m (gotoindvdum[at]gmail[dot]com) * @since 0.9.0 */ public class Rectangle implements IElement { protected int x; protected int y; protected int width; protected int height; public Rectangle() { super(); this.x = Integer.MIN_VALUE; this.y = Integer.MIN_VALUE; this.width = Integer.MIN_VALUE; this.height = Integer.MIN_VALUE; } public Rectangle(int x, int y, int width, int height) { super(); this.x = x; this.y = y; this.width = width; this.height = height; } @Override
public IPoint draw(ICanvas canvas, IContext context) {
1
multi-os-engine/moe-plugin-gradle
src/main/java/org/moe/gradle/tasks/Dex2Oat.java
[ "public class MoeExtension extends AbstractMoeExtension {\n\n private static final Logger LOG = Logging.getLogger(MoeExtension.class);\n\n @NotNull\n public final PackagingOptions packaging;\n\n @NotNull\n public final ResourceOptions resources;\n\n @NotNull\n public final XcodeOptions xcode;\n\n @NotNull\n public final SigningOptions signing;\n\n @NotNull\n public final UIActionsAndOutletsOptions actionsAndOutlets;\n\n @NotNull\n public final IpaExportOptions ipaExport;\n\n @NotNull\n public final RemoteBuildOptions remoteBuildOptions;\n\n @NotNull\n private MoePlatform platform = MoePlatform.IOS;\n\n @NotNull\n public final ProGuardOptions proguard;\n\n public MoeExtension(@NotNull MoePlugin plugin, @NotNull Instantiator instantiator) {\n super(plugin, instantiator);\n this.packaging = instantiator.newInstance(PackagingOptions.class);\n this.resources = instantiator.newInstance(ResourceOptions.class);\n this.xcode = instantiator.newInstance(XcodeOptions.class);\n this.signing = instantiator.newInstance(SigningOptions.class);\n this.actionsAndOutlets = instantiator.newInstance(UIActionsAndOutletsOptions.class);\n this.ipaExport = instantiator.newInstance(IpaExportOptions.class);\n this.remoteBuildOptions = instantiator.newInstance(RemoteBuildOptions.class);\n this.proguard = instantiator.newInstance(ProGuardOptions.class);\n }\n\n void setup() {}\n\n @IgnoreUnused\n public void packaging(Action<PackagingOptions> action) {\n Require.nonNull(action).execute(packaging);\n }\n\n @IgnoreUnused\n public void resources(Action<ResourceOptions> action) {\n Require.nonNull(action).execute(resources);\n }\n\n @IgnoreUnused\n public void xcode(Action<XcodeOptions> action) {\n Require.nonNull(action).execute(xcode);\n }\n\n @IgnoreUnused\n public void signing(Action<SigningOptions> action) {\n Require.nonNull(action).execute(signing);\n }\n\n @IgnoreUnused\n public void actionsAndOutlets(Action<UIActionsAndOutletsOptions> action) {\n Require.nonNull(action).execute(actionsAndOutlets);\n }\n\n @IgnoreUnused\n public void ipaExport(Action<IpaExportOptions> action) {\n Require.nonNull(action).execute(ipaExport);\n }\n\n @IgnoreUnused\n public void remoteBuild(Action<RemoteBuildOptions> action) {\n Require.nonNull(action).execute(remoteBuildOptions);\n }\n\n @IgnoreUnused\n public void proguard(Action<ProGuardOptions> action) {\n Require.nonNull(action).execute(proguard);\n }\n\n @NotNull\n @IgnoreUnused\n public String getPlatform() {\n return Require.nonNull(platform).displayName;\n }\n\n @NotNull\n public MoePlatform getPlatformType() {\n return Require.nonNull(platform);\n }\n\n @IgnoreUnused\n public void setPlatform(@NotNull String platform) {\n this.platform = MoePlatform.getForDisplayName(platform);\n }\n\n @NotNull\n @IgnoreUnused\n @Deprecated\n public String getProguardLevel() {\n LOG.warn(\"The 'getProguardLevel' is deprecated, please use 'proguard.level' instead!\");\n return proguard.getLevel();\n }\n\n @IgnoreUnused\n @Deprecated\n public void setProguardLevel(@NotNull String proguardLevel) {\n LOG.warn(\"The 'setProguardLevel' is deprecated, please use 'proguard.level' instead!\");\n proguard.setLevel(proguardLevel);\n }\n\n @Nullable\n public File getPlatformJar() {\n return plugin.getSDK().getPlatformJar(platform);\n }\n\n @Nullable\n public File getPlatformDex() {\n return plugin.getSDK().getPlatformDex(platform);\n }\n}", "public class MoePlugin extends AbstractMoePlugin {\n\n private static final Logger LOG = Logging.getLogger(MoePlugin.class);\n\n private static final String MOE_ARCHS_PROPERTY = \"moe.archs\";\n\n @NotNull\n private MoeExtension extension;\n\n @NotNull\n @Override\n public MoeExtension getExtension() {\n return Require.nonNull(extension, \"The plugin's 'extension' property was null\");\n }\n\n @Nullable\n private Server remoteServer;\n\n @Nullable\n public Server getRemoteServer() {\n return remoteServer;\n }\n\n @Nullable\n private Set<Arch> archs = null;\n\n @Nullable\n public Set<Arch> getArchs() {\n return archs;\n }\n\n @Inject\n public MoePlugin(Instantiator instantiator, ToolingModelBuilderRegistry registry) {\n super(instantiator, registry, false);\n }\n\n @Override\n public void apply(Project project) {\n super.apply(project);\n\n // Setup explicit archs\n String archsProp = PropertiesUtil.tryGetProperty(project, MOE_ARCHS_PROPERTY);\n if (archsProp != null) {\n archsProp = archsProp.trim();\n archs = Arrays.stream(archsProp.split(\",\"))\n .map(String::trim)\n .filter(it -> !it.isEmpty())\n .map(Arch::getForName)\n .collect(Collectors.toSet());\n\n if (archs.isEmpty()) {\n archs = null;\n }\n }\n\n // Setup remote build\n remoteServer = Server.setup(this);\n if (remoteServer != null) {\n remoteServer.connect();\n }\n\n // Create plugin extension\n extension = project.getExtensions().create(MOE, MoeExtension.class, this, instantiator);\n extension.setup();\n\n // Add common MOE dependencies\n installCommonDependencies();\n\n // Install rules\n addRule(ProGuard.class, \"Creates a ProGuarded jar.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(ClassValidate.class, \"Validate classes.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(Dex.class, \"Creates a Dexed jar.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(Dex2Oat.class, \"Creates art and oat files.\",\n asList(SOURCE_SET, MODE, ARCH_FAMILY), MoePlugin.this);\n ResourcePackager.addRule(this);\n addRule(TestClassesProvider.class, \"Creates the classlist.txt file.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(StartupProvider.class, \"Creates the preregister.txt file.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(XcodeProvider.class, \"Collects the required dependencies.\",\n asList(SOURCE_SET, MODE, ARCH, PLATFORM), MoePlugin.this);\n addRule(XcodeInternal.class, \"Creates all files for Xcode.\",\n emptyList(), MoePlugin.this);\n addRule(XcodeBuild.class, \"Creates .app files.\",\n asList(SOURCE_SET, MODE, PLATFORM), MoePlugin.this);\n addRule(IpaBuild.class, \"Creates .ipa files.\",\n emptyList(), MoePlugin.this);\n addRule(GenerateUIObjCInterfaces.class, \"Creates a source file for Interface Builder\",\n singletonList(MODE), MoePlugin.this);\n addRule(NatJGen.class, \"Generate binding\",\n emptyList(), MoePlugin.this);\n addRule(UpdateXcodeSettings.class, \"Updates Xcode project settings\",\n emptyList(), MoePlugin.this);\n\n project.getTasks().create(\"moeSDKProperties\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Prints some properties of the MOE SDK.\");\n task.getActions().add(t -> {\n final File platformJar = extension.getPlatformJar();\n LOG.quiet(\"\\n\" +\n \"moe.sdk.home=\" + getSDK().getRoot() + \"\\n\" +\n \"moe.sdk.coreJar=\" + getSDK().getCoreJar() + \"\\n\" +\n \"moe.sdk.platformJar=\" + (platformJar == null ? \"\" : platformJar) + \"\\n\" +\n \"moe.sdk.junitJar=\" + getSDK().getiOSJUnitJar() + \"\\n\" +\n \"\\n\");\n });\n });\n project.getTasks().create(\"moeXcodeProperties\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Prints some properties of the MOE Xcode project.\");\n task.getActions().add(t -> {\n final StringBuilder b = new StringBuilder(\"\\n\");\n Optional.ofNullable(extension.xcode.getProject()).ifPresent(\n o -> b.append(\"moe.xcode.project=\").append(project.file(o).getAbsolutePath()).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getWorkspace()).ifPresent(\n o -> b.append(\"moe.xcode.workspace=\").append(project.file(o).getAbsolutePath()).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getMainTarget()).ifPresent(\n o -> b.append(\"moe.xcode.mainTarget=\").append(o).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getTestTarget()).ifPresent(\n o -> b.append(\"moe.xcode.testTarget=\").append(o).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getMainScheme()).ifPresent(\n o -> b.append(\"moe.xcode.mainScheme=\").append(o).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getTestScheme()).ifPresent(\n o -> b.append(\"moe.xcode.testScheme=\").append(o).append(\"\\n\"));\n b.append(\"\\n\");\n LOG.quiet(b.toString());\n });\n });\n\n Launchers.addTasks(this);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static String getTaskName(@NotNull Class<?> taskClass, @NotNull Object... params) {\n Require.nonNull(taskClass);\n Require.nonNull(params);\n\n final String TASK_CLASS_NAME = taskClass.getSimpleName();\n final String ELEMENTS_DESC = Arrays.stream(params).map(TaskParams::getNameForValue).collect(Collectors.joining());\n\n return MOE + ELEMENTS_DESC + TASK_CLASS_NAME;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T extends AbstractBaseTask> T getTaskBy(@NotNull Class<T> taskClass, @NotNull Object... params) {\n return (T) getProject().getTasks().getByName(getTaskName(taskClass, params));\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T extends Task> T getTaskByName(@NotNull String name) {\n Require.nonNull(name);\n\n return (T) getProject().getTasks().getByName(name);\n }\n\n public void requireMacHostOrRemoteServerConfig(@NotNull Task task) {\n Require.nonNull(task);\n if (!Os.isFamily(Os.FAMILY_MAC) && getRemoteServer() == null) {\n throw new GradleException(\"The '\" + task.getName() + \"' task requires a macOS host or a remote build configuration.\");\n }\n }\n\n @Override\n protected void checkRemoteServer(AbstractBaseTask task) {\n if (getRemoteServer() != null && task.getRemoteExecutionStatusSet()) {\n task.dependsOn(getRemoteServer().getMoeRemoteServerSetupTask());\n }\n }\n}", "public class MoeSDK {\n private static final Logger LOG = Logging.getLogger(MoeSDK.class);\n\n private static final String MOE_GRADLE_ARTIFACT_ID = \"moe-gradle\";\n private static final String MOE_SDK_CONFIGURATION_NAME = \"moeMavenSDK\";\n private static final String MOE_LOCAL_SDK_PROPERTY = \"moe.sdk.localbuild\";\n private static final String MOE_LOCAL_SDK_ENV = \"MOE_SDK_LOCALBUILD\";\n private static final String MOE_GROUP_ID = \"org.multi-os-engine\";\n private static final String MOE_SDK_ARTIFACT_ID = \"moe-sdk\";\n\n public static final Path USER_MOE_HOME;\n\n static {\n final String user_moe_home = System.getenv(\"USER_MOE_HOME\");\n if (user_moe_home != null && user_moe_home.length() > 0) {\n USER_MOE_HOME = new File(user_moe_home).toPath();\n } else {\n USER_MOE_HOME = new File(System.getProperty(\"user.home\")).toPath().resolve(\".moe\");\n }\n }\n\n private static final int DIR = 1 << 0;\n private static final int FIL = 1 << 1;\n private static final int EXE = 1 << 2;\n\n @NotNull\n public final String pluginVersion;\n\n @NotNull\n public final String sdkVersion;\n\n private MoeSDK(@NotNull String pluginVersion, @NotNull String sdkVersion) {\n this.pluginVersion = Require.nonNull(pluginVersion);\n this.sdkVersion = Require.nonNull(sdkVersion);\n }\n\n public static MoeSDK setup(@NotNull AbstractMoePlugin plugin) {\n Require.nonNull(plugin);\n final Project project = plugin.getProject();\n\n Configuration classpathConfiguration =\n project.getBuildscript().getConfigurations().getByName(\"classpath\");\n Require.nonNull(classpathConfiguration, \"Couldn't find the classpath configuration in the buildscript.\");\n\n // Check if explicit SDK version is defined.\n String sdkVersion = getMoeSDKVersion(project);\n if (sdkVersion == null) {\n // There's no explicit SDK version, retrieving version\n // from moe.properties.\n {\n // Get SDK version from moe.properties\n final Properties props = new Properties();\n try {\n props.load(MoeSDK.class.getResourceAsStream(\"moe.properties\"));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n sdkVersion = props.getProperty(\"MOE-SDK-Version\");\n }\n if (sdkVersion == null || sdkVersion.length() == 0) {\n throw new GradleException(\"MOE SDK version is undefined\");\n }\n\n LOG.info(\"Using implicit moe-sdk version: {}\", sdkVersion);\n } else {\n LOG.info(\"Using explicit moe-sdk version: {}\", sdkVersion);\n }\n\n // Retrieve and resolve the moe-gradle plugin version.\n ResolvedArtifact artifact;\n {\n Project classpathProject = project;\n while ((artifact = classpathConfiguration.getResolvedConfiguration().getResolvedArtifacts()\n .stream()\n .filter(p -> MOE_GRADLE_ARTIFACT_ID.equals(p.getName()))\n .findAny()\n .orElse(null)) == null) {\n classpathProject = classpathProject.getParent();\n if (classpathProject == null) {\n break;\n }\n classpathConfiguration = classpathProject.getBuildscript().getConfigurations().getByName(\"classpath\");\n Require.nonNull(classpathConfiguration, \"Couldn't find the classpath configuration in the buildscript.\");\n }\n }\n Require.nonNull(artifact, \"Couldn't find the moe-gradle artifact.\");\n final String pluginVersion = artifact.getModuleVersion().getId().getVersion();\n Require.nonNull(pluginVersion, \"Couldn't resolve the version of the moe-gradle artifact.\");\n LOG.info(\"Resolved moe-gradle version: {}\", pluginVersion);\n\n // Check for overriding property\n final String p = PropertiesUtil.tryGetProperty(project, MOE_LOCAL_SDK_PROPERTY);\n if (p != null) {\n final Path path = Paths.get(p);\n LOG.quiet(\"Using custom local MOE SDK: {}\", path.toFile().getAbsolutePath());\n // Construct the SDK.\n final MoeSDK sdk = new MoeSDK(pluginVersion, sdkVersion);\n sdk.validateSDK(path, true);\n sdk.bakeSDKPaths(path);\n return sdk;\n }\n\n // Check for overriding environment variable\n if (System.getenv(MOE_LOCAL_SDK_ENV) != null) {\n final Path path = Paths.get(System.getenv(MOE_LOCAL_SDK_ENV));\n LOG.quiet(\"Using custom local MOE SDK (env): {}\", path.toFile().getAbsolutePath());\n // Construct the SDK.\n final MoeSDK sdk = new MoeSDK(pluginVersion, sdkVersion);\n sdk.validateSDK(path, true);\n sdk.bakeSDKPaths(path);\n return sdk;\n }\n\n // Check if moe.sdk.localbuild file exists.\n if (plugin.getProject().file(\"moe.sdk.localbuild\").exists()) {\n final Path path = Paths.get(FileUtils.read(plugin.getProject().file(\"moe.sdk.localbuild\")).trim());\n LOG.quiet(\"Using custom local MOE SDK (file): {}\", path.toFile().getAbsolutePath());\n // Construct the SDK.\n final MoeSDK sdk = new MoeSDK(pluginVersion, sdkVersion);\n sdk.validateSDK(path, true);\n sdk.bakeSDKPaths(path);\n return sdk;\n }\n\n // Use configuration\n LOG.info(\"Using Maven-based MOE SDK\");\n\n // We need a resolved SDK version which is required as a part of the SDK path.\n sdkVersion = resolveSDKVersion(project, sdkVersion);\n LOG.info(\"Resolved moe-sdk version: {}\", sdkVersion);\n\n // Construct the SDK.\n final MoeSDK sdk = new MoeSDK(pluginVersion, sdkVersion);\n\n // Prepare USER_MOE_HOME\n if (!USER_MOE_HOME.toFile().exists() && !USER_MOE_HOME.toFile().mkdir()) {\n throw new GradleException(\"Failed to create directory at \" + USER_MOE_HOME);\n }\n\n // If the required SDK version is already downloaded and not a snapshot (because snapshot versions\n // can't be reused due to it's version can't be checked), use it and return.\n final boolean isSnapshotSDKVersion = sdkVersion.endsWith(\"-SNAPSHOT\");\n final Path SDK_PATH = USER_MOE_HOME.resolve(\"moe-sdk-\" + sdkVersion);\n if (SDK_PATH.toFile().exists() && !isSnapshotSDKVersion) {\n LOG.quiet(\"Using already downloaded SDK: {}\", SDK_PATH.toFile().getAbsolutePath());\n sdk.validateSDK(SDK_PATH, false);\n sdk.bakeSDKPaths(SDK_PATH);\n return sdk;\n }\n\n // Download the SDK from the repositories.\n final File file = sdk.downloadSDK(project, sdkVersion);\n\n // Calculate MD5 on the SDK.\n final AtomicReference<String> sdkCalculatedMD5Ref = new AtomicReference<>();\n final File md5CacheFile = SDK_PATH.resolve(\"sdk.md5\").toFile();\n final boolean sdkUpToDate = checkComponentUpToDate(file, md5CacheFile, sdkCalculatedMD5Ref);\n if (SDK_PATH.toFile().exists() && isSnapshotSDKVersion) {\n if (sdkUpToDate) {\n LOG.quiet(\"Using already downloaded SDK: {}\", SDK_PATH.toFile().getAbsolutePath());\n sdk.validateSDK(SDK_PATH, false);\n sdk.bakeSDKPaths(SDK_PATH);\n return sdk;\n } else {\n try {\n FileUtils.deleteFileOrFolder(SDK_PATH);\n LOG.info(\"Deleted existing SDK: {}\", SDK_PATH.toFile().getAbsolutePath());\n } catch (IOException e) {\n throw new GradleException(\"Failed to remove directory at \" + SDK_PATH.toFile().getAbsolutePath(), e);\n }\n }\n }\n\n // Prepare temp dir by removing old tmp directory and re-creating it\n LOG.quiet(\"Installing MOE SDK ({}), this may take a few minutes...\", sdkVersion);\n\n // Extract zip into the temp directory\n project.copy(spec -> {\n spec.from(project.zipTree(file));\n spec.into(SDK_PATH.toFile());\n });\n\n if (isSnapshotSDKVersion && sdkCalculatedMD5Ref.get() != null) {\n // Cache md5\n try {\n FileUtils.deleteFileOrFolder(md5CacheFile);\n } catch (IOException e) {\n throw new GradleException(\"Failed to delete file \" + md5CacheFile, e);\n }\n FileUtils.write(md5CacheFile, sdkCalculatedMD5Ref.get());\n }\n\n // Validate files\n sdk.validateSDK(SDK_PATH, false);\n sdk.bakeSDKPaths(SDK_PATH);\n return sdk;\n }\n\n private static String getMoeSDKVersion(@NotNull Project project) {\n final ExtraPropertiesExtension extraProperties = project.getExtensions().getExtraProperties();\n if (!extraProperties.has(\"moeSDKVersion\")) {\n return null;\n }\n final Object moeSDKVersion = extraProperties.get(\"moeSDKVersion\");\n if (moeSDKVersion == null) {\n throw new GradleException(\"'moeSDKVersion' property cannot be null\");\n }\n if (!(moeSDKVersion instanceof String)) {\n throw new GradleException(\"'moeSDKVersion' property must be a string\");\n }\n if (\"\".equals((String) moeSDKVersion)) {\n throw new GradleException(\"'moeSDKVersion' property must not be an empty string\");\n }\n return (String)moeSDKVersion;\n }\n\n private static boolean checkComponentUpToDate(File input, File md5file, AtomicReference<String> out) {\n final String calculatedMD5;\n try {\n calculatedMD5 = DigestUtils.md5Hex(new FileInputStream(input)).trim();\n } catch (IOException ignore) {\n throw new GradleException(ignore.getMessage(), ignore);\n }\n out.set(calculatedMD5);\n\n if (!md5file.exists()) {\n return false;\n }\n final String cachedMD5 = FileUtils.read(md5file);\n return cachedMD5.length() != 0 && cachedMD5.trim().equalsIgnoreCase(calculatedMD5);\n }\n\n private static <T> T createSDKArtifact(@NotNull Project project, String version, BiFunction<Configuration, ExternalDependency, T> consumer) {\n Require.nonNull(project);\n Require.nonNull(version);\n final String desc = MOE_GROUP_ID + \":\" + MOE_SDK_ARTIFACT_ID + \":\" + version + \"@zip\";\n\n // Get or create configuration\n Configuration configuration;\n ExternalDependency dependency;\n try {\n configuration = project.getConfigurations().getByName(MOE_SDK_CONFIGURATION_NAME);\n Require.EQ(configuration.getDependencies().size(), 1,\n \"Unexpected number of dependencies in moeSDK configuration.\");\n dependency = (ExternalDependency)configuration.getDependencies().iterator().next();\n } catch (UnknownConfigurationException ex) {\n configuration = project.getConfigurations().create(MOE_SDK_CONFIGURATION_NAME);\n // Create an external dependency\n dependency = (ExternalDependency)project.getDependencies().create(desc);\n configuration.getDependencies().add(dependency);\n }\n\n // Add repositories from the buildscript to be able to download the SDK\n Set<ArtifactRepository> addedRepositories = new HashSet<>();\n project.getBuildscript().getRepositories().forEach(repository -> {\n if (!project.getRepositories().contains(repository)) {\n project.getRepositories().add(repository);\n addedRepositories.add(repository);\n }\n });\n\n try {\n return consumer.apply(configuration, dependency);\n } finally {\n // Remove added repositories\n project.getRepositories().removeAll(addedRepositories);\n }\n }\n\n private static String resolveSDKVersion(@NotNull Project project, String version) {\n return createSDKArtifact(project, version, (config, dep) -> {\n ResolvedArtifact artifact = config.getResolvedConfiguration().getResolvedArtifacts()\n .stream()\n .filter(p -> MOE_SDK_ARTIFACT_ID.equals(p.getName()))\n .findAny()\n .orElse(null);\n Require.nonNull(artifact, \"Couldn't find the \" + MOE_SDK_ARTIFACT_ID + \" artifact.\");\n final String sdkVersion = artifact.getModuleVersion().getId().getVersion();\n Require.nonNull(sdkVersion, \"Couldn't resolve the version of the \" + MOE_SDK_ARTIFACT_ID + \" artifact.\");\n return sdkVersion;\n });\n }\n\n @NotNull\n private File downloadSDK(@NotNull Project project, String version) {\n Require.nonNull(project);\n Require.nonNull(version);\n\n final String desc = MOE_GROUP_ID + \":\" + MOE_SDK_ARTIFACT_ID + \":\" + version + \"@zip\";\n LOG.info(\"Downloading dependency \" + desc);\n\n final Set<File> files = createSDKArtifact(project, version, (config, dep) -> {\n return config.files(dep);\n });\n\n // Return the SDK\n return Require.sizeEQ(files, 1, \"Unexpected number of files in MOE SDK\").iterator().next();\n }\n\n private void validateSDK(@NotNull Path path, boolean isLocalSDK) {\n Require.nonNull(path);\n\n try {\n validate(DIR, path, \"\");\n validate(FIL, path, \"sdk/moe-core.dex\");\n validate(FIL, path, \"sdk/moe-core.jar\");\n validate(FIL, path, \"sdk/moe-core-javadoc.jar\");\n validate(FIL, path, \"sdk/moe-core-sources.jar\");\n\n validate(FIL, path, \"sdk/moe-ios-junit.dex\");\n validate(FIL, path, \"sdk/moe-ios-junit.jar\");\n validate(FIL, path, \"sdk/moe-ios-junit-javadoc.jar\");\n validate(FIL, path, \"sdk/moe-ios-junit-sources.jar\");\n\n validate(FIL, path, \"sdk/moe-ios-dex.jar\");\n validate(FIL, path, \"sdk/moe-ios.jar\");\n validate(FIL, path, \"sdk/moe-ios-javadoc.jar\");\n validate(FIL, path, \"sdk/moe-ios-sources.jar\");\n\n if (!isLocalSDK) {\n validate(DIR, path, \"sdk/iphoneos/MOE.framework\");\n validate(DIR, path, \"sdk/iphonesimulator/MOE.framework\");\n }\n\n validate(FIL | EXE, path, \"tools/dex2oat\");\n validate(FIL, path, \"tools/dx.jar\");\n validate(FIL, path, \"tools/ios-device.jar\");\n validate(FIL, path, \"tools/java8support.jar\");\n validate(DIR, path, \"tools/macosx\");\n validate(FIL, path, \"tools/preloaded-classes\");\n validate(FIL, path, \"tools/proguard-full.cfg\");\n validate(FIL, path, \"tools/proguard.cfg\");\n validate(FIL, path, \"tools/proguard.jar\");\n validate(DIR, path, \"tools/windows/x86_64\");\n validate(FIL, path, \"tools/wrapnatjgen.jar\");\n validate(FIL, path, \"tools/gradlew.zip\");\n } catch (IOException ex) {\n LOG.error(\"Error: failed to validate MOE SDK, \" + ex.getMessage());\n throw new GradleException(\"MOE SDK is probably damaged, please remove it manually from \" + path);\n }\n }\n\n private void validate(int type, @NotNull Path path, @NotNull String sub) throws IOException {\n Require.nonNull(path);\n Require.nonNull(sub);\n\n final Path fullPath = sub.length() == 0 ? path : path.resolve(sub);\n final File file = fullPath.toFile();\n if (!file.exists()) {\n throw new IOException(\"no filesystem entry exists at \" + file.getAbsolutePath());\n }\n if ((type & DIR) != 0 && !file.isDirectory()) {\n throw new IOException(\"expected a directory at \" + file.getAbsolutePath());\n }\n if ((type & FIL) != 0 && !file.isFile()) {\n throw new IOException(\"expected a file at \" + file.getAbsolutePath());\n }\n if ((type & EXE) != 0 && !file.canExecute() && !file.setExecutable(true)) {\n throw new IOException(\"file is not executable at \" + file.getAbsolutePath());\n }\n }\n\n private @Nullable File MOE_SDK_ROOT;\n private @Nullable File MOE_SDK_SDK_DIR;\n private @Nullable File MOE_SDK_TOOLS_DIR;\n private @Nullable File MOE_SDK_CORE_JAR;\n private @Nullable File MOE_SDK_CORE_SOURCES_JAR;\n private @Nullable File MOE_SDK_CORE_JAVADOC_JAR;\n private @Nullable File MOE_SDK_CORE_DEX;\n private @Nullable File MOE_SDK_IOS_JAVADOC_JAR;\n private @Nullable File MOE_SDK_IOS_JUNIT_JAR;\n private @Nullable File MOE_SDK_IOS_JUNIT_SOURCES_JAR;\n private @Nullable File MOE_SDK_IOS_JUNIT_JAVADOC_JAR;\n private @Nullable File MOE_SDK_IOS_JUNIT_DEX;\n private @Nullable File MOE_SDK_IOS_JAR;\n private @Nullable File MOE_SDK_IOS_SOURCES_JAR;\n private @Nullable File MOE_SDK_IOS_DEX;\n private @Nullable File MOE_SDK_DEX2OAT_EXEC;\n private @Nullable File MOE_SDK_DX_JAR;\n private @Nullable File MOE_SDK_IOS_DEVICE_JAR;\n private @Nullable File MOE_SDK_JAVA8SUPPORT_JAR;\n private @Nullable File MOE_SDK_MACOS_SUPPORT;\n private @Nullable File MOE_SDK_PRELOADEDCLASSES_FILE;\n private @Nullable File MOE_SDK_PROGUARDFULL_CFG;\n private @Nullable File MOE_SDK_PROGUARD_CFG;\n private @Nullable File MOE_SDK_PROGUARD_JAR;\n private @Nullable File MOE_SDK_WINDOWS_X86_64_SUPPORT;\n private @Nullable File MOE_SDK_NATJGEN_JAR;\n private @Nullable File MOE_SDK_GRADLEW_ZIP;\n\n private void bakeSDKPaths(@NotNull Path path) {\n MOE_SDK_ROOT = path.toFile();\n MOE_SDK_SDK_DIR = path.resolve(\"sdk\").toFile();\n MOE_SDK_TOOLS_DIR = path.resolve(\"tools\").toFile();\n MOE_SDK_CORE_JAR = path.resolve(\"sdk/moe-core.jar\").toFile();\n MOE_SDK_CORE_DEX = path.resolve(\"sdk/moe-core.dex\").toFile();\n MOE_SDK_CORE_SOURCES_JAR = path.resolve(\"sdk/moe-core-sources.jar\").toFile();\n MOE_SDK_CORE_JAVADOC_JAR = path.resolve(\"sdk/moe-core-javadoc.jar\").toFile();\n MOE_SDK_IOS_DEX = path.resolve(\"sdk/moe-ios-dex.jar\").toFile();\n MOE_SDK_IOS_JAR = path.resolve(\"sdk/moe-ios.jar\").toFile();\n MOE_SDK_IOS_SOURCES_JAR = path.resolve(\"sdk/moe-ios-sources.jar\").toFile();\n MOE_SDK_IOS_JAVADOC_JAR = path.resolve(\"sdk/moe-ios-javadoc.jar\").toFile();\n MOE_SDK_IOS_JUNIT_JAR = path.resolve(\"sdk/moe-ios-junit.jar\").toFile();\n MOE_SDK_IOS_JUNIT_DEX = path.resolve(\"sdk/moe-ios-junit.dex\").toFile();\n MOE_SDK_IOS_JUNIT_SOURCES_JAR = path.resolve(\"sdk/moe-ios-junit-sources.jar\").toFile();\n MOE_SDK_IOS_JUNIT_JAVADOC_JAR = path.resolve(\"sdk/moe-ios-junit-javadoc.jar\").toFile();\n MOE_SDK_DEX2OAT_EXEC = path.resolve(\"tools/dex2oat\").toFile();\n MOE_SDK_DX_JAR = path.resolve(\"tools/dx.jar\").toFile();\n MOE_SDK_IOS_DEVICE_JAR = path.resolve(\"tools/ios-device.jar\").toFile();\n MOE_SDK_JAVA8SUPPORT_JAR = path.resolve(\"tools/java8support.jar\").toFile();\n MOE_SDK_MACOS_SUPPORT = path.resolve(\"tools/macosx\").toFile();\n MOE_SDK_PRELOADEDCLASSES_FILE = path.resolve(\"tools/preloaded-classes\").toFile();\n MOE_SDK_PROGUARDFULL_CFG = path.resolve(\"tools/proguard-full.cfg\").toFile();\n MOE_SDK_PROGUARD_CFG = path.resolve(\"tools/proguard.cfg\").toFile();\n MOE_SDK_PROGUARD_JAR = path.resolve(\"tools/proguard.jar\").toFile();\n MOE_SDK_WINDOWS_X86_64_SUPPORT = path.resolve(\"tools/windows/x86_64\").toFile();\n MOE_SDK_NATJGEN_JAR = path.resolve(\"tools/wrapnatjgen.jar\").toFile();\n MOE_SDK_GRADLEW_ZIP = path.resolve(\"tools/gradlew.zip\").toFile();\n }\n\n @NotNull\n public File getRoot() {\n return safeVariable(MOE_SDK_ROOT, \"MOE_SDK_ROOT\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getSDKDir() {\n return safeVariable(MOE_SDK_SDK_DIR, \"MOE_SDK_SDK_DIR\");\n }\n\n @NotNull\n public File getToolsDir() {\n return safeVariable(MOE_SDK_TOOLS_DIR, \"MOE_SDK_TOOLS_DIR\");\n }\n\n @NotNull\n public File getCoreJar() {\n return safeVariable(MOE_SDK_CORE_JAR, \"MOE_SDK_CORE_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getCoreJavadocJar() {\n return safeVariable(MOE_SDK_CORE_JAVADOC_JAR, \"MOE_SDK_CORE_JAVADOC_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getCoreSourcesJar() {\n return safeVariable(MOE_SDK_CORE_SOURCES_JAR, \"MOE_SDK_CORE_SOURCES_JAR\");\n }\n\n @NotNull\n public File getCoreDex() {\n return safeVariable(MOE_SDK_CORE_DEX, \"MOE_SDK_CORE_DEX\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getiOSJavadocJar() {\n return safeVariable(MOE_SDK_IOS_JAVADOC_JAR, \"MOE_SDK_IOS_JAVADOC_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getiOSSourcesJar() {\n return safeVariable(MOE_SDK_IOS_SOURCES_JAR, \"MOE_SDK_IOS_SOURCES_JAR\");\n }\n\n @NotNull\n public File getiOSJUnitJar() {\n return safeVariable(MOE_SDK_IOS_JUNIT_JAR, \"MOE_SDK_IOS_JUNIT_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getiOSJUnitJavadocJar() {\n return safeVariable(MOE_SDK_IOS_JUNIT_JAVADOC_JAR, \"MOE_SDK_IOS_JUNIT_JAVADOC_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getiOSJUnitSourcesJar() {\n return safeVariable(MOE_SDK_IOS_JUNIT_SOURCES_JAR, \"MOE_SDK_IOS_JUNIT_SOURCES_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getiOSJUnitDex() {\n return safeVariable(MOE_SDK_IOS_JUNIT_DEX, \"MOE_SDK_IOS_JUNIT_DEX\");\n }\n\n @NotNull\n private File getiOSJar() {\n return safeVariable(MOE_SDK_IOS_JAR, \"MOE_SDK_IOS_JAR\");\n }\n\n @NotNull\n private File getiOSDex() {\n return safeVariable(MOE_SDK_IOS_DEX, \"MOE_SDK_IOS_DEX\");\n }\n\n @NotNull\n public File getDex2OatExec() {\n return safeVariable(MOE_SDK_DEX2OAT_EXEC, \"MOE_SDK_DEX2OAT_EXEC\");\n }\n\n @NotNull\n public File getDxJar() {\n return safeVariable(MOE_SDK_DX_JAR, \"MOE_SDK_DX_JAR\");\n }\n\n @NotNull\n public File getiOSDeviceJar() {\n return safeVariable(MOE_SDK_IOS_DEVICE_JAR, \"MOE_SDK_IOS_DEVICE_JAR\");\n }\n\n @NotNull\n public File getJava8SupportJar() {\n return safeVariable(MOE_SDK_JAVA8SUPPORT_JAR, \"MOE_SDK_JAVA8SUPPORT_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getMacOS_Support() {\n return safeVariable(MOE_SDK_MACOS_SUPPORT, \"MOE_SDK_MACOS_SUPPORT\");\n }\n\n @NotNull\n public File getPreloadedClassesFile() {\n return safeVariable(MOE_SDK_PRELOADEDCLASSES_FILE, \"MOE_SDK_PRELOADEDCLASSES_FILE\");\n }\n\n @NotNull\n public File getProguardFullCfg() {\n return safeVariable(MOE_SDK_PROGUARDFULL_CFG, \"MOE_SDK_PROGUARDFULL_CFG\");\n }\n\n @NotNull\n public File getProguardCfg() {\n return safeVariable(MOE_SDK_PROGUARD_CFG, \"MOE_SDK_PROGUARD_CFG\");\n }\n\n @NotNull\n public File getProGuardJar() {\n return safeVariable(MOE_SDK_PROGUARD_JAR, \"MOE_SDK_PROGUARD_JAR\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getWindows_X86_64Support() {\n return safeVariable(MOE_SDK_WINDOWS_X86_64_SUPPORT, \"MOE_SDK_WINDOWS_X86_64_SUPPORT\");\n }\n\n @NotNull\n @IgnoreUnused\n public File getNatJGenJar() {\n return safeVariable(MOE_SDK_NATJGEN_JAR, \"MOE_SDK_NATJGEN_JAR\");\n }\n\n @NotNull\n public File getGradlewZip() {\n return safeVariable(MOE_SDK_GRADLEW_ZIP, \"MOE_SDK_GRADLEW_ZIP\");\n }\n\n @NotNull\n public File getPlatformJar(final @NotNull MoePlatform platform) {\n if (platform == MoePlatform.IOS) {\n return getiOSJar();\n }\n throw new GradleException(\"platform jar is unsupported for \" + platform.displayName);\n }\n\n @NotNull\n public File getPlatformDex(final @NotNull MoePlatform platform) {\n if (platform == MoePlatform.IOS) {\n return getiOSDex();\n }\n throw new GradleException(\"platform dex is unsupported for \" + platform.displayName);\n }\n\n @NotNull\n private static <T> T safeVariable(@Nullable T variable, @NotNull String name) {\n return Require.nonNull(variable, \"Unable to access MOE SDK variable '\" + name + \"'\");\n }\n}", "public class ProGuardOptions {\n\n public static final int LEVEL_APP = 0;\n public static final int LEVEL_PLATFORM = 1;\n public static final int LEVEL_ALL = 2;\n\n private static final String LEVEL_APP_STRING = \"app\";\n private static final String LEVEL_PLATFORM_STRING = \"platform\";\n private static final String LEVEL_ALL_STRING = \"all\";\n\n private int level = LEVEL_APP;\n private boolean minifyEnabled = true;\n private boolean obfuscationEnabled = false;\n @Nullable\n private Set<String> excludeFiles;\n\n @NotNull\n @IgnoreUnused\n public String getLevel() {\n switch (level) {\n case LEVEL_APP:\n return LEVEL_APP_STRING;\n case LEVEL_PLATFORM:\n return LEVEL_PLATFORM_STRING;\n case LEVEL_ALL:\n return LEVEL_ALL_STRING;\n default:\n throw new IllegalStateException();\n }\n }\n\n public int getLevelRaw() {\n return level;\n }\n\n @IgnoreUnused\n public void setLevel(@NotNull String level) {\n try {\n this.level = getLevelForString(level);\n } catch (GradleException ex) {\n throw new GradleException(\"level property can only be set to \" +\n \"'\" + LEVEL_APP_STRING + \"', \" +\n \"'\" + LEVEL_PLATFORM_STRING + \"' or \" +\n \"'\" + LEVEL_ALL_STRING + \"'\");\n }\n }\n\n private static int getLevelForString(@NotNull String proguardLevel) {\n if (LEVEL_APP_STRING.equalsIgnoreCase(proguardLevel)) {\n return LEVEL_APP;\n } else if (LEVEL_PLATFORM_STRING.equalsIgnoreCase(proguardLevel)) {\n return LEVEL_PLATFORM;\n } else if (LEVEL_ALL_STRING.equalsIgnoreCase(proguardLevel)) {\n return LEVEL_ALL;\n } else {\n throw new GradleException();\n }\n }\n\n public boolean isMinifyEnabled() {\n return minifyEnabled;\n }\n\n @IgnoreUnused\n public void setMinifyEnabled(boolean minifyEnabled) {\n this.minifyEnabled = minifyEnabled;\n }\n\n public boolean isObfuscationEnabled() {\n return obfuscationEnabled;\n }\n\n @IgnoreUnused\n public void setObfuscationEnabled(boolean obfuscationEnabled) {\n this.obfuscationEnabled = obfuscationEnabled;\n }\n\n @Nullable\n public Collection<String> getExcludeFiles() {\n return excludeFiles;\n }\n\n @IgnoreUnused\n public void setExcludeFiles(@Nullable Collection<String> excludedFiles) {\n this.excludeFiles = excludedFiles == null ? null : new LinkedHashSet<>(excludedFiles);\n }\n\n public ProGuardOptions excludeFile(String... names) {\n if (excludeFiles == null) {\n excludeFiles = new LinkedHashSet<>();\n }\n excludeFiles.addAll(Arrays.asList(Require.nonNull(names)));\n return this;\n }\n\n @Nullable\n private Object baseCfgFile;\n\n @Nullable\n public Object getBaseCfgFile() {\n return baseCfgFile;\n }\n\n @IgnoreUnused\n public void setBaseCfgFile(@Nullable Object baseCfgFile) {\n this.baseCfgFile = baseCfgFile;\n }\n\n @Nullable\n private Object appendCfgFile;\n\n @Nullable\n public Object getAppendCfgFile() {\n return appendCfgFile;\n }\n\n @IgnoreUnused\n public void setAppendCfgFile(@Nullable Object appendCfgFile) {\n this.appendCfgFile = appendCfgFile;\n }\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 FileList implements EntryParent {\n\n @NotNull\n private final Path localRoot;\n\n @NotNull\n private final URI target;\n\n @NotNull\n private final List<Entry> entries = new ArrayList<>();\n\n public FileList(@NotNull File localRoot, @NotNull URI target) {\n this.localRoot = Require.nonNull(localRoot.getAbsoluteFile().toPath());\n this.target = Require.nonNull(target);\n }\n\n public Path getLocalRoot() {\n return localRoot;\n }\n\n public URI getTarget() {\n return target;\n }\n\n public void walk(@NotNull Walker walker) {\n Require.nonNull(walker);\n\n try {\n for (Entry entry : entries) {\n entry.walk(walker);\n }\n } catch (IOException ex) {\n throw new GradleException(ex.getMessage(), ex);\n }\n }\n\n @Override\n public boolean isLast(Entry entry) {\n Require.TRUE(entries.contains(entry), \"unexpected state\");\n Require.sizeGT(entries, 0);\n return entries.indexOf(entry) == entries.size() - 1;\n }\n\n public String add(@NotNull File file) {\n return add(file, null);\n }\n\n public String add(@NotNull File file, @Nullable Set<File> excludes) {\n Require.nonNull(file);\n Require.TRUE(file.isAbsolute(), \"Internal error: file must be an absolute path\");\n\n final Set<Path> excls;\n if (excludes != null) {\n excls = excludes.stream()\n .map(x -> x.getAbsoluteFile().toPath())\n .collect(Collectors.toSet());\n } else {\n excls = Collections.emptySet();\n }\n\n // We only support files and directories\n if (!file.isFile() && !file.isDirectory()) {\n throw new GradleException(\"unknown file type \" + file.getAbsolutePath());\n }\n\n final File absoluteFile = file.getAbsoluteFile();\n if (file.isFile()) {\n addFile(absoluteFile);\n return resolveRemotePath(absoluteFile);\n\n } else if (file.isDirectory()) {\n final Path root = absoluteFile.toPath();\n try {\n Files.walkFileTree(root, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n if (excls.contains(dir)) {\n return SKIP_SUBTREE;\n }\n\n final Path relativize = localRoot.relativize(dir);\n\n if (relativize.getNameCount() == 1 && relativize.getName(0).toString().length() == 0) {\n return CONTINUE;\n }\n\n getDirectory(relativize);\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (excls.contains(file)) {\n return CONTINUE;\n }\n addFile(file.toFile());\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return TERMINATE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return CONTINUE;\n }\n });\n } catch (IOException e) {\n throw new GradleException(e.getMessage(), e);\n }\n return resolveRemotePath(absoluteFile);\n\n } else {\n throw new IllegalStateException();\n }\n }\n\n private String resolveRemotePath(File absoluteFile) {\n final Path relative = localRoot.relativize(absoluteFile.toPath());\n try {\n return Server.getRemotePath(target, relative);\n } catch (IOException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n private void addFile(@NotNull File absoluteFile) {\n // Get relative path\n final Path relativePath = localRoot.relativize(absoluteFile.toPath());\n\n Require.GT(relativePath.getNameCount(), 0, \"unexpected state - relativePath.namecount <= 0\");\n\n // Get entryParent and entries container\n List<Entry> entries = this.entries;\n EntryParent entryParent = this;\n if (relativePath.getNameCount() > 1) {\n final DirectoryEntry directory = getDirectory(relativePath.getParent());\n assert directory != null;\n entries = directory.entries;\n entryParent = directory;\n }\n\n // Add the file\n insertFileEntry(relativePath.getFileName().toString(), absoluteFile, entryParent, entries);\n }\n\n private static void insertFileEntry(@NotNull String name, @NotNull File localFile,\n @NotNull EntryParent parent, @NotNull List<Entry> entries) {\n Require.GT(name.length(), 0, \"unexpected state - rpath.filename.length <= 0\");\n final Entry entry = getEntry(entries, name);\n if (entry != null) {\n Require.TRUE(entry instanceof FileEntry, \"unexpected state - entry.class !~ FileEntry\");\n Require.TRUE(((FileEntry) entry).getLocalFile().equals(localFile), \"unexpected state - entry.localFile != localFile\");\n\n } else {\n entries.add(new FileEntry(name, parent, localFile));\n }\n }\n\n @Nullable\n private static Entry getEntry(@NotNull List<Entry> entries, @NotNull String name) {\n Require.nonNull(name);\n Require.nonNull(entries);\n\n return entries.stream().filter(entry -> entry.name.equals(name)).findFirst().orElse(null);\n }\n\n @Override\n public DirectoryEntry getEntry() {\n throw new IllegalStateException();\n }\n\n @Override\n public EntryParent getEntryParent() {\n return null;\n }\n\n private DirectoryEntry getDirectory(Path path) {\n return getDirectory(path, entries, this, 0);\n }\n\n private static DirectoryEntry getDirectory(Path path, List<Entry> entries, EntryParent entryParent, int idx) {\n final Path name = path.getName(idx);\n DirectoryEntry entry = (DirectoryEntry) getEntry(entries, name.getFileName().toString());\n if (entry == null) {\n entry = new DirectoryEntry(name.toString(), entryParent);\n entries.add(entry);\n }\n if (idx + 1 < path.getNameCount()) {\n return getDirectory(path, entry.entries, entry, idx + 1);\n }\n return entry;\n }\n}", "public class Arch {\n @NotNull\n public final String name;\n\n @NotNull\n public final String family;\n\n private Arch(@NotNull String name, @NotNull String family) {\n this.name = Require.nonNull(name);\n this.family = Require.nonNull(family);\n }\n\n public static final String ARCH_ARMV7 = \"armv7\";\n public static final String ARCH_ARMV7S = \"armv7s\";\n public static final String ARCH_ARMV7K = \"armv7k\";\n public static final String ARCH_ARM64 = \"arm64\";\n public static final String ARCH_I386 = \"i386\";\n public static final String ARCH_X86_64 = \"x86_64\";\n\n public static final String FAMILY_ARM = \"arm\";\n public static final String FAMILY_ARM64 = \"arm64\";\n public static final String FAMILY_X86 = \"x86\";\n public static final String FAMILY_X86_64 = \"x86_64\";\n public static final String[] ALL_FAMILIES = new String[]{FAMILY_ARM, FAMILY_ARM64, FAMILY_X86, FAMILY_X86_64};\n\n public static final Arch ARMV7 = new Arch(ARCH_ARMV7, FAMILY_ARM);\n public static final Arch ARMV7S = new Arch(ARCH_ARMV7S, FAMILY_ARM);\n public static final Arch ARMV7K = new Arch(ARCH_ARMV7K, FAMILY_ARM);\n public static final Arch ARM64 = new Arch(ARCH_ARM64, FAMILY_ARM64);\n public static final Arch I386 = new Arch(ARCH_I386, FAMILY_X86);\n public static final Arch X86_64 = new Arch(ARCH_X86_64, FAMILY_X86_64);\n public static final Arch[] ALL_ARCHS = new Arch[]{ARMV7, ARMV7S, ARMV7K, ARM64, I386, X86_64};\n\n @NotNull\n public static Arch getForName(@NotNull String name) {\n Require.nonNull(name);\n\n for (Arch arch : ALL_ARCHS) {\n if (arch.name.equalsIgnoreCase(name)) {\n return arch;\n }\n }\n throw new GradleException(\"Unknown architecture '\" + name + \"', supported: \" +\n Arrays.stream(ALL_ARCHS).map(x -> x.name).collect(Collectors.toList()));\n }\n\n @NotNull\n public static String validateArchFamily(@NotNull String name) {\n Require.nonNull(name);\n\n for (String family : ALL_FAMILIES) {\n if (family.equalsIgnoreCase(name)) {\n return family;\n }\n }\n throw new GradleException(\"Unknown architecture family '\" + name + \"', supported: \" +\n Arrays.stream(ALL_ARCHS).map(x -> x.name).collect(Collectors.toList()));\n }\n\n @Override\n public String toString() {\n return name;\n }\n}", "public class Mode {\n @NotNull\n public final String name;\n\n private Mode(@NotNull String name) {\n this.name = name;\n }\n\n public static final Mode DEBUG = new Mode(\"debug\");\n public static final Mode RELEASE = new Mode(\"release\");\n\n public static Mode getForName(@NotNull String name) {\n Require.nonNull(name);\n\n if (\"debug\".equalsIgnoreCase(name)) {\n return DEBUG;\n }\n if (\"release\".equalsIgnoreCase(name)) {\n return RELEASE;\n }\n throw new GradleException(\"Unknown configuration '\" + name + \"'\");\n }\n\n public static boolean validateName(@Nullable String name) {\n return \"debug\".equalsIgnoreCase(name) || \"release\".equalsIgnoreCase(name);\n }\n\n public String getXcodeCompatibleName() {\n if (this == DEBUG) {\n return \"Debug\";\n }\n if (this == RELEASE) {\n return \"Release\";\n }\n throw new GradleException(\"Unknown configuration '\" + name + \"'\");\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.GradleException; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.SourceSet; import org.moe.common.utils.NativeUtil; import org.moe.gradle.MoeExtension; import org.moe.gradle.MoePlugin; import org.moe.gradle.MoeSDK; import org.moe.gradle.anns.IgnoreUnused; import org.moe.gradle.anns.NotNull; import org.moe.gradle.anns.Nullable; import org.moe.gradle.options.ProGuardOptions; import org.moe.gradle.remote.Server; import org.moe.gradle.remote.file.FileList; import org.moe.gradle.utils.Arch; import org.moe.gradle.utils.Mode; import org.moe.gradle.utils.Require; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set;
try { dex2oatExec = remoteServer.getSDKRemotePath(getDex2oatExec()); imageClasses = remoteServer.getSDKRemotePath(getImageClasses()); } catch (IOException e) { throw new GradleException("Unsupported configuration", e); } final FileList fileList = new FileList(getProject().getProjectDir(), remoteServer.getBuildDir()); StringBuilder dexFiles = new StringBuilder(); StringBuilder remoteDexFilesCheck = new StringBuilder(); getInputFiles().forEach(it -> { String path; boolean needsUpload = false; try { path = remoteServer.getSDKRemotePath(it); } catch (IOException ignore) { needsUpload = true; try { path = getInnerProjectRelativePath(it).toString(); } catch (IOException e) { throw new GradleException("Unsupported configuration", e); } } if (dexFiles.length() > 0) { dexFiles.append(':'); remoteDexFilesCheck.append(" && "); } if (needsUpload) { final String remotePath = fileList.add(it); dexFiles.append(remotePath); remoteDexFilesCheck.append("[ -f '").append(remotePath).append("' ]"); } else { dexFiles.append(path); remoteDexFilesCheck.append("[ -f '").append(path).append("' ]"); } }); remoteServer.upload("dex2oat inputs", fileList); remoteServer.exec("dex2oat inputs check", remoteDexFilesCheck.toString()); final Path destArtRel; final Path destOatRel; try { destArtRel = getInnerProjectRelativePath(getDestImageFile()); destOatRel = getInnerProjectRelativePath(getDestOatFile()); } catch (IOException e) { throw new GradleException("Unsupported configuration", e); } final String remoteDestArt = remoteServer.getRemotePath(destArtRel); final String remoteDestOat = remoteServer.getRemotePath(destOatRel); remoteServer.exec("prepare output directories", "" + "mkdir -p `dirname " + remoteDestArt + "` && " + "mkdir -p `dirname " + remoteDestOat + "`"); remoteServer.exec("dex2oat", dex2oatExec + " " + "--instruction-set=" + Arch.validateArchFamily(getArchFamily()) + " " + "--base=0x" + Long.toHexString(getBase()) + " " + "--compiler-backend=" + validateBackend(getCompilerBackend()) + " " + (getEmitDebugInfo() ? "--generate-debug-info" : "--no-generate-debug-info") + " " + "--image=" + remoteDestArt + " " + "--image-classes=" + imageClasses + " " + "--oat-file=" + remoteDestOat + " " + "--dex-file=" + dexFiles ); remoteServer.downloadFile("art", remoteDestArt, getDestImageFile().getParentFile()); remoteServer.downloadFile("oat", remoteDestOat, getDestOatFile().getParentFile()); } else { exec(spec -> { // Set executable if (NativeUtil.isHostAARCH64() && !Arch.FAMILY_ARM64.equalsIgnoreCase(getArchFamily())) { // Run dex2oat using rosetta 2 when compiling non-arm64 target on Apple silicon // because currently the arm64 version of dex2oat does not work reliably due to // the issue of word size & alignment mismatch. // TODO: solve this? spec.setExecutable("arch"); spec.args("--x86_64"); spec.args(getDex2oatExec()); } else { spec.setExecutable(getDex2oatExec()); } // Set target options spec.args("--instruction-set=" + Arch.validateArchFamily(getArchFamily())); spec.args("--base=0x" + Long.toHexString(getBase())); // Set compiler backend spec.args("--compiler-backend=" + validateBackend(getCompilerBackend())); // Include or not include ELF symbols in oat file if (getEmitDebugInfo()) { spec.args("--generate-debug-info"); } else { spec.args("--no-generate-debug-info"); } // Set files spec.args("--image=" + getDestImageFile().getAbsolutePath()); spec.args("--image-classes=" + getImageClasses().getAbsolutePath()); spec.args("--oat-file=" + getDestOatFile().getAbsolutePath()); // Set inputs StringBuilder dexFiles = new StringBuilder(); getInputFiles().forEach(it -> { if (dexFiles.length() > 0) { dexFiles.append(':'); } dexFiles.append(it.getAbsolutePath()); }); spec.args("--dex-file=" + dexFiles); }); } } private Dex dexTaskDep; @NotNull @Internal public Dex getDexTaskDep() {
return Require.nonNull(dexTaskDep);
8
Sensirion/SmartGadget-Android
app/src/main/java/com/sensirion/smartgadget/view/glossary/adapter/GlossaryAdapter.java
[ "public class GlossaryDescriptorItem implements GlossaryItem {\n public final String title;\n public final String description;\n public final Drawable icon;\n\n public GlossaryDescriptorItem(final String title, final String description, final Drawable icon) {\n this.title = title;\n this.description = description;\n this.icon = icon;\n }\n}", "public interface GlossaryItem {\n}", "public class GlossarySourceItem implements GlossaryItem {\n public final String sourceName;\n public final Drawable icon;\n\n public GlossarySourceItem(final String sourceName, final Drawable icon) {\n this.sourceName = sourceName;\n this.icon = icon;\n }\n}", "public class GlossaryDescriptorViewHolder {\n public final TextView itemTitle;\n public final TextView itemDescription;\n public final ImageView itemIcon;\n\n public GlossaryDescriptorViewHolder(final TextView itemTitle, final TextView itemDescription, final ImageView itemIcon) {\n this.itemTitle = itemTitle;\n this.itemDescription = itemDescription;\n this.itemIcon = itemIcon;\n }\n}", "public class GlossarySourceViewHolder {\n public final TextView itemSourceText;\n public final ImageView itemSourceIcon;\n\n public GlossarySourceViewHolder(final TextView itemSourceText, final ImageView itemSourceIcon) {\n this.itemSourceText = itemSourceText;\n this.itemSourceIcon = itemSourceIcon;\n }\n}" ]
import android.content.Context; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.sensirion.smartgadget.R; import com.sensirion.smartgadget.view.glossary.adapter.glossary_items.GlossaryDescriptorItem; import com.sensirion.smartgadget.view.glossary.adapter.glossary_items.GlossaryItem; import com.sensirion.smartgadget.view.glossary.adapter.glossary_items.GlossarySourceItem; import com.sensirion.smartgadget.view.glossary.adapter.view_holders.GlossaryDescriptorViewHolder; import com.sensirion.smartgadget.view.glossary.adapter.view_holders.GlossarySourceViewHolder; import java.util.ArrayList;
/* * Copyright (c) 2017, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.sensirion.smartgadget.view.glossary.adapter; public class GlossaryAdapter extends BaseAdapter { private final Typeface mTypefaceNormal; private final Typeface mTypefaceBold; private final LayoutInflater mInflater; @NonNull private final ArrayList<GlossaryItem> mGlossaryDatabase; public GlossaryAdapter(final LayoutInflater inflater, @NonNull final Context context) { super(); mGlossaryDatabase = new ArrayList<>(); mInflater = inflater; mTypefaceNormal = Typeface.createFromAsset(context.getAssets(), "HelveticaNeueLTStd-Cn.otf"); mTypefaceBold = Typeface.createFromAsset(context.getAssets(), "HelveticaNeueLTStd-Bd.otf"); } @Override public int getCount() { return mGlossaryDatabase.size(); } @Override public Object getItem(final int i) { return mGlossaryDatabase.get(i); } @Override public long getItemId(final int i) { return i; } @Override public View getView(final int i, final View view, final ViewGroup viewGroup) { if (mGlossaryDatabase.get(i) instanceof GlossaryDescriptorItem) { return getDescriptorView(i, viewGroup); } return getSourceView(i, viewGroup); } @NonNull private View getDescriptorView(final int i, final ViewGroup viewGroup) { final GlossaryDescriptorViewHolder viewHolder; final View view = mInflater.inflate(R.layout.listitem_glossary_item, viewGroup, false); final TextView itemTitle = (TextView) view.findViewById(R.id.glossary_item_title); final TextView itemDescription = (TextView) view.findViewById(R.id.glossary_item_description); final ImageView itemIcon = (ImageView) view.findViewById(R.id.glossary_icon); viewHolder = new GlossaryDescriptorViewHolder(itemTitle, itemDescription, itemIcon); view.setTag(viewHolder); final GlossaryDescriptorItem descriptor = ((GlossaryDescriptorItem) mGlossaryDatabase.get(i)); //Sets the title. viewHolder.itemTitle.setText(descriptor.title); viewHolder.itemTitle.setTypeface(mTypefaceBold); //Sets the description. final String description = descriptor.description; viewHolder.itemDescription.setText(description); viewHolder.itemDescription.setTypeface(mTypefaceNormal); //Sets the icon viewHolder.itemIcon.setImageDrawable(descriptor.icon); return view; } @NonNull private View getSourceView(final int i, final ViewGroup viewGroup) {
final GlossarySourceViewHolder viewHolder;
4
eHarmony/pho
src/main/java/com/eharmony/pho/query/builder/QueryBuilder.java
[ "public enum QueryOperationType {\n\n SELECT, UPDATE, INSERT, DELETE;\n \n}", "public interface QuerySelect<T, R> {\n\n /**\n * Get the queried entity type.\n * \n * @return the entity class being queried\n */\n public Class<T> getEntityClass();\n\n /**\n * Get the return entity type.\n * \n * @return the class of the desired return type\n */\n public Class<R> getReturnType();\n\n /**\n * The list of properties to return. An empty collection means all properties.\n * \n * @return the fields to be returned from the query\n */\n public List<String> getReturnFields();\n\n /**\n * Get the query criteria. The top level object can either be a single Criterion or a Junction of multiple nested\n * Criterion objects.\n * \n * @return the root criterion node\n */\n public Criterion getCriteria();\n\n Criterion getGroupCriteria();\n\n /**\n * Get the Order clauses.\n * \n * @return the ordering clauses\n */\n public Orderings getOrder();\n\n public List<Projection> getProjection();\n\n /**\n * Get the max desired results. Null signifies no maximum.\n * \n * @return the maximum number of results or null if no maximum\n * \n */\n public Integer getMaxResults();\n\n /**\n * Getter method for Query Operation type\n * \n * @return <code>QueryOperationType</code> \n */\n public QueryOperationType getQueryOperationType();\n\n /**\n * Getter method for Query Hint\n *\n * @return <code>String</code>\n */\n public String getQueryHint();\n\n}", "public class QuerySelectImpl<T, R> implements QuerySelect<T, R> {\n\n private final Class<T> entityClass;\n private final Class<R> returnType;\n private final Criterion criteria;\n private final Criterion groupCriterion;\n private final Orderings orderings;\n private final Integer maxResults;\n private final List<String> returnFields;\n private final List<Projection> projections;\n private final QueryOperationType queryOperationType;\n private final String queryHint;\n\n public QuerySelectImpl(Class<T> entityClass, Class<R> returnType, Criterion criteria, Criterion groupCriterion, Orderings orderings,\n Integer maxResults, List<String> returnFields, List<Projection> projections, QueryOperationType queryOperationType, String queryHint) {\n this.entityClass = entityClass;\n this.returnType = returnType;\n this.criteria = criteria;\n this.groupCriterion = groupCriterion;\n this.returnFields = returnFields;\n this.orderings = orderings;\n this.maxResults = maxResults;\n this.projections = projections;\n this.queryOperationType = queryOperationType;\n this.queryHint = queryHint;\n }\n\n @Override\n public QueryOperationType getQueryOperationType() {\n return queryOperationType;\n }\n\n @Override\n public String getQueryHint() {\n return queryHint;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see com.eharmony.matching.seeking.query.Query#getEntityClass()\n */\n @Override\n public Class<T> getEntityClass() {\n return entityClass;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see com.eharmony.matching.seeking.query.Query#getReturnType()\n */\n @Override\n public Class<R> getReturnType() {\n return returnType;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see com.eharmony.matching.seeking.query.Query#getReturnFields()\n */\n @Override\n public List<String> getReturnFields() {\n return returnFields;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see com.eharmony.matching.seeking.query.Query#getCriteria()\n */\n @Override\n public Criterion getCriteria() {\n return criteria;\n }\n\n @Override\n public Criterion getGroupCriteria() {\n return groupCriterion;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see com.eharmony.matching.seeking.query.Query#getOrder()\n */\n @Override\n public Orderings getOrder() {\n return orderings;\n }\n\n @Override\n public List<Projection> getProjection() {\n return this.projections;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see com.eharmony.matching.seeking.query.Query#getMaxResults()\n */\n @Override\n public Integer getMaxResults() {\n return maxResults;\n }\n\n /*\n * (non-Javadoc)\n * \n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return \"QueryImpl [entityClass=\" + entityClass + \", criteria=\" + criteria + \", orderings=\" + orderings\n + \", maxResults=\" + maxResults + \"]\";\n }\n}", "public class AggregateProjection extends Projection {\n private String propertyName;\n private Aggregate function;\n\n protected AggregateProjection(Aggregate function, String propertyName) {\n super(function, propertyName);\n this.propertyName = propertyName;\n this.function = function;\n }\n\n public String getPropertyName(){\n return propertyName;\n }\n\n public AggregateProjection setPropertyName(String propertyName) {\n this.propertyName = propertyName;\n return this;\n }\n\n public String getName() {\n return function.symbol() + \"(\" + propertyName + \")\";\n }\n}", "public class Projection implements Criterion, WithAggregateFunction {\n private final Aggregate function;\n private final List<String> propertyNames;\n\n protected Projection(Aggregate function, String... propertyNames) {\n this.function = function;\n this.propertyNames = Arrays.asList(propertyNames);\n }\n\n @Override\n public Aggregate getAggregate() {\n return this.function;\n }\n\n public List<String> getPropertyNames() {\n return this.propertyNames;\n }\n}" ]
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.eharmony.pho.query.QueryOperationType; import com.eharmony.pho.query.QuerySelect; import com.eharmony.pho.query.QuerySelectImpl; import com.eharmony.pho.query.criterion.*; import com.eharmony.pho.query.criterion.projection.AggregateProjection; import com.eharmony.pho.query.criterion.projection.Projection;
package com.eharmony.pho.query.builder; /** * Builder for Query objects * * @param <T> the entity type being queried * @param <R> the desired return type */ public class QueryBuilder<T, R> { private final Class<T> entityClass; private final Class<R> returnType; private List<Criterion> criteria = new ArrayList<>(); private List<Criterion> groupCriteria = new ArrayList<>(); private Orderings orderings = new Orderings();
private List<Projection> projections = new ArrayList<>();
4
DaiDongLiang/DSC
src/test/java/net/floodlightcontroller/core/internal/OFSwitchHandlerTestBase.java
[ "@JsonSerialize(using=IOFSwitchSerializer.class)//Json序列化\npublic interface IOFSwitch extends IOFMessageWriter {\n // Attribute keys\n // These match our YANG schema, make sure they are in sync\n public static final String SWITCH_DESCRIPTION_FUTURE = \"description-future\";\n public static final String SWITCH_DESCRIPTION_DATA = \"description-data\";\n public static final String SWITCH_SUPPORTS_NX_ROLE = \"supports-nx-role\";\n public static final String PROP_FASTWILDCARDS = \"fast-wildcards\";\n public static final String PROP_REQUIRES_L3_MATCH = \"requires-l3-match\";\n public static final String PROP_SUPPORTS_OFPP_TABLE = \"supports-ofpp-table\";\n public static final String PROP_SUPPORTS_OFPP_FLOOD = \"supports-ofpp-flood\";\n public static final String PROP_SUPPORTS_NETMASK_TBL = \"supports-netmask-table\";\n public static final String PROP_SUPPORTS_BSN_SET_TUNNEL_DST_ACTION =\n \"supports-set-tunnel-dst-action\";\n public static final String PROP_SUPPORTS_NX_TTL_DECREMENT = \"supports-nx-ttl-decrement\";\n\n public enum SwitchStatus {\n /** this switch is in the process of being handshaked. Initial State. \n * 这个交换机在握手进程中初始状态\n */\n \tHANDSHAKE(false),\n /** the OF channel to this switch is currently in SLAVE role - the switch will not accept\n * state-mutating messages from this controller node.\n * OF链路连接的控制器当前是SLAVE角色,交换机将不承认此控制器修改的信息\n */\n SLAVE(true),\n /** the OF channel to this switch is currently in MASTER (or EQUALS) role - the switch is\n * controllable from this controller node.\n * OF链路连接的交换机当前是MASTER或者EQUALS角色。控制器能够控制交换机\n */\n MASTER(true),\n /** the switch has been sorted out and quarantined by the handshake. It does not show up\n * in normal switch listings\n * 这个交换机通过握手被挑选和隔离。它不能呈现在正常的交换机表\n */\n QUARANTINED(false),\n /** the switch has disconnected, and will soon be removed from the switch database \n * 这个交换机已断开连接,并且不就将会从交换机表中移除\n * */\n DISCONNECTED(false);\n\n private final boolean visible;\n\n SwitchStatus(boolean visible) {\n this.visible = visible;\n }\n\n /** wether this switch is currently visible for normal operation \n * 对于正常运行当前交换机是否可见\n * */\n public boolean isVisible() {\n return visible;\n }\n\n /** wether this switch is currently ready to be controlled by this controller\n * 当前交换机是否已经准备好被控制器控制\n * */\n public boolean isControllable() {\n return this == MASTER;\n }\n }\n /**\n * 得到交换机状态\n * @return\n */\n SwitchStatus getStatus();\n\n /**\n * Returns switch features from features Reply\n * 在特征回复中回复交换机特征\n * @return\n */\n long getBuffers();\n\n /**\n * Disconnect all the switch's channels and mark the switch as disconnected\n * 断开所有交换机连接,并标记交换机为disconnected\n */\n void disconnect();\n /**\n * 得到Actions集合\n * @return \n */\n Set<OFActionType> getActions();\n /**\n * 得到Capabilities集合\n * @return\n */\n Set<OFCapabilities> getCapabilities();\n /**\n * 得到流表\n * @return\n */\n short getTables();\n\n /**\n * 获取一个对这台交换机描述性统计的副本 \n * @return a copy of the description statistics for this switch\n */\n SwitchDescription getSwitchDescription();\n\n /**\n * Get the IP address of the remote (switch) end of the connection\n * 得到交换机IP\n * @return the inet address\n */\n SocketAddress getInetAddress();\n\n /**\n * Get list of all enabled ports. This will typically be different from\n * the list of ports in the OFFeaturesReply, since that one is a static\n * snapshot of the ports at the time the switch connected to the controller\n * whereas this port list also reflects the port status messages that have\n * been received.\n * 得到全部使能端口列表。\n * 这通常与OFFeaturesReply回复中的端口列表不同,因为这是此刻交换机连接控制器的端口快照。\n * 然而这个端口列表也能反映出端口状态信息已经收到\n * \n * @return Unmodifiable list of ports not backed by the underlying collection\n * 不可修改的列表\n */\n Collection<OFPortDesc> getEnabledPorts();\n\n /**\n * Get list of the port numbers of all enabled ports. This will typically\n * be different from the list of ports in the OFFeaturesReply, since that\n * one is a static snapshot of the ports at the time the switch connected\n * to the controller whereas this port list also reflects the port status\n * messages that have been received.\n * 获得所有活动端口的端口号。\n * @return Unmodifiable list of ports not backed by the underlying collection\n * 不可修改的列表\n */\n Collection<OFPort> getEnabledPortNumbers();\n\n /**\n * Retrieve the port object by the port number. The port object\n * is the one that reflects the port status updates that have been\n * received, not the one from the features reply.\n * 通过端口号获取端口对象.\n * 这个端口对象反映端口状态更新已被接收,不来自features回复\n * @param portNumber 端口号\n * @return port object 端口对象\n */\n OFPortDesc getPort(OFPort portNumber);\n\n /**\n * Retrieve the port object by the port name. The port object\n * is the one that reflects the port status updates that have been\n * received, not the one from the features reply.\n * Port names are case insentive\n * 通过端口名获取端口对象.\n * @param portName\n * @return port object\n */\n OFPortDesc getPort(String portName);\n\n /**\n * Get list of all ports. This will typically be different from\n * the list of ports in the OFFeaturesReply, since that one is a static\n * snapshot of the ports at the time the switch connected to the controller\n * whereas this port list also reflects the port status messages that have\n * been received.\n * 获得所有端口列表\n * @return Unmodifiable list of ports\n */\n Collection<OFPortDesc> getPorts();\n\n /**\n * This is mainly for the benefit of the DB code which currently has the\n * requirement that list elements be sorted by key. Hopefully soon the\n * DB will handle the sorting automatically or not require it at all, in\n * which case we could get rid of this method.\n * 这主要是为了当前数据库代码要求列表元素根据key排序。\n * 希望很快数据库能自动排序或不再需要排序,这种情况下我们可以拜托这个方法。\n * @return 已排序的端口列表\n */\n Collection<OFPortDesc> getSortedPorts();\n\n /**\n * 端口是否处在活动状态\n * 该端口是否被启用。(configured down、link down和生成树端口阻塞的情况不在此列) \n * @param portNumber\n * @return Whether a port is enabled per latest port status message\n * (not configured down nor link down nor in spanning tree blocking state)\n */\n boolean portEnabled(OFPort portNumber);\n\n /**\n * @param portNumber\n * @return Whether a port is enabled per latest port status message\n * (not configured down nor link down nor in spanning tree blocking state)\n */\n boolean portEnabled(String portName);\n\n /**\n * Check is switch is connected\n * 检查是否连接\n * @return Whether or not this switch is connected\n */\n boolean isConnected();\n\n /**\n * Retrieves the date the switch connected to this controller\n * 获取此交换机连接到控制器的时间\n * @return the date\n */\n Date getConnectedSince();\n\n /**\n * Get the datapathId of the switch\n * 获取此交换机的DPID\n * @return\n */\n DatapathId getId();\n\n /**\n * Retrieves attributes of this switch\n * 获取此交换机的属性\n * @return\n */\n Map<Object, Object> getAttributes();\n\n /**\n * 检查该交换机是否处于活动状态。\n * 交换机连接这个控制器并且处于master角色\n * Check if the switch is active. I.e., the switch is connected to this\n * controller and is in master role\n * @return\n */\n boolean isActive();\n\n /**\n * Get the current role of the controller for the switch\n * 获得当前控制器对于交换机的角色\n * @return the role of the controller\n */\n OFControllerRole getControllerRole();\n\n /**\n * Checks if a specific switch property exists for this switch\n * 检查一个特定的属性是否存在于这个交换机\n * @param name name of property\n * @return value for name\n */\n boolean hasAttribute(String name);\n\n /**\n * Set properties for switch specific behavior\n * 获取交换机特定行为的属性\n * @param name name of property\n * @return value for name\n */\n Object getAttribute(String name);\n\n /**\n * Check if the given attribute is present and if so whether it is equal\n * to \"other\"\n * 检查给定的属性是否存在,如果是,该属性是否为“other”\n * @param name the name of the attribute to check\n * @param other the object to compare the attribute against.\n * @return true if the specified attribute is set and equals() the given\n * other object.\n */\n boolean attributeEquals(String name, Object other);\n\n /**\n * Set properties for switch specific behavior\n * 设置交换机特定行为的属性\n * @param name name of property\n * @param value value for name\n */\n void setAttribute(String name, Object value);\n\n /**\n * Set properties for switch specific behavior\n * 移除交换机特定行为的属性\n * @param name name of property\n * @return current value for name or null (if not present)\n */\n Object removeAttribute(String name);\n\n /**\n * Returns a factory object that can be used to create OpenFlow messages.\n * 返回一个能够创造OpenFlow消息的工厂对象\n * @return\n */\n OFFactory getOFFactory();\n\n /**\n * Flush all flows queued for this switch on all connections that were written by the current thread.\n * 通过当前线程刷新所有连接在此交换机上流队列\n *\n */\n void flush();\n\n /**\n * Gets the OF connections for this switch instance\n * 获得此交换机实例的OF连接\n * @return Collection of IOFConnection\n */\n ImmutableList<IOFConnection> getConnections();\n\n /**\n * Writes a message to the connection specified by the logical OFMessage category\n * 写入一个正确的OFMessage到指定的连接\n * @param m an OF Message\n * @param category the category of the OF Message to be sent\n */\n void write(OFMessage m, LogicalOFMessageCategory category);\n\n /**\n * Writes a message list to the connection specified by the logical OFMessage category\n * 写入一个正确的OFMessage列表到指定的连接\n * @param msglist an OF Message list\n * @param category the category of the OF Message list to be sent\n */\n void write(Iterable<OFMessage> msglist, LogicalOFMessageCategory category);\n\n /**\n * Get a connection specified by the logical OFMessage category\n * 通过获得一个指定的连接\n * @param category the category for the connection the user desires\n * @return an OF Connection\n */\n OFConnection getConnectionByCategory(LogicalOFMessageCategory category);\n\n /** write a Stats (Multipart-) request, register for all corresponding reply messages.\n * 写入一个状态请求,登记所有相应的回复信息\n * Returns a Future object that can be used to retrieve the List of asynchronous\n * OFStatsReply messages when it is available.\n * 返回一个Future对象能被用来获得异步OFStatsReply回复报文列表当它可用\n *\n * @param request stats request\n * @param category the category for the connection that this request should be written to\n * @return Future object wrapping OFStatsReply\n * If the connection is not currently connected, will\n * return a Future that immediately fails with a @link{SwitchDisconnectedException}.\n */\n <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(OFStatsRequest<REPLY> request, LogicalOFMessageCategory category);\n\n /** write an OpenFlow Request message, register for a single corresponding reply message\n * or error message.\n *\t写入一个OpenFlow请求信息,登记单个相应的回复报文\n * @param request\n * @param category the category for the connection that this request should be written to\n * @return a Future object that can be used to retrieve the asynchrounous\n * response when available.\n *\n * If the connection is not currently connected, will\n * return a Future that immediately fails with a @link{SwitchDisconnectedException}.\n */\n <R extends OFMessage> ListenableFuture<R> writeRequest(OFRequest<R> request, LogicalOFMessageCategory category);\n}", "public enum SwitchStatus {\n /** this switch is in the process of being handshaked. Initial State. \n * 这个交换机在握手进程中初始状态\n */\n\tHANDSHAKE(false),\n /** the OF channel to this switch is currently in SLAVE role - the switch will not accept\n * state-mutating messages from this controller node.\n * OF链路连接的控制器当前是SLAVE角色,交换机将不承认此控制器修改的信息\n */\n SLAVE(true),\n /** the OF channel to this switch is currently in MASTER (or EQUALS) role - the switch is\n * controllable from this controller node.\n * OF链路连接的交换机当前是MASTER或者EQUALS角色。控制器能够控制交换机\n */\n MASTER(true),\n /** the switch has been sorted out and quarantined by the handshake. It does not show up\n * in normal switch listings\n * 这个交换机通过握手被挑选和隔离。它不能呈现在正常的交换机表\n */\n QUARANTINED(false),\n /** the switch has disconnected, and will soon be removed from the switch database \n * 这个交换机已断开连接,并且不就将会从交换机表中移除\n * */\n DISCONNECTED(false);\n\n private final boolean visible;\n\n SwitchStatus(boolean visible) {\n this.visible = visible;\n }\n\n /** wether this switch is currently visible for normal operation \n * 对于正常运行当前交换机是否可见\n * */\n public boolean isVisible() {\n return visible;\n }\n\n /** wether this switch is currently ready to be controlled by this controller\n * 当前交换机是否已经准备好被控制器控制\n * */\n public boolean isControllable() {\n return this == MASTER;\n }\n}", "public interface IOFSwitchBackend extends IOFSwitch {\n /**\n * Set the netty Channel this switch instance is associated with\n * Called immediately after instantiation\n * 注册连接\n * 实例化完成后立刻通知\n * @param channel\n */\n void registerConnection(IOFConnectionBackend connection);\n\n /**\n * Remove the netty Channels associated with this switch\n * 移除交换机与网络通道的联系\n * @param channel\n */\n void removeConnections();\n\n /**\n * Remove the netty Channel belonging to the specified connection\n * 移除属于特定连接的网络通道\n * @param connection\n */\n void removeConnection(IOFConnectionBackend connection);\n\n /**\n * Set the OFFeaturesReply message returned by the switch during initial\n * handshake.\n * 设置OFFeaturesReply报文回复在交换机最初的握手时\n * @param featuresReply\n */\n void setFeaturesReply(OFFeaturesReply featuresReply);\n\n /**\n * Add or modify a switch port.\n * This is called by the core controller\n * code in response to a OFPortStatus message. It should not typically be\n * called by other floodlight applications.\n *\t添加或修改一个交换机端口\n *\t这就是所谓的核心控制器\n *\t代码在OFPortStatus消息的回复中。\n *\t它不应该代表被称为其他floodl应用\n * OFPPR_MODIFY and OFPPR_ADD will be treated as equivalent. The OpenFlow\n * spec is not clear on whether portNames are portNumbers are considered\n * authoritative identifiers. We treat portNames <-> portNumber mappings\n * as fixed. If they change, we delete all previous conflicting ports and\n * add all new ports.\n *\tOFPPR_MODIFY 和 OFPPR_ADD将被视为相同。\n *\tOpenFlow细则不清楚portNames和portNumbers哪个是权威的标识符\n *\t我们看待portNames <-> portNumber映射不变。\n *\t如果它们改变,我们删除所有以前的节点,并创建新的节点\n *\t\n * @param ps the port status message\n * @return the ordered Collection of changes \"applied\" to the old ports\n * of the switch according to the PortStatus message. A single PortStatus\n * message can result in multiple changes.\n * 返回一个有序的集合应用于旧交换机节点根据PortStatus消息\n * 单个PortStatus消息能导致多个变化\n * If portName <-> portNumber mappings have\n * changed, the iteration order ensures that delete events for old\n * conflicting appear before before events adding new ports\n * 如果portName <-> portNumbe映射发生变化,通过迭代确保删除旧的冲突出现,在添加新节点之前\n */\n OrderedCollection<PortChangeEvent> processOFPortStatus(OFPortStatus ps);\n\n /**\n * Compute the changes that would be required to replace the old ports\n * of this switch with the new ports\n * @param ports new ports to set\n * @return the ordered collection of changes \"applied\" to the old ports\n * of the switch in order to set them to the new set.\n * If portName <-> portNumber mappings have\n * changed, the iteration order ensures that delete events for old\n * conflicting appear before before events adding new ports\n */\n OrderedCollection<PortChangeEvent>\n comparePorts(Collection<OFPortDesc> ports);\n\n /**\n * Replace the ports of this switch with the given ports.\n * @param ports new ports to set\n * @return the ordered collection of changes \"applied\" to the old ports\n * of the switch in order to set them to the new set.\n * If portName <-> portNumber mappings have\n * changed, the iteration order ensures that delete events for old\n * conflicting appear before before events adding new ports\n */\n OrderedCollection<PortChangeEvent>\n setPorts(Collection<OFPortDesc> ports);\n\n /***********************************************\n * The following method can be overridden by\n * specific types of switches\n ***********************************************\n */\n\n /**\n * Set the SwitchProperties based on it's description\n * @param description\n */\n void setSwitchProperties(SwitchDescription description);\n\n /**\n * Set the flow table full flag in the switch\n */\n void setTableFull(boolean isFull);\n\n /**\n * Start this switch driver's sub handshake. This might be a no-op but\n * this method must be called at least once for the switch to be become\n * ready.\n * This method must only be called from the I/O thread\n * @throws SwitchDriverSubHandshakeAlreadyStarted if the sub-handshake has\n * already been started\n */\n void startDriverHandshake();\n\n /**\n * Check if the sub-handshake for this switch driver has been completed.\n * This method can only be called after startDriverHandshake()\n *\n * This methods must only be called from the I/O thread\n * @return true if the sub-handshake has been completed. False otherwise\n * @throws SwitchDriverSubHandshakeNotStarted if startDriverHandshake() has\n * not been called yet.\n */\n boolean isDriverHandshakeComplete();\n\n /**\n * Pass the given OFMessage to the driver as part of this driver's\n * sub-handshake. Must not be called after the handshake has been completed\n * This methods must only be called from the I/O thread\n * @param m The message that the driver should process\n * @throws SwitchDriverSubHandshakeCompleted if isDriverHandshake() returns\n * false before this method call\n * @throws SwitchDriverSubHandshakeNotStarted if startDriverHandshake() has\n * not been called yet.\n */\n void processDriverHandshakeMessage(OFMessage m);\n\n void setPortDescStats(OFPortDescStatsReply portDescStats);\n\n /**\n * Cancel all pending request\n */\n void cancelAllPendingRequests();\n\n /** the the current HA role of this switch */\n void setControllerRole(OFControllerRole role);\n\n void setStatus(SwitchStatus switchStatus);\n\n /**\n * Updates the switch's mapping of controller connections\n * 更新交换机和控制器连接映射\n * @param controllerCxnsReply the controller connections message sent from the switch\n */\n void updateControllerConnections(OFBsnControllerConnectionsReply controllerCxnsReply);\n\n /**\n * Determines whether there is another master controller that the switches are\n * connected to by looking at the controller connections.\n * 是否另一个master存在\n * @return true if another viable master exists\n */\n boolean hasAnotherMaster();\n}", "public enum PluginResultType {\n CONTINUE(),\n DISCONNECT(),\n QUARANTINE();\n}", "public class QuarantineState extends OFSwitchHandshakeState {\n\n\tprivate final String quarantineReason;\n\n\tQuarantineState(String reason) {\n\t\tsuper(true);\n\t\tthis.quarantineReason = reason;\n\t}\n\n\t@Override\n\tpublic void enterState() {\n\t\tsetSwitchStatus(SwitchStatus.QUARANTINED);\n\t}\n\n\t@Override\n\tvoid processOFPortStatus(OFPortStatus m) {\n\t\thandlePortStatusMessage(m, false);\n\t}\n\n\tpublic String getQuarantineReason() {\n\t\treturn this.quarantineReason;\n\t}\n}", "public class WaitAppHandshakeState extends OFSwitchHandshakeState {\n\n\tprivate final Iterator<IAppHandshakePluginFactory> pluginIterator;\n\tprivate OFSwitchAppHandshakePlugin plugin;\n\n\tWaitAppHandshakeState() {\n\t\tsuper(false);\n\t\tthis.pluginIterator = switchManager.getHandshakePlugins().iterator();\n\t}\n\n\t@Override\n\tvoid processOFMessage(OFMessage m) {\n\t\tif(m.getType() == OFType.PORT_STATUS){\n\t\t\tOFPortStatus status = (OFPortStatus) m;\n\t\t\thandlePortStatusMessage(status, false);\n\t\t}\n\t\telse if(plugin != null){\n\t\t\tthis.plugin.processOFMessage(m);\n\t\t}\n\t\telse{\n\t\t\tsuper.processOFMessage(m);\n\t\t}\n\t}\n\n\t/**\n\t * Called by handshake plugins to signify that they have finished their\n\t * sub handshake.\n\t *\n\t * @param result\n\t * the result of the sub handshake\n\t */\n\tvoid exitPlugin(PluginResult result) {\n\n\t\t// Proceed\n\t\tif (result.getResultType() == PluginResultType.CONTINUE) {\n\t\t\tif (log.isDebugEnabled()) {\n\t\t\t\tlog.debug(\"Switch \" + getSwitchInfoString() + \" app handshake plugin {} returned {}.\"\n\t\t\t\t\t\t+ \" Proceeding normally..\",\n\t\t\t\t\t\tthis.plugin.getClass().getSimpleName(), result);\n\t\t\t}\n\n\t\t\tenterNextPlugin();\n\n\t\t\t// Stop\n\t\t} else if (result.getResultType() == PluginResultType.DISCONNECT) {\n\t\t\tlog.error(\"Switch \" + getSwitchInfoString() + \" app handshake plugin {} returned {}. \"\n\t\t\t\t\t+ \"Disconnecting switch.\",\n\t\t\t\t\tthis.plugin.getClass().getSimpleName(), result);\n\t\t\tmainConnection.disconnect();\n\t\t} else if (result.getResultType() == PluginResultType.QUARANTINE) {\n\t\t\tlog.warn(\"Switch \" + getSwitchInfoString() + \" app handshake plugin {} returned {}. \"\n\t\t\t\t\t+ \"Putting switch into quarantine state.\",\n\t\t\t\t\tthis.plugin.getClass().getSimpleName(),\n\t\t\t\t\tresult);\n\t\t\tsetState(new QuarantineState(result.getReason()));\n\t\t}\n\t}\n\n\t@Override\n\tpublic void enterState() {\n\t\tenterNextPlugin();\n\t}\n\n\t/**\n\t * Initialize the plugin and begin.\n\t *\n\t * @param plugin the of switch app handshake plugin\n\t */\n\tpublic void enterNextPlugin() {\n\t\tif(this.pluginIterator.hasNext()){\n\t\t\tthis.plugin = pluginIterator.next().createPlugin();\n\t\t\tthis.plugin.init(this, sw, timer);\n\t\t\tthis.plugin.enterPlugin();\n\t\t}\n\t\t// No more plugins left...\n\t\telse{\n\t\t\tsetState(new WaitInitialRoleState());\n\t\t}\n\t}\n\n\t@Override\n\tvoid processOFPortStatus(OFPortStatus m) {\n\t\thandlePortStatusMessage(m, false);\n\t}\n\n\tOFSwitchAppHandshakePlugin getCurrentPlugin() {\n\t\treturn plugin;\n\t}\n\n}", "public interface IDebugCounterService extends IFloodlightService {\n public enum MetaData {\n WARN,\n DROP,\n ERROR\n }\n\n /**\n * All modules that wish to have the DebugCounterService count for them, must\n * register themselves. If a module is registered multiple times subsequent\n * registrations will reset all counter in the module.\n *\t所有希望拥有DebugCounterService的模块必须注册。\n *\t如果模块在多个时间被注册,随后的注册将会重置模块中所有的计数器\n * @param moduleName\n * @return true if the module is registered for the first time, false if\n * the modue was previously registered\n * 当模块第一次注册时返回true,否则返回false\n */\n public boolean registerModule(String moduleName);\n\n /**\n * All modules that wish to have the DebugCounterService count for them, must\n * register their counters by making this call (typically from that module's\n * 'startUp' method). The counter can then be updated, displayed, reset etc.\n * using the registered moduleName and counterHierarchy.\n *\t所有希望拥有DebugCounterService的模块必须注册他们的计数器通过调用这个方法(通常从模块的startup方法)。\n *\t计数器之后能被更新,显示,重置等\n *\t使用moduleName和conterHierarchy\n * @param moduleName the name of the module which is registering the\n * counter eg. linkdiscovery or controller or switch\n * 哪一个模块注册的计数器\n * @param counterHierarchy the hierarchical counter name specifying all\n * the hierarchical levels that come above it.\n * For example: to register a drop counter for\n * packet-ins from a switch, the counterHierarchy\n * can be \"00:00:00:00:01:02:03:04/pktin/drops\"\n * It is necessary that counters in hierarchical levels\n * above have already been pre-registered - in this\n * example: \"00:00:00:00:01:02:03:04/pktin\" and\n * \"00:00:00:00:01:02:03:04\"\n * \n * @param counterDescription a descriptive string that gives more information\n * of what the counter is measuring. For example,\n * \"Measures the number of incoming packets seen by\n * this module\".\n * @param metaData variable arguments that qualify a counter\n * eg. warn, error etc.\n * @return IDebugCounter with update methods that can be\n * used to update a counter.\n */\n public IDebugCounter\n registerCounter(String moduleName, String counterHierarchy,\n String counterDescription, MetaData... metaData);\n\n\n /**\n * Resets the value of counters in the hierarchy to zero. Note that the reset\n * applies to the level of counter hierarchy specified AND ALL LEVELS BELOW it\n * in the hierarchy.\n * 重置控制器层次\n * 备注:重置适用于指定的计数器层次或所有的低于这个层次的计数器\n * For example: If a hierarchy exists like \"00:00:00:00:01:02:03:04/pktin/drops\"\n * specifying a reset hierarchy: \"00:00:00:00:01:02:03:04\"\n * will reset all counters for the switch dpid specified;\n * while specifying a reset hierarchy: \"\"00:00:00:00:01:02:03:04/pktin\"\n * will reset the pktin counter and all levels below it (like drops)\n * for the switch dpid specified.\n * @return false if the given moduleName, counterHierarchy\n * does not exist\n */\n public boolean resetCounterHierarchy(String moduleName, String counterHierarchy);\n\n /**\n * Resets the values of all counters in the system.\n * 重置所有计数器\n */\n public void resetAllCounters();\n\n /**\n * Resets the values of all counters belonging\n * to a module with the given 'moduleName'.\n * 重置属于指定模块的所有计数器\n * @return false if the given module name does not exists\n */\n public boolean resetAllModuleCounters(String moduleName);\n \n /**\n * Removes/deletes the counter hierarchy AND ALL LEVELS BELOW it in the hierarchy.\n * 移除/删除指定的计数器层次和低于此层次的计数器。\n * For example: If a hierarchy exists like \"00:00:00:00:01:02:03:04/pktin/drops\"\n * specifying a remove hierarchy: \"00:00:00:00:01:02:03:04\"\n * will remove all counters for the switch dpid specified;\n * while specifying a remove hierarchy: \"\"00:00:00:00:01:02:03:04/pktin\"\n * will remove the pktin counter and all levels below it (like drops)\n * for the switch dpid specified.\n * @return false if the given moduleName, counterHierarchy does not exist\n */\n public boolean removeCounterHierarchy(String moduleName, String counterHierarchy);\n\n\n /**\n * Get counter value and associated information for the specified counterHierarchy.\n * Note that information on the level of counter hierarchy specified\n * AND ALL LEVELS BELOW it in the hierarchy will be returned.\n * 得到计数器值和相应的信息从指定的层次中\n * 备注指定层级的信息和所有低于这个层级将会被返回\n * For example,\n * if a hierarchy exists like \"00:00:00:00:01:02:03:04/pktin/drops\", then\n * specifying a counterHierarchy of \"00:00:00:00:01:02:03:04/pktin\" in the\n * get call will return information on the 'pktin' as well as the 'drops'\n * counters for the switch dpid specified.\n *\n * If the module or hierarchy is not registered, returns an empty list\n *\n * @return A list of DebugCounterResource or an empty list if the counter\n * could not be found\n */\n public List<DebugCounterResource>\n getCounterHierarchy(String moduleName, String counterHierarchy);\n\n /**\n * Get counter values and associated information for all counters in the\n * system\n *\t得到所有的计数器值\n * @return the list of values/info or an empty list\n */\n public List<DebugCounterResource> getAllCounterValues();\n\n /**\n * Get counter values and associated information for all counters associated\n * with a module.\n * If the module is not registered, returns an empty list\n *\t得到所有的模块计数器值\n * @param moduleName\n * @return the list of values/info or an empty list\n */\n public List<DebugCounterResource> getModuleCounterValues(String moduleName);\n\n}" ]
import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.resetToStrict; import static org.easymock.EasyMock.verify; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.concurrent.TimeUnit; import net.dsc.cluster.HARole; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IOFSwitch.SwitchStatus; import net.floodlightcontroller.core.IOFSwitchBackend; import net.floodlightcontroller.core.PortChangeEvent; import net.floodlightcontroller.core.PortChangeType; import net.floodlightcontroller.core.internal.OFSwitchAppHandshakePlugin.PluginResultType; import net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler.QuarantineState; import net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler.WaitAppHandshakeState; import net.floodlightcontroller.debugcounter.DebugCounterServiceImpl; import net.floodlightcontroller.debugcounter.IDebugCounterService; import net.floodlightcontroller.util.LinkedHashSetWrapper; import net.floodlightcontroller.util.OrderedCollection; import org.easymock.EasyMock; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.projectfloodlight.openflow.protocol.OFBadActionCode; import org.projectfloodlight.openflow.protocol.OFBadRequestCode; import org.projectfloodlight.openflow.protocol.OFControllerRole; import org.projectfloodlight.openflow.protocol.OFDescStatsReply; import org.projectfloodlight.openflow.protocol.OFErrorMsg; import org.projectfloodlight.openflow.protocol.OFFactory; import org.projectfloodlight.openflow.protocol.OFFeaturesReply; import org.projectfloodlight.openflow.protocol.OFGetConfigReply; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPacketInReason; import org.projectfloodlight.openflow.protocol.OFPortDesc; import org.projectfloodlight.openflow.protocol.OFPortReason; import org.projectfloodlight.openflow.protocol.OFPortStatus; import org.projectfloodlight.openflow.protocol.OFSetConfig; import org.projectfloodlight.openflow.protocol.OFStatsRequest; import org.projectfloodlight.openflow.protocol.OFStatsType; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.protocol.match.Match; import org.projectfloodlight.openflow.types.DatapathId; import org.projectfloodlight.openflow.types.OFAuxId; import org.projectfloodlight.openflow.types.OFPort; import com.google.common.collect.ImmutableList;
assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(WaitAppHandshakeState.class)); WaitAppHandshakeState state = (WaitAppHandshakeState) switchHandler.getStateForTesting(); assertThat(state.getCurrentPlugin(), CoreMatchers.<OFSwitchAppHandshakePlugin>equalTo(handshakePlugin)); reset(sw); expect(sw.getStatus()).andReturn(SwitchStatus.HANDSHAKE); sw.setStatus(SwitchStatus.QUARANTINED); expectLastCall().once(); replay(sw); PluginResult result = new PluginResult(PluginResultType.QUARANTINE, "test quarantine"); handshakePlugin.exitPlugin(result); assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(QuarantineState.class)); verify(switchManager); } /** * Tests a situation where a plugin returns a DISCONNECT result. This means * we should disconnect the connection and the state should not change. * * @throws Exception */ @Test public void failedAppHandshake() throws Exception { moveToWaitAppHandshakeState(); assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(WaitAppHandshakeState.class)); WaitAppHandshakeState state = (WaitAppHandshakeState) switchHandler.getStateForTesting(); assertThat(state.getCurrentPlugin(), CoreMatchers.<OFSwitchAppHandshakePlugin>equalTo(handshakePlugin)); PluginResult result = new PluginResult(PluginResultType.DISCONNECT); handshakePlugin.exitPlugin(result); assertThat(connection.isConnected(), equalTo(false)); } @Test public void validAppHandshakePluginReason() throws Exception { try{ new PluginResult(PluginResultType.QUARANTINE,"This should not cause an exception"); }catch(IllegalStateException e) { fail("This should cause an illegal state exception"); } } @Test public void invalidAppHandshakePluginReason() throws Exception { try{ new PluginResult(PluginResultType.CONTINUE,"This should cause an exception"); fail("This should cause an illegal state exception"); }catch(IllegalStateException e) { /* Expected */ } try{ new PluginResult(PluginResultType.DISCONNECT,"This should cause an exception"); fail("This should cause an illegal state exception"); }catch(IllegalStateException e) { /* Expected */ } } /** * Move the channel from scratch to WAIT_INITIAL_ROLE state via * WAIT_SWITCH_DRIVER_SUB_HANDSHAKE * Does extensive testing for the WAIT_SWITCH_DRIVER_SUB_HANDSHAKE state * */ @Test public void testSwitchDriverSubHandshake() throws Exception { moveToWaitSwitchDriverSubHandshake(); //------------------------------------------------- //------------------------------------------------- // Send a message to the handler, it should be passed to the // switch's sub-handshake handling. After this message the // sub-handshake will be complete // FIXME:LOJI: With Andi's fix for a default Match object we won't // need to build/set this match object Match match = factory.buildMatch().build(); OFMessage m = factory.buildFlowRemoved().setMatch(match).build(); resetToStrict(sw); sw.processDriverHandshakeMessage(m); expectLastCall().once(); expect(sw.isDriverHandshakeComplete()).andReturn(true).once(); replay(sw); switchHandler.processOFMessage(m); assertThat(switchHandler.getStateForTesting(), CoreMatchers.instanceOf(OFSwitchHandshakeHandler.WaitAppHandshakeState.class)); assertThat("Unexpected message captured", connection.getMessages(), Matchers.empty()); verify(sw); } @Test /** Test WaitDescriptionReplyState */ public void testWaitDescriptionReplyState() throws Exception { moveToWaitInitialRole(); } /** * Setup the mock switch and write capture for a role request, set the * role and verify mocks. * @param supportsNxRole whether the switch supports role request messages * to setup the attribute. This must be null (don't yet know if roles * supported: send to check) or true. * @param role The role to send * @throws IOException */ private long setupSwitchSendRoleRequestAndVerify(Boolean supportsNxRole, OFControllerRole role) throws IOException { assertTrue("This internal test helper method most not be called " + "with supportsNxRole==false. Test setup broken", supportsNxRole == null || supportsNxRole == true); reset(sw);
expect(sw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE))
0
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/discord/BruteForceDiscordImplementation.java
[ "public final class EuclideanDistance {\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public EuclideanDistance() {\r\n super();\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param p1 The first point.\r\n * @param p2 The second point.\r\n * @return The Euclidean distance.\r\n */\r\n public double distance(double p1, double p2) {\r\n double d = (p1 - p2) * (p1 - p2);\r\n return Math.sqrt(d);\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double distance(double[] point1, double[] point2) throws Exception {\r\n return Math.sqrt(distance2(point1, point2));\r\n }\r\n\r\n /**\r\n * Calculates the Euclidean distance between two points.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double distance(int[] point1, int[] point2) throws Exception {\r\n return Math.sqrt(Long.valueOf(distance2(point1, point2)).doubleValue());\r\n }\r\n\r\n /**\r\n * Calculates the square of the Euclidean distance between two 1D points represented by real\r\n * values.\r\n * \r\n * @param p1 The first point.\r\n * @param p2 The second point.\r\n * @return The Square of Euclidean distance.\r\n */\r\n public double distance2(double p1, double p2) {\r\n return (p1 - p2) * (p1 - p2);\r\n }\r\n\r\n /**\r\n * Calculates the square of the Euclidean distance between two multidimensional points represented\r\n * by the rational vectors.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double distance2(double[] point1, double[] point2) throws Exception {\r\n if (point1.length == point2.length) {\r\n Double sum = 0D;\r\n for (int i = 0; i < point1.length; i++) {\r\n double tmp = point2[i] - point1[i];\r\n sum = sum + tmp * tmp;\r\n }\r\n return sum;\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * Calculates the square of the Euclidean distance between two multidimensional points represented\r\n * by integer vectors.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public long distance2(int[] point1, int[] point2) throws Exception {\r\n if (point1.length == point2.length) {\r\n long sum = 0;\r\n for (int i = 0; i < point1.length; i++) {\r\n sum = sum + (point2[i] - point1[i]) * (point2[i] - point1[i]);\r\n }\r\n return sum;\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * Calculates Euclidean distance between two multi-dimensional time-series of equal length.\r\n * \r\n * @param series1 The first series.\r\n * @param series2 The second series.\r\n * @return The eclidean distance.\r\n * @throws Exception if error occures.\r\n */\r\n public double seriesDistance(double[][] series1, double[][] series2) throws Exception {\r\n if (series1.length == series2.length) {\r\n Double res = 0D;\r\n for (int i = 0; i < series1.length; i++) {\r\n res = res + distance2(series1[i], series2[i]);\r\n }\r\n return Math.sqrt(res);\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * Calculates the Normalized Euclidean distance between two points.\r\n * \r\n * @param point1 The first point.\r\n * @param point2 The second point.\r\n * @return The Euclidean distance.\r\n * @throws Exception In the case of error.\r\n */\r\n public double normalizedDistance(double[] point1, double[] point2) throws Exception {\r\n return Math.sqrt(distance2(point1, point2)) / point1.length;\r\n }\r\n\r\n /**\r\n * Implements Euclidean distance with early abandoning.\r\n * \r\n * @param series1 the first series.\r\n * @param series2 the second series.\r\n * @param cutoff the cut-off threshold\r\n * @return the distance if it is less than cutoff or Double.NAN if it is above.\r\n * \r\n * @throws Exception if error occurs.\r\n */\r\n public Double earlyAbandonedDistance(double[] series1, double[] series2, double cutoff)\r\n throws Exception {\r\n if (series1.length == series2.length) {\r\n double cutOff2 = cutoff;\r\n if (Double.MAX_VALUE != cutoff) {\r\n cutOff2 = cutoff * cutoff;\r\n }\r\n Double res = 0D;\r\n for (int i = 0; i < series1.length; i++) {\r\n res = res + distance2(series1[i], series2[i]);\r\n if (res > cutOff2) {\r\n return Double.NaN;\r\n }\r\n }\r\n return Math.sqrt(res);\r\n }\r\n else {\r\n throw new Exception(\"Exception in Euclidean distance: array lengths are not equal\");\r\n }\r\n }\r\n\r\n}\r", "public final class SAXProcessor {\r\n\r\n private final TSProcessor tsProcessor;\r\n private final NormalAlphabet na;\r\n private EuclideanDistance ed;\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public SAXProcessor() {\r\n super();\r\n this.tsProcessor = new TSProcessor();\r\n this.na = new NormalAlphabet();\r\n this.ed = new EuclideanDistance();\r\n }\r\n\r\n /**\r\n * Convert the timeseries into SAX string representation.\r\n * \r\n * @param ts the timeseries.\r\n * @param paaSize the PAA size.\r\n * @param cuts the alphabet cuts.\r\n * @param nThreshold the normalization thresholds.\r\n * \r\n * @return The SAX representation for timeseries.\r\n * @throws SAXException if error occurs.\r\n */\r\n public char[] ts2string(double[] ts, int paaSize, double[] cuts, double nThreshold)\r\n throws SAXException {\r\n\r\n if (paaSize == ts.length) {\r\n return tsProcessor.ts2String(tsProcessor.znorm(ts, nThreshold), cuts);\r\n }\r\n else {\r\n // perform PAA conversion\r\n double[] paa = tsProcessor.paa(tsProcessor.znorm(ts, nThreshold), paaSize);\r\n return tsProcessor.ts2String(paa, cuts);\r\n }\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via chunking and Z normalization.\r\n * \r\n * @param ts the input data.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxByChunking(double[] ts, int paaSize, double[] cuts, double nThreshold)\r\n throws SAXException {\r\n\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n // Z normalize it\r\n double[] normalizedTS = tsProcessor.znorm(ts, nThreshold);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(normalizedTS, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n // create the datastructure\r\n for (int i = 0; i < currentString.length; i++) {\r\n char c = currentString[i];\r\n int pos = (int) Math.floor(i * ts.length / currentString.length);\r\n saxFrequencyData.add(String.valueOf(c).toCharArray(), pos);\r\n }\r\n\r\n return saxFrequencyData;\r\n\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via sliding window and Z\r\n * normalization.\r\n * \r\n * @param ts the input data.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * @param strategy the NR strategy.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxViaWindow(double[] ts, int windowSize, int paaSize, double[] cuts,\r\n NumerosityReductionStrategy strategy, double nThreshold) throws SAXException {\r\n\r\n if (windowSize > ts.length) {\r\n throw new SAXException(\r\n \"Unable to saxify via window, window size is greater than the timeseries length...\");\r\n }\r\n\r\n // the resulting data structure init\r\n //\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n // scan across the time series extract sub sequences, and convert them to strings\r\n char[] previousString = null;\r\n\r\n for (int i = 0; i <= ts.length - windowSize; i++) {\r\n\r\n // fix the current subsection\r\n double[] subSection = Arrays.copyOfRange(ts, i, i + windowSize);\r\n\r\n // Z normalize it\r\n subSection = tsProcessor.znorm(subSection, nThreshold);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(subSection, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n if (null != previousString) {\r\n\r\n if (NumerosityReductionStrategy.EXACT.equals(strategy)\r\n && Arrays.equals(previousString, currentString)) {\r\n // NumerosityReduction\r\n continue;\r\n }\r\n else if (NumerosityReductionStrategy.MINDIST.equals(strategy)\r\n && checkMinDistIsZero(previousString, currentString)) {\r\n continue;\r\n }\r\n\r\n }\r\n\r\n previousString = currentString;\r\n\r\n saxFrequencyData.add(currentString, i);\r\n }\r\n\r\n // ArrayList<Integer> keys = saxFrequencyData.getAllIndices();\r\n // for (int i : keys) {\r\n // System.out.println(i + \",\" + String.valueOf(saxFrequencyData.getByIndex(i).getPayload()));\r\n // }\r\n\r\n return saxFrequencyData;\r\n\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via sliding window and Z\r\n * normalization. The difference between this function and ts2saxViaWindow is that in this\r\n * function, Z normalization occurs on entire range, rather than the sliding window.\r\n * \r\n * @param ts the input data.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * @param strategy the NR strategy.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxViaWindowGlobalZNorm(double[] ts, int windowSize, int paaSize,\r\n double[] cuts, NumerosityReductionStrategy strategy, double nThreshold) throws SAXException {\r\n\r\n // the resulting data structure init\r\n //\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n // scan across the time series extract sub sequences, and convert them to strings\r\n char[] previousString = null;\r\n\r\n // normalize the entire range\r\n double[] normalizedData = tsProcessor.znorm(ts, nThreshold);\r\n\r\n for (int i = 0; i <= ts.length - windowSize; i++) {\r\n\r\n // get the current subsection\r\n double[] subSection = Arrays.copyOfRange(normalizedData, i, i + windowSize);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(subSection, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n if (null != previousString) {\r\n\r\n if (NumerosityReductionStrategy.EXACT.equals(strategy)\r\n && Arrays.equals(previousString, currentString)) {\r\n // NumerosityReduction\r\n continue;\r\n }\r\n else if (NumerosityReductionStrategy.MINDIST.equals(strategy)\r\n && checkMinDistIsZero(previousString, currentString)) {\r\n continue;\r\n }\r\n\r\n }\r\n\r\n previousString = currentString;\r\n\r\n saxFrequencyData.add(currentString, i);\r\n }\r\n\r\n return saxFrequencyData;\r\n\r\n }\r\n\r\n /**\r\n * Converts the input time series into a SAX data structure via sliding window and Z\r\n * normalization.\r\n * \r\n * @param ts the input data.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA size.\r\n * @param cuts the Alphabet cuts.\r\n * @param nThreshold the normalization threshold value.\r\n * @param strategy the NR strategy.\r\n * @param skips The list of points which shall be skipped during conversion; this feature is\r\n * particularly important when building a concatenated from pieces time series and junction shall\r\n * not make it into the grammar.\r\n * \r\n * @return SAX representation of the time series.\r\n * @throws SAXException if error occurs.\r\n */\r\n public SAXRecords ts2saxViaWindowSkipping(double[] ts, int windowSize, int paaSize, double[] cuts,\r\n NumerosityReductionStrategy strategy, double nThreshold, ArrayList<Integer> skips)\r\n throws SAXException {\r\n\r\n // the resulting data structure init\r\n //\r\n SAXRecords saxFrequencyData = new SAXRecords();\r\n\r\n Collections.sort(skips);\r\n int cSkipIdx = 0;\r\n\r\n // scan across the time series extract sub sequences, and convert them to strings\r\n char[] previousString = null;\r\n boolean skipped = false;\r\n\r\n for (int i = 0; i < ts.length - (windowSize - 1); i++) {\r\n\r\n // skip what need to be skipped\r\n if (cSkipIdx < skips.size() && i == skips.get(cSkipIdx)) {\r\n cSkipIdx = cSkipIdx + 1;\r\n skipped = true;\r\n continue;\r\n }\r\n\r\n // fix the current subsection\r\n double[] subSection = Arrays.copyOfRange(ts, i, i + windowSize);\r\n\r\n // Z normalize it\r\n subSection = tsProcessor.znorm(subSection, nThreshold);\r\n\r\n // perform PAA conversion if needed\r\n double[] paa = tsProcessor.paa(subSection, paaSize);\r\n\r\n // Convert the PAA to a string.\r\n char[] currentString = tsProcessor.ts2String(paa, cuts);\r\n\r\n if (!(skipped) && null != previousString) {\r\n\r\n if (NumerosityReductionStrategy.EXACT.equals(strategy)\r\n && Arrays.equals(previousString, currentString)) {\r\n // NumerosityReduction\r\n continue;\r\n }\r\n else if (NumerosityReductionStrategy.MINDIST.equals(strategy)\r\n && checkMinDistIsZero(previousString, currentString)) {\r\n continue;\r\n }\r\n\r\n }\r\n\r\n previousString = currentString;\r\n if (skipped) {\r\n skipped = false;\r\n }\r\n\r\n saxFrequencyData.add(currentString, i);\r\n }\r\n\r\n return saxFrequencyData;\r\n }\r\n\r\n /**\r\n * Compute the distance between the two chars based on the ASCII symbol codes.\r\n * \r\n * @param a The first char.\r\n * @param b The second char.\r\n * @return The distance.\r\n */\r\n public int charDistance(char a, char b) {\r\n return Math.abs(Character.getNumericValue(a) - Character.getNumericValue(b));\r\n }\r\n\r\n /**\r\n * Compute the distance between the two strings, this function use the numbers associated with\r\n * ASCII codes, i.e. distance between a and b would be 1.\r\n * \r\n * @param a The first string.\r\n * @param b The second string.\r\n * @return The pairwise distance.\r\n * @throws SAXException if length are differ.\r\n */\r\n public int strDistance(char[] a, char[] b) throws SAXException {\r\n if (a.length == b.length) {\r\n int distance = 0;\r\n for (int i = 0; i < a.length; i++) {\r\n int tDist = Math.abs(Character.getNumericValue(a[i]) - Character.getNumericValue(b[i]));\r\n distance += tDist;\r\n }\r\n return distance;\r\n }\r\n else {\r\n throw new SAXException(\"Unable to compute SAX distance, string lengths are not equal\");\r\n }\r\n }\r\n\r\n /**\r\n * This function implements SAX MINDIST function which uses alphabet based distance matrix.\r\n * \r\n * @param a The SAX string.\r\n * @param b The SAX string.\r\n * @param distanceMatrix The distance matrix to use.\r\n * @param n the time series length (sliding window length).\r\n * @param w the number of PAA segments.\r\n * @return distance between strings.\r\n * @throws SAXException If error occurs.\r\n */\r\n public double saxMinDist(char[] a, char[] b, double[][] distanceMatrix, int n, int w)\r\n throws SAXException {\r\n if (a.length == b.length) {\r\n double dist = 0.0D;\r\n for (int i = 0; i < a.length; i++) {\r\n if (Character.isLetter(a[i]) && Character.isLetter(b[i])) {\r\n // ... forms have numeric values from 10 through 35\r\n int numA = Character.getNumericValue(a[i]) - 10;\r\n int numB = Character.getNumericValue(b[i]) - 10;\r\n int maxIdx = distanceMatrix[0].length;\r\n if (numA > (maxIdx - 1) || numA < 0 || numB > (maxIdx - 1) || numB < 0) {\r\n throw new SAXException(\r\n \"The character index greater than \" + maxIdx + \" or less than 0!\");\r\n }\r\n double localDist = distanceMatrix[numA][numB];\r\n dist = dist + localDist * localDist;\r\n }\r\n else {\r\n throw new SAXException(\"Non-literal character found!\");\r\n }\r\n }\r\n return Math.sqrt((double) n / (double) w) * Math.sqrt(dist);\r\n }\r\n else {\r\n throw new SAXException(\"Data arrays lengths are not equal!\");\r\n }\r\n }\r\n\r\n /**\r\n * Check for trivial mindist case.\r\n * \r\n * @param a first string.\r\n * @param b second string.\r\n * @return true if mindist between strings is zero.\r\n */\r\n public boolean checkMinDistIsZero(char[] a, char[] b) {\r\n for (int i = 0; i < a.length; i++) {\r\n if (charDistance(a[i], b[i]) > 1) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Computes the distance between approximated values and the real TS.\r\n * \r\n * @param ts the timeseries.\r\n * @param winSize SAX window size.\r\n * @param paaSize SAX PAA size.\r\n * @param normThreshold the normalization threshold.\r\n * @return the distance value.\r\n * @throws Exception if error occurs.\r\n */\r\n public double approximationDistancePAA(double[] ts, int winSize, int paaSize,\r\n double normThreshold) throws Exception {\r\n\r\n double resDistance = 0d;\r\n int windowCounter = 0;\r\n\r\n double pointsPerWindow = (double) winSize / (double) paaSize;\r\n\r\n for (int i = 0; i < ts.length - winSize + 1; i++) {\r\n\r\n double[] subseries = Arrays.copyOfRange(ts, i, i + winSize);\r\n\r\n if (tsProcessor.stDev(subseries) > normThreshold) {\r\n subseries = tsProcessor.znorm(subseries, normThreshold);\r\n }\r\n\r\n double[] paa = tsProcessor.paa(subseries, paaSize);\r\n\r\n windowCounter++;\r\n\r\n // essentially the distance here is the distance between the segment's\r\n // PAA value and the real TS value\r\n //\r\n double subsequenceDistance = 0.;\r\n for (int j = 0; j < subseries.length; j++) {\r\n\r\n int paaIdx = (int) Math.floor(((double) j + 0.5) / (double) pointsPerWindow);\r\n if (paaIdx < 0) {\r\n paaIdx = 0;\r\n }\r\n if (paaIdx > paa.length) {\r\n paaIdx = paa.length - 1;\r\n }\r\n\r\n subsequenceDistance = subsequenceDistance + ed.distance(paa[paaIdx], subseries[j]);\r\n }\r\n\r\n resDistance = resDistance + subsequenceDistance / subseries.length;\r\n }\r\n return resDistance / (double) windowCounter;\r\n }\r\n\r\n /**\r\n * Computes the distance between approximated values and the real TS.\r\n * \r\n * @param ts the timeseries.\r\n * @param winSize SAX window size.\r\n * @param paaSize SAX PAA size.\r\n * @param alphabetSize SAX alphabet size.\r\n * @param normThreshold the normalization threshold.\r\n * @return the distance value.\r\n * @throws Exception if error occurs.\r\n */\r\n public double approximationDistanceAlphabet(double[] ts, int winSize, int paaSize,\r\n int alphabetSize, double normThreshold) throws Exception {\r\n\r\n double resDistance = 0d;\r\n int windowCounter = 0;\r\n\r\n double[] centralLines = na.getCentralCuts(alphabetSize);\r\n double[] cuts = na.getCuts(alphabetSize);\r\n\r\n for (int i = 0; i < ts.length - winSize + 1; i++) {\r\n\r\n double[] subseries = Arrays.copyOfRange(ts, i, i + winSize);\r\n double subsequenceDistance = 0.;\r\n\r\n if (tsProcessor.stDev(subseries) > normThreshold) {\r\n subseries = tsProcessor.znorm(subseries, normThreshold);\r\n }\r\n\r\n double[] paa = tsProcessor.paa(subseries, paaSize);\r\n int[] leterIndexes = tsProcessor.ts2Index(paa, cuts);\r\n\r\n windowCounter++;\r\n\r\n // essentially the distance here is the distance between the segment's\r\n // PAA value and the real TS value\r\n //\r\n for (int j = 0; j < paa.length; j++) {\r\n // compute the alphabet central cut line\r\n int letterIdx = leterIndexes[j];\r\n double cLine = centralLines[letterIdx];\r\n subsequenceDistance = subsequenceDistance + ed.distance(cLine, paa[j]);\r\n }\r\n\r\n resDistance = resDistance + subsequenceDistance / paa.length;\r\n }\r\n\r\n return resDistance / (double) windowCounter;\r\n }\r\n\r\n /**\r\n * Converts a single time-series into map of shingle frequencies.\r\n * \r\n * @param series the time series.\r\n * @param windowSize the sliding window size.\r\n * @param paaSize the PAA segments number.\r\n * @param alphabetSize the alphabet size.\r\n * @param strategy the numerosity reduction strategy.\r\n * @param nrThreshold the SAX normalization threshold.\r\n * @param shingleSize the shingle size.\r\n * \r\n * @return map of shingle frequencies.\r\n * @throws SAXException if error occurs.\r\n */\r\n public Map<String, Integer> ts2Shingles(double[] series, int windowSize, int paaSize,\r\n int alphabetSize, NumerosityReductionStrategy strategy, double nrThreshold, int shingleSize)\r\n throws SAXException {\r\n\r\n // build all shingles\r\n String[] alphabet = new String[alphabetSize];\r\n for (int i = 0; i < alphabetSize; i++) {\r\n alphabet[i] = String.valueOf(TSProcessor.ALPHABET[i]);\r\n }\r\n String[] allShingles = getAllPermutations(alphabet, shingleSize);\r\n\r\n // result\r\n HashMap<String, Integer> res = new HashMap<String, Integer>(allShingles.length);\r\n for (String s : allShingles) {\r\n res.put(s, 0);\r\n }\r\n\r\n // discretize\r\n SAXRecords saxData = ts2saxViaWindow(series, windowSize, paaSize, na.getCuts(alphabetSize),\r\n strategy, nrThreshold);\r\n\r\n // fill in the counts\r\n for (SAXRecord sr : saxData) {\r\n String word = String.valueOf(sr.getPayload());\r\n int frequency = sr.getIndexes().size();\r\n for (int i = 0; i <= word.length() - shingleSize; i++) {\r\n String shingle = word.substring(i, i + shingleSize);\r\n res.put(shingle, res.get(shingle) + frequency);\r\n }\r\n }\r\n\r\n return res;\r\n }\r\n\r\n /**\r\n * Get all permutations of the given alphabet of given length.\r\n * \r\n * @param alphabet the alphabet to use.\r\n * @param wordLength the word length.\r\n * @return set of permutation.\r\n */\r\n public static String[] getAllPermutations(String[] alphabet, int wordLength) {\r\n\r\n // initialize our returned list with the number of elements calculated above\r\n String[] allLists = new String[(int) Math.pow(alphabet.length, wordLength)];\r\n\r\n // lists of length 1 are just the original elements\r\n if (wordLength == 1)\r\n return alphabet;\r\n else {\r\n // the recursion--get all lists of length 3, length 2, all the way up to 1\r\n String[] allSublists = getAllPermutations(alphabet, wordLength - 1);\r\n\r\n // append the sublists to each element\r\n int arrayIndex = 0;\r\n\r\n for (int i = 0; i < alphabet.length; i++) {\r\n for (int j = 0; j < allSublists.length; j++) {\r\n // add the newly appended combination to the list\r\n allLists[arrayIndex] = alphabet[i] + allSublists[j];\r\n arrayIndex++;\r\n }\r\n }\r\n\r\n return allLists;\r\n }\r\n }\r\n\r\n /**\r\n * Generic method to convert the milliseconds into the elapsed time string.\r\n * \r\n * @param start Start timestamp.\r\n * @param finish End timestamp.\r\n * @return String representation of the elapsed time.\r\n */\r\n public static String timeToString(long start, long finish) {\r\n\r\n long millis = finish - start;\r\n\r\n if (millis < 0) {\r\n throw new IllegalArgumentException(\"Duration must be greater than zero!\");\r\n }\r\n\r\n long days = TimeUnit.MILLISECONDS.toDays(millis);\r\n millis -= TimeUnit.DAYS.toMillis(days);\r\n long hours = TimeUnit.MILLISECONDS.toHours(millis);\r\n millis -= TimeUnit.HOURS.toMillis(hours);\r\n long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);\r\n millis -= TimeUnit.MINUTES.toMillis(minutes);\r\n long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);\r\n millis -= TimeUnit.SECONDS.toMillis(seconds);\r\n\r\n StringBuilder sb = new StringBuilder(64);\r\n sb.append(days);\r\n sb.append(\"d\");\r\n sb.append(hours);\r\n sb.append(\"h\");\r\n sb.append(minutes);\r\n sb.append(\"m\");\r\n sb.append(seconds);\r\n sb.append(\"s\");\r\n sb.append(millis);\r\n sb.append(\"ms\");\r\n\r\n return sb.toString();\r\n\r\n }\r\n}\r", "public class TSProcessor {\r\n\r\n private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;\r\n\r\n /** The latin alphabet, lower case letters a-z. */\r\n public static final char[] ALPHABET = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\r\n 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };\r\n\r\n // static block - we instantiate the logger\r\n //\r\n private static final Logger LOGGER = LoggerFactory.getLogger(TSProcessor.class);\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public TSProcessor() {\r\n super();\r\n }\r\n\r\n /**\r\n * Reads timeseries from a file. Assumes that file has a single double value on every line.\r\n * Assigned timestamps are the line numbers.\r\n * \r\n * @param filename The file to read from.\r\n * @param columnIdx The column index.\r\n * @param sizeLimit The number of lines to read, 0 == all.\r\n * @return data.\r\n * @throws IOException if error occurs.\r\n * @throws SAXException if error occurs.\r\n */\r\n public static double[] readFileColumn(String filename, int columnIdx, int sizeLimit)\r\n throws IOException, SAXException {\r\n\r\n // make sure the path exists\r\n Path path = Paths.get(filename);\r\n if (!(Files.exists(path))) {\r\n throw new SAXException(\"unable to load data - data source not found.\");\r\n }\r\n\r\n BufferedReader br = new BufferedReader(\r\n new InputStreamReader(new FileInputStream(filename), \"UTF-8\"));\r\n\r\n return readTS(br, columnIdx, sizeLimit);\r\n }\r\n\r\n /**\r\n * Reads timeseries from a file. Assumes that file has a single double value on every line.\r\n * Assigned timestamps are the line numbers.\r\n * \r\n * @param br The reader to use.\r\n * @param columnIdx The column index.\r\n * @param sizeLimit The number of lines to read, 0 == all.\r\n * @return data.\r\n * @throws IOException if error occurs.\r\n * @throws SAXException if error occurs.\r\n */\r\n public static double[] readTS(BufferedReader br, int columnIdx, int sizeLimit)\r\n throws IOException, SAXException {\r\n ArrayList<Double> preRes = new ArrayList<Double>();\r\n int lineCounter = 0;\r\n\r\n String line = null;\r\n while ((line = br.readLine()) != null) {\r\n String[] split = line.trim().split(\"\\\\s+\");\r\n if (split.length < columnIdx) {\r\n String message = \"Unable to read data from column \" + columnIdx;\r\n br.close();\r\n throw new SAXException(message);\r\n }\r\n String str = split[columnIdx];\r\n double num = Double.NaN;\r\n try {\r\n num = Double.valueOf(str);\r\n }\r\n catch (NumberFormatException e) {\r\n LOGGER.info(\"Skipping the row \" + lineCounter + \" with value \\\"\" + str + \"\\\"\");\r\n continue;\r\n }\r\n preRes.add(num);\r\n lineCounter++;\r\n if ((0 != sizeLimit) && (lineCounter >= sizeLimit)) {\r\n break;\r\n }\r\n }\r\n br.close();\r\n double[] res = new double[preRes.size()];\r\n for (int i = 0; i < preRes.size(); i++) {\r\n res[i] = preRes.get(i);\r\n }\r\n return res;\r\n\r\n }\r\n\r\n /**\r\n * Read at least N elements from the one-column file.\r\n * \r\n * @param dataFileName the file name.\r\n * @param loadLimit the load limit.\r\n * @return the read data or empty array if nothing to load.\r\n * @throws SAXException if error occurs.\r\n * @throws IOException if error occurs.\r\n */\r\n public double[] readTS(String dataFileName, int loadLimit) throws SAXException, IOException {\r\n\r\n Path path = Paths.get(dataFileName);\r\n if (!(Files.exists(path))) {\r\n throw new SAXException(\"unable to load data - data source not found.\");\r\n }\r\n\r\n BufferedReader reader = Files.newBufferedReader(path, DEFAULT_CHARSET);\r\n\r\n return readTS(reader, 0, loadLimit);\r\n\r\n }\r\n\r\n /**\r\n * Finds the maximal value in timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The max value.\r\n */\r\n public double max(double[] series) {\r\n double max = Double.MIN_VALUE;\r\n for (int i = 0; i < series.length; i++) {\r\n if (max < series[i]) {\r\n max = series[i];\r\n }\r\n }\r\n return max;\r\n }\r\n\r\n /**\r\n * Finds the minimal value in timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The min value.\r\n */\r\n public double min(double[] series) {\r\n double min = Double.MAX_VALUE;\r\n for (int i = 0; i < series.length; i++) {\r\n if (min > series[i]) {\r\n min = series[i];\r\n }\r\n }\r\n return min;\r\n }\r\n\r\n /**\r\n * Computes the mean value of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The mean value.\r\n */\r\n public double mean(double[] series) {\r\n double res = 0D;\r\n int count = 0;\r\n for (double tp : series) {\r\n res += tp;\r\n count += 1;\r\n\r\n }\r\n if (count > 0) {\r\n return res / ((Integer) count).doubleValue();\r\n }\r\n return Double.NaN;\r\n }\r\n\r\n /**\r\n * Computes the mean value of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The mean value.\r\n */\r\n public double mean(int[] series) {\r\n double res = 0D;\r\n int count = 0;\r\n for (int tp : series) {\r\n res += (double) tp;\r\n count += 1;\r\n\r\n }\r\n if (count > 0) {\r\n return res / ((Integer) count).doubleValue();\r\n }\r\n return Double.NaN;\r\n }\r\n\r\n /**\r\n * Computes the median value of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The median value.\r\n */\r\n public double median(double[] series) {\r\n double[] clonedSeries = series.clone();\r\n Arrays.sort(clonedSeries);\r\n\r\n double median;\r\n if (clonedSeries.length % 2 == 0) {\r\n median = (clonedSeries[clonedSeries.length / 2]\r\n + (double) clonedSeries[clonedSeries.length / 2 - 1]) / 2;\r\n }\r\n else {\r\n median = clonedSeries[clonedSeries.length / 2];\r\n }\r\n return median;\r\n }\r\n\r\n /**\r\n * Compute the variance of timeseries.\r\n * \r\n * @param series The timeseries.\r\n * @return The variance.\r\n */\r\n public double var(double[] series) {\r\n double res = 0D;\r\n double mean = mean(series);\r\n int count = 0;\r\n for (double tp : series) {\r\n res += (tp - mean) * (tp - mean);\r\n count += 1;\r\n }\r\n if (count > 0) {\r\n return res / ((Integer) (count - 1)).doubleValue();\r\n }\r\n return Double.NaN;\r\n }\r\n\r\n /**\r\n * Speed-optimized implementation.\r\n * \r\n * @param series The timeseries.\r\n * @return the standard deviation.\r\n */\r\n public double stDev(double[] series) {\r\n double num0 = 0D;\r\n double sum = 0D;\r\n int count = 0;\r\n for (double tp : series) {\r\n num0 = num0 + tp * tp;\r\n sum = sum + tp;\r\n count += 1;\r\n }\r\n double len = ((Integer) count).doubleValue();\r\n return Math.sqrt((len * num0 - sum * sum) / (len * (len - 1)));\r\n }\r\n\r\n /**\r\n * Z-Normalize routine.\r\n * \r\n * @param series the input timeseries.\r\n * @param normalizationThreshold the zNormalization threshold value.\r\n * @return Z-normalized time-series.\r\n */\r\n public double[] znorm(double[] series, double normalizationThreshold) {\r\n double[] res = new double[series.length];\r\n double sd = stDev(series);\r\n if (sd < normalizationThreshold) {\r\n // return series.clone();\r\n // return array of zeros\r\n return res;\r\n }\r\n double mean = mean(series);\r\n for (int i = 0; i < res.length; i++) {\r\n res[i] = (series[i] - mean) / sd;\r\n }\r\n return res;\r\n }\r\n\r\n /**\r\n * Approximate the timeseries using PAA. If the timeseries has some NaN's they are handled as\r\n * follows: 1) if all values of the piece are NaNs - the piece is approximated as NaN, 2) if there\r\n * are some (more or equal one) values happened to be in the piece - algorithm will handle it as\r\n * usual - getting the mean.\r\n * \r\n * @param ts The timeseries to approximate.\r\n * @param paaSize The desired length of approximated timeseries.\r\n * @return PAA-approximated timeseries.\r\n * @throws SAXException if error occurs.\r\n * \r\n */\r\n public double[] paa(double[] ts, int paaSize) throws SAXException {\r\n // fix the length\r\n int len = ts.length;\r\n if (len < paaSize) {\r\n throw new SAXException(\"PAA size can't be greater than the timeseries size.\");\r\n }\r\n // check for the trivial case\r\n if (len == paaSize) {\r\n return Arrays.copyOf(ts, ts.length);\r\n }\r\n else {\r\n double[] paa = new double[paaSize];\r\n double pointsPerSegment = (double) len / (double) paaSize;\r\n double[] breaks = new double[paaSize + 1];\r\n for (int i = 0; i < paaSize + 1; i++) {\r\n breaks[i] = i * pointsPerSegment;\r\n }\r\n\r\n for (int i = 0; i < paaSize; i++) {\r\n double segStart = breaks[i];\r\n double segEnd = breaks[i + 1];\r\n\r\n double fractionStart = Math.ceil(segStart) - segStart;\r\n double fractionEnd = segEnd - Math.floor(segEnd);\r\n\r\n int fullStart = Double.valueOf(Math.floor(segStart)).intValue();\r\n int fullEnd = Double.valueOf(Math.ceil(segEnd)).intValue();\r\n\r\n double[] segment = Arrays.copyOfRange(ts, fullStart, fullEnd);\r\n\r\n if (fractionStart > 0) {\r\n segment[0] = segment[0] * fractionStart;\r\n }\r\n\r\n if (fractionEnd > 0) {\r\n segment[segment.length - 1] = segment[segment.length - 1] * fractionEnd;\r\n }\r\n\r\n double elementsSum = 0.0;\r\n for (double e : segment) {\r\n elementsSum = elementsSum + e;\r\n }\r\n\r\n paa[i] = elementsSum / pointsPerSegment;\r\n\r\n }\r\n return paa;\r\n }\r\n }\r\n\r\n /**\r\n * Converts the timeseries into string using given cuts intervals. Useful for not-normal\r\n * distribution cuts.\r\n * \r\n * @param vals The timeseries.\r\n * @param cuts The cut intervals.\r\n * @return The timeseries SAX representation.\r\n */\r\n public char[] ts2String(double[] vals, double[] cuts) {\r\n char[] res = new char[vals.length];\r\n for (int i = 0; i < vals.length; i++) {\r\n res[i] = num2char(vals[i], cuts);\r\n }\r\n return res;\r\n }\r\n\r\n /**\r\n * Convert the timeseries into the index using SAX cuts.\r\n * \r\n * @param series The timeseries to convert.\r\n * @param cuts The alphabet cuts.\r\n * @return SAX cuts indices.\r\n * @throws Exception if error occurs.\r\n */\r\n public int[] ts2Index(double[] series, double[] cuts) throws Exception {\r\n int[] res = new int[series.length];\r\n for (int i = 0; i < series.length; i++) {\r\n res[i] = num2index(series[i], cuts);\r\n }\r\n return res;\r\n }\r\n\r\n /**\r\n * Get mapping of a number to char.\r\n * \r\n * @param value the value to map.\r\n * @param cuts the array of intervals.\r\n * @return character corresponding to numeric value.\r\n */\r\n public char num2char(double value, double[] cuts) {\r\n int idx = 0;\r\n if (value >= 0) {\r\n idx = cuts.length;\r\n while ((idx > 0) && (cuts[idx - 1] > value)) {\r\n idx--;\r\n }\r\n }\r\n else {\r\n while ((idx < cuts.length) && (cuts[idx] <= value)) {\r\n idx++;\r\n }\r\n }\r\n return ALPHABET[idx];\r\n }\r\n\r\n /**\r\n * Converts index into char.\r\n * \r\n * @param idx The index value.\r\n * @return The char by index.\r\n */\r\n public char num2char(int idx) {\r\n return ALPHABET[idx];\r\n }\r\n\r\n /**\r\n * Get mapping of number to cut index.\r\n * \r\n * @param value the value to map.\r\n * @param cuts the array of intervals.\r\n * @return character corresponding to numeric value.\r\n */\r\n public int num2index(double value, double[] cuts) {\r\n int count = 0;\r\n while ((count < cuts.length) && (cuts[count] <= value)) {\r\n count++;\r\n }\r\n return count;\r\n }\r\n\r\n /**\r\n * Extract subseries out of series.\r\n * \r\n * @param series The series array.\r\n * @param start the fragment start.\r\n * @param end the fragment end.\r\n * @return The subseries.\r\n * @throws IndexOutOfBoundsException If error occurs.\r\n */\r\n public double[] subseriesByCopy(double[] series, int start, int end)\r\n throws IndexOutOfBoundsException {\r\n if ((start > end) || (start < 0) || (end > series.length)) {\r\n throw new IndexOutOfBoundsException(\"Unable to extract subseries, series length: \"\r\n + series.length + \", start: \" + start + \", end: \" + String.valueOf(end - start));\r\n }\r\n return Arrays.copyOfRange(series, start, end);\r\n }\r\n\r\n /**\r\n * Prettyfies the timeseries for screen output.\r\n * \r\n * @param series the data.\r\n * @param df the number format to use.\r\n * \r\n * @return The timeseries formatted for screen output.\r\n */\r\n public String seriesToString(double[] series, NumberFormat df) {\r\n StringBuffer sb = new StringBuffer();\r\n sb.append('[');\r\n for (double d : series) {\r\n sb.append(df.format(d)).append(',');\r\n }\r\n sb.delete(sb.length() - 2, sb.length() - 1).append(\"]\");\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * Normalizes data in interval 0-1.\r\n * \r\n * @param data the dataset.\r\n * @return normalized dataset.\r\n */\r\n public double[] normOne(double[] data) {\r\n double[] res = new double[data.length];\r\n double max = max(data);\r\n for (int i = 0; i < data.length; i++) {\r\n res[i] = data[i] / max;\r\n }\r\n return res;\r\n }\r\n\r\n}\r", "public interface SlidingWindowMarkerAlgorithm {\n\n /**\n * Marks visited locations (of the magic array).\n * \n * @param registry The magic array instance.\n * @param startPosition The position to start labeling from.\n * @param intervalLength The length of the interval to be labeled.\n */\n void markVisited(VisitRegistry registry, int startPosition, int intervalLength);\n\n}", "public class VisitRegistry implements Cloneable {\n\n private static final byte ZERO = 0;\n private static final byte ONE = 1;\n\n protected byte[] registry; // 1 visited, 0 unvisited\n\n private int unvisitedCount; // unvisited counter\n\n private final Random randomizer = new Random(System.currentTimeMillis());\n\n /**\n * Constructor.\n * \n * @param capacity The initial capacity.\n */\n public VisitRegistry(int capacity) {\n super();\n this.registry = new byte[capacity];\n this.unvisitedCount = capacity;\n }\n\n /**\n * Disabling the default constructor.\n */\n @SuppressWarnings(\"unused\")\n private VisitRegistry() {\n super();\n }\n\n /**\n * Marks location visited. If it was unvisited, counter decremented.\n * \n * @param loc The location to mark.\n */\n public void markVisited(int loc) {\n if (checkBounds(loc)) {\n if (ZERO == this.registry[loc]) {\n this.unvisitedCount--;\n }\n this.registry[loc] = ONE;\n }\n else {\n throw new RuntimeException(\n \"The location \" + loc + \" out of bounds [0,\" + (this.registry.length - 1) + \"]\");\n }\n }\n\n /**\n * Marks as visited a range of locations.\n * \n * @param from the start of labeling (inclusive).\n * @param upTo the end of labeling (exclusive).\n */\n public void markVisited(int from, int upTo) {\n if (checkBounds(from) && checkBounds(upTo - 1)) {\n for (int i = from; i < upTo; i++) {\n this.markVisited(i);\n }\n }\n else {\n throw new RuntimeException(\"The location \" + from + \",\" + upTo + \" out of bounds [0,\"\n + (this.registry.length - 1) + \"]\");\n }\n }\n\n /**\n * Get the next random unvisited position.\n * \n * @return The next unvisited position.\n */\n public int getNextRandomUnvisitedPosition() {\n\n // if all are visited, return -1\n //\n if (0 == this.unvisitedCount) {\n return -1;\n }\n\n // if there is space continue with random sampling\n //\n int i = this.randomizer.nextInt(this.registry.length);\n while (ONE == registry[i]) {\n i = this.randomizer.nextInt(this.registry.length);\n }\n return i;\n }\n\n /**\n * Check if position is not visited.\n * \n * @param loc The index.\n * @return true if not visited.\n */\n public boolean isNotVisited(int loc) {\n if (checkBounds(loc)) {\n return (ZERO == this.registry[loc]);\n }\n else {\n throw new RuntimeException(\n \"The location \" + loc + \" out of bounds [0,\" + (this.registry.length - 1) + \"]\");\n }\n }\n\n /**\n * Check if the interval and its boundaries were visited.\n * \n * @param from The interval start (inclusive).\n * @param upTo The interval end (exclusive).\n * @return True if visited.\n */\n public boolean isVisited(int from, int upTo) {\n if (checkBounds(from) && checkBounds(upTo - 1)) {\n // perform the visit check\n //\n for (int i = from; i < upTo; i++) {\n if (ONE == this.registry[i]) {\n return true;\n }\n }\n return false;\n }\n else {\n throw new RuntimeException(\"The location \" + from + \",\" + upTo + \" out of bounds [0,\"\n + (this.registry.length - 1) + \"]\");\n }\n }\n\n /**\n * Check if the location specified is visited.\n * \n * @param loc the location.\n * @return true if visited\n */\n public boolean isVisited(int loc) {\n if (checkBounds(loc)) {\n return (ONE == this.registry[loc]);\n }\n else {\n throw new RuntimeException(\n \"The location \" + loc + \" out of bounds [0,\" + (this.registry.length - 1) + \"]\");\n }\n\n }\n\n /**\n * Get the list of unvisited positions.\n * \n * @return list of unvisited positions.\n */\n public ArrayList<Integer> getUnvisited() {\n if (0 == this.unvisitedCount) {\n return new ArrayList<Integer>();\n }\n ArrayList<Integer> res = new ArrayList<Integer>(this.unvisitedCount);\n for (int i = 0; i < this.registry.length; i++) {\n if (ZERO == this.registry[i]) {\n res.add(i);\n }\n }\n return res;\n }\n\n /**\n * Get the list of visited positions. Returns NULL if none are visited.\n * \n * @return list of visited positions.\n */\n public ArrayList<Integer> getVisited() {\n if (0 == (this.registry.length - this.unvisitedCount)) {\n return new ArrayList<Integer>();\n }\n ArrayList<Integer> res = new ArrayList<Integer>(this.registry.length - this.unvisitedCount);\n for (int i = 0; i < this.registry.length; i++) {\n if (ONE == this.registry[i]) {\n res.add(i);\n }\n }\n return res;\n }\n\n /**\n * Transfers all visited entries from another registry to current.\n * \n * @param discordRegistry The discords registry to copy from.\n */\n public void transferVisited(VisitRegistry discordRegistry) {\n for (int v : discordRegistry.getVisited()) {\n this.markVisited(v);\n }\n }\n\n /**\n * Creates the copy of a registry.\n * \n * @return the complete copy.\n * @throws CloneNotSupportedException if error occurs.\n */\n public VisitRegistry clone() throws CloneNotSupportedException {\n VisitRegistry res = (VisitRegistry) super.clone();\n res.unvisitedCount = this.unvisitedCount;\n res.registry = Arrays.copyOfRange(this.registry, 0, this.registry.length);\n return res;\n }\n\n /**\n * The registry size.\n * \n * @return the registry size.\n */\n public int size() {\n return this.registry.length;\n }\n\n /**\n * Check the bounds.\n * \n * @param pos the pos to check.\n * @return true if within the bounds.\n */\n private boolean checkBounds(int pos) {\n if (pos < 0 || pos >= this.registry.length) {\n return false;\n }\n return true;\n }\n\n public int getUnvisitedCount() {\n return this.unvisitedCount;\n }\n\n}" ]
import java.util.Date; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import net.seninp.jmotif.distance.EuclideanDistance; import net.seninp.jmotif.sax.SAXProcessor; import net.seninp.jmotif.sax.TSProcessor; import net.seninp.jmotif.sax.registry.SlidingWindowMarkerAlgorithm; import net.seninp.jmotif.sax.registry.VisitRegistry;
package net.seninp.jmotif.sax.discord; /** * Implements SAX-based discord finder, i.e. HOT-SAX. * * @author psenin */ public class BruteForceDiscordImplementation { // logging stuff // private static final Logger LOGGER; private static final Level LOGGING_LEVEL = Level.INFO; static { LOGGER = (Logger) LoggerFactory.getLogger(BruteForceDiscordImplementation.class); LOGGER.setLevel(LOGGING_LEVEL); }
private static TSProcessor tsProcessor = new TSProcessor();
2
tech-advantage/sonar-gerrit-plugin
src/test/java/fr/techad/sonar/gerrit/network/rest/GerritRestConnectorTest.java
[ "@ScannerSide\n@InstantiationStrategy(InstantiationStrategy.PER_BATCH)\npublic class GerritConfiguration {\n private static final Logger LOG = Loggers.get(GerritConfiguration.class);\n\n private boolean enabled;\n private boolean valid;\n private boolean anonymous;\n private boolean commentNewIssuesOnly;\n private boolean strictHostkey;\n\n private String host;\n\n private String scheme;\n private Integer port;\n private String username;\n private String password;\n private String authScheme;\n private String basePath;\n\n private String sshKeyPath;\n\n private String label;\n private String message;\n private String issueComment;\n private String threshold;\n private int voteNoIssue;\n private int voteBelowThreshold;\n private int voteAboveThreshold;\n\n private String projectName;\n private String branchName;\n private String changeId;\n private String revisionId;\n\n public GerritConfiguration(Settings settings) {\n LOG.debug(\"[GERRIT PLUGIN] Instanciating GerritConfiguration\");\n\n this.enable(settings.getBoolean(PropertyKey.GERRIT_ENABLED));\n this.commentNewIssuesOnly(settings.getBoolean(PropertyKey.GERRIT_COMMENT_NEW_ISSUES_ONLY));\n this.strictlyCheckHostkey(settings.getBoolean(PropertyKey.GERRIT_STRICT_HOSTKEY));\n\n this.setScheme(settings.getString(PropertyKey.GERRIT_SCHEME));\n this.setHost(settings.getString(PropertyKey.GERRIT_HOST));\n this.setPort(settings.getInt(PropertyKey.GERRIT_PORT));\n\n this.setUsername(settings.getString(PropertyKey.GERRIT_USERNAME));\n this.setPassword(settings.getString(PropertyKey.GERRIT_PASSWORD));\n this.setHttpAuthScheme(settings.getString(PropertyKey.GERRIT_HTTP_AUTH_SCHEME));\n this.setBasePath(settings.getString(PropertyKey.GERRIT_BASE_PATH));\n\n this.setSshKeyPath(settings.getString(PropertyKey.GERRIT_SSH_KEY_PATH));\n\n this.setLabel(settings.getString(PropertyKey.GERRIT_LABEL));\n this.setMessage(settings.getString(PropertyKey.GERRIT_MESSAGE));\n this.setIssueComment(settings.getString(PropertyKey.GERRIT_ISSUE_COMMENT));\n this.setThreshold(settings.getString(PropertyKey.GERRIT_THRESHOLD));\n this.setVoteNoIssue(settings.getInt(PropertyKey.GERRIT_VOTE_NO_ISSUE));\n this.setVoteBelowThreshold(settings.getInt(PropertyKey.GERRIT_VOTE_ISSUE_BELOW_THRESHOLD));\n this.setVoteAboveThreshold(settings.getInt(PropertyKey.GERRIT_VOTE_ISSUE_ABOVE_THRESHOLD));\n\n this.setProjectName(settings.getString(PropertyKey.GERRIT_PROJECT));\n this.setBranchName(settings.getString(PropertyKey.GERRIT_BRANCH));\n this.setChangeId(settings.getString(PropertyKey.GERRIT_CHANGE_ID));\n this.setRevisionId(settings.getString(PropertyKey.GERRIT_REVISION_ID));\n\n this.assertGerritConfiguration();\n }\n\n public boolean isValid() {\n assertGerritConfiguration();\n return valid;\n }\n\n public GerritConfiguration enable(boolean serverEnabled) {\n enabled = serverEnabled;\n return this;\n }\n\n public boolean isEnabled() {\n boolean ret = enabled;\n if (StringUtils.isEmpty(changeId) || StringUtils.isEmpty(revisionId)) {\n LOG.info(\n \"[GERRIT PLUGIN] changeId or revisionId is empty. Not called from Gerrit ? Soft-disabling myself.\");\n ret = false;\n }\n return ret;\n }\n\n public boolean isAnonymous() {\n return anonymous;\n }\n\n public GerritConfiguration commentNewIssuesOnly(boolean newIssuesOnly) {\n commentNewIssuesOnly = newIssuesOnly;\n return this;\n }\n\n public boolean shouldCommentNewIssuesOnly() {\n return commentNewIssuesOnly;\n }\n\n public GerritConfiguration strictlyCheckHostkey(boolean strictHostkey) {\n this.strictHostkey = strictHostkey;\n return this;\n }\n\n public boolean shouldStrictlyCheckHostKey() {\n return strictHostkey;\n }\n\n public String getScheme() {\n return scheme;\n }\n\n public GerritConfiguration setScheme(String scheme) {\n this.scheme = scheme;\n return this;\n }\n\n public String getHost() {\n return host;\n }\n\n public GerritConfiguration setHost(String host) {\n this.host = host;\n return this;\n }\n\n public Integer getPort() {\n return port;\n }\n\n public GerritConfiguration setPort(Integer port) {\n this.port = port;\n return this;\n }\n\n public String getUsername() {\n return username;\n }\n\n public GerritConfiguration setUsername(String username) {\n this.username = username;\n if (StringUtils.isBlank(username)) {\n anonymous = true;\n }\n return this;\n }\n\n public String getPassword() {\n return password;\n }\n\n public GerritConfiguration setPassword(String password) {\n this.password = password;\n return this;\n }\n\n public String getHttpAuthScheme() {\n return authScheme;\n }\n\n public GerritConfiguration setHttpAuthScheme(String authScheme) {\n this.authScheme = authScheme;\n return this;\n }\n\n public String getBasePath() {\n return basePath;\n }\n\n public GerritConfiguration setBasePath(String basePath) {\n String newBasePath = basePath;\n\n if (StringUtils.isBlank(newBasePath)) {\n newBasePath = \"/\";\n }\n\n if (newBasePath.charAt(0) != '/') {\n newBasePath = \"/\" + newBasePath;\n }\n\n while (newBasePath.startsWith(\"/\", 1) && !newBasePath.isEmpty()) {\n newBasePath = newBasePath.substring(1, newBasePath.length());\n }\n\n while (newBasePath.endsWith(\"/\") && 1 < newBasePath.length()) {\n newBasePath = newBasePath.substring(0, newBasePath.length() - 1);\n }\n\n this.basePath = newBasePath;\n\n return this;\n }\n\n public String getSshKeyPath() {\n return sshKeyPath;\n }\n\n public GerritConfiguration setSshKeyPath(String sshKey) {\n this.sshKeyPath = sshKey;\n return this;\n }\n\n public String getLabel() {\n return label;\n }\n\n public GerritConfiguration setLabel(String label) {\n this.label = label;\n return this;\n }\n\n public String getMessage() {\n return message;\n }\n\n public GerritConfiguration setMessage(String message) {\n this.message = message;\n return this;\n }\n\n public String getIssueComment() {\n return issueComment;\n }\n\n public void setIssueComment(String issueComment) {\n this.issueComment = issueComment;\n }\n\n public String getThreshold() {\n return threshold;\n }\n\n public GerritConfiguration setThreshold(String threshold) {\n this.threshold = threshold;\n return this;\n }\n\n public int getVoteNoIssue() {\n return voteNoIssue;\n }\n\n public GerritConfiguration setVoteNoIssue(int voteNoIssue) {\n this.voteNoIssue = voteNoIssue;\n return this;\n }\n\n public int getVoteBelowThreshold() {\n return voteBelowThreshold;\n }\n\n public GerritConfiguration setVoteBelowThreshold(int voteBelowThreshold) {\n this.voteBelowThreshold = voteBelowThreshold;\n return this;\n }\n\n public int getVoteAboveThreshold() {\n return voteAboveThreshold;\n }\n\n public GerritConfiguration setVoteAboveThreshold(int voteAboveThreshold) {\n this.voteAboveThreshold = voteAboveThreshold;\n return this;\n }\n\n public String getProjectName() {\n return projectName;\n }\n\n public GerritConfiguration setProjectName(String projectName) {\n this.projectName = projectName;\n return this;\n }\n\n public String getBranchName() {\n return branchName;\n }\n\n public GerritConfiguration setBranchName(String branchName) {\n this.branchName = branchName;\n return this;\n }\n\n public String getChangeId() {\n return changeId;\n }\n\n public GerritConfiguration setChangeId(String changeId) {\n this.changeId = changeId;\n return this;\n }\n\n public String getRevisionId() {\n return revisionId;\n }\n\n public GerritConfiguration setRevisionId(String revisionId) {\n this.revisionId = revisionId;\n return this;\n }\n\n void assertGerritConfiguration() {\n LOG.debug(\"[GERRIT PLUGIN] Verifying configuration settings …\\n{}\", this.toString());\n\n if (StringUtils.isBlank(host) || null == port) {\n valid = false;\n if (isEnabled() || LOG.isDebugEnabled()) {\n LOG.error(\"[GERRIT PLUGIN] ServerConfiguration is not valid : {}\", this.toString());\n }\n } else {\n valid = true;\n }\n\n if (GerritConstants.SCHEME_SSH.equals(scheme) && StringUtils.isBlank(username)) {\n valid = false;\n if (isEnabled() || LOG.isDebugEnabled()) {\n LOG.error(\"[GERRIT PLUGIN] Scheme is ssh but username is blank : {}\", this.toString());\n }\n }\n\n if (GerritConstants.SCHEME_SSH.equals(scheme) && StringUtils.isBlank(sshKeyPath)) {\n valid = false;\n if (isEnabled() || LOG.isDebugEnabled()) {\n LOG.error(\"[GERRIT PLUGIN] Scheme is ssh but keypath is blank : {}\", this.toString());\n }\n }\n\n if (StringUtils.isBlank(label) || StringUtils.isBlank(projectName) || StringUtils.isBlank(branchName)\n || StringUtils.isBlank(changeId) || StringUtils.isBlank(revisionId)) {\n valid = false;\n if (isEnabled() || LOG.isDebugEnabled()) {\n LOG.error(\"[GERRIT PLUGIN] ReviewConfiguration is not valid : {}\", this.toString());\n }\n } else {\n valid &= true;\n }\n }\n\n @Override\n public String toString() {\n return \"GerritConfiguration [valid=\" + valid + \", enabled=\" + enabled + \", scheme=\" + scheme + \", host=\" + host\n + \", port=\" + port + \", anonymous=\" + anonymous + \", username=\" + username + \", password=\"\n + (StringUtils.isBlank(password) ? \"blank\" : \"*obfuscated*\") + \", authScheme=\" + authScheme\n + \", basePath=\" + basePath + \", sshKeyPath=\" + sshKeyPath + \", label=\" + label + \", message=\" + message\n + \", issueComment=\" + issueComment + \", threshold=\" + threshold + \", voteNoIssue=\" + voteNoIssue\n + \",voteBelowThreshold=\" + voteBelowThreshold + \",voteAboveThreshold=\" + voteAboveThreshold\n + \",commentNewIssuesOnly=\" + commentNewIssuesOnly + \", projectName=\" + projectName + \", branchName=\"\n + branchName + \", changeId=\" + changeId + \", revisionId=\" + revisionId + \"]\";\n }\n}", "public final class GerritConstants {\n\n public static final String GERRIT_CATEGORY = \"Gerrit\";\n public static final String GERRIT_SUBCATEGORY_SERVER = \"Server\";\n public static final String GERRIT_SUBCATEGORY_REVIEW = \"Review\";\n public static final String GERRIT_ENABLED_DEFAULT = \"true\";\n public static final String GERRIT_FORCE_BRANCH_DEFAULT = \"false\";\n public static final String SCHEME_HTTP = \"http\";\n public static final String SCHEME_HTTPS = \"https\";\n public static final String SCHEME_SSH = \"ssh\";\n public static final String AUTH_BASIC = \"basic\";\n public static final String AUTH_DIGEST = \"digest\";\n public static final String GERRIT_COMMENT_NEW_ISSUES_ONLY = \"false\";\n public static final String GERRIT_STRICT_HOSTKEY_DEFAULT = \"true\";\n public static final String GERRIT_VOTE_NO_ISSUE_DEFAULT = \"+1\";\n public static final String GERRIT_VOTE_ISSUE_BELOW_THRESHOLD_DEFAULT = \"+1\";\n public static final String GERRIT_VOTE_ISSUE_ABOVE_THRESHOLD_DEFAULT = \"-1\";\n\n private GerritConstants() {\n throw new IllegalAccessError(\"Utility class\");\n }\n\n}", "public class GerritPluginException extends Exception {\n private static final long serialVersionUID = 3158628966283370707L;\n\n public GerritPluginException() {\n super();\n }\n\n public GerritPluginException(String message) {\n super(message);\n }\n\n public GerritPluginException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public final class PropertyKey {\n public static final String GERRIT_ENABLED = \"GERRIT_ENABLED\";\n public static final String GERRIT_SCHEME = \"GERRIT_SCHEME\";\n public static final String GERRIT_HOST = \"GERRIT_HOST\";\n public static final String GERRIT_PORT = \"GERRIT_PORT\";\n public static final String GERRIT_PROJECT = \"GERRIT_PROJECT\";\n public static final String GERRIT_BRANCH = \"GERRIT_BRANCH\";\n public static final String GERRIT_CHANGE_ID = \"GERRIT_CHANGE_ID\";\n public static final String GERRIT_REVISION_ID = \"GERRIT_PATCHSET_REVISION\";\n public static final String GERRIT_USERNAME = \"GERRIT_USERNAME\";\n public static final String GERRIT_PASSWORD = \"GERRIT_PASSWORD\"; // NOSONAR\n public static final String GERRIT_SSH_KEY_PATH = \"GERRIT_SSH_KEY_PATH\";\n public static final String GERRIT_HTTP_AUTH_SCHEME = \"GERRIT_HTTP_AUTH_SCHEME\";\n public static final String GERRIT_LABEL = \"GERRIT_LABEL\";\n public static final String GERRIT_MESSAGE = \"GERRIT_MESSAGE\";\n public static final String GERRIT_BASE_PATH = \"GERRIT_BASE_PATH\";\n public static final String GERRIT_THRESHOLD = \"GERRIT_THRESHOLD\";\n public static final String GERRIT_FORCE_BRANCH = \"GERRIT_FORCE_BRANCH\";\n public static final String GERRIT_COMMENT_NEW_ISSUES_ONLY = \"GERRIT_COMMENT_NEW_ISSUES_ONLY\";\n public static final String GERRIT_VOTE_NO_ISSUE = \"GERRIT_VOTE_NO_ISSUE\";\n public static final String GERRIT_VOTE_ISSUE_BELOW_THRESHOLD = \"GERRIT_VOTE_ISSUE_BELOW_THRESHOLD\";\n public static final String GERRIT_VOTE_ISSUE_ABOVE_THRESHOLD = \"GERRIT_VOTE_ISSUE_ABOVE_THRESHOLD\";\n public static final String GERRIT_ISSUE_COMMENT = \"GERRIT_ISSUE_COMMENT\";\n public static final String GERRIT_STRICT_HOSTKEY = \"GERRIT_STRICT_HOSTKEY\";\n\n private PropertyKey() {\n }\n}", "public interface GerritConnector {\n public String listFiles() throws IOException;\n\n public String setReview(String reviewInputAsJson) throws IOException;\n}", "@ScannerSide\n@InstantiationStrategy(InstantiationStrategy.PER_BATCH)\npublic class GerritConnectorFactory {\n private static final Logger LOG = Loggers.get(GerritConnectorFactory.class);\n\n GerritConfiguration gerritConfiguration;\n GerritConnector gerritConnector;\n\n public GerritConnectorFactory(GerritConfiguration gerritConfiguration) {\n this.gerritConfiguration = gerritConfiguration;\n\n if (gerritConfiguration.getScheme().startsWith(GerritConstants.SCHEME_HTTP)) {\n LOG.debug(\"[GERRIT PLUGIN] Using REST connector.\");\n gerritConnector = new GerritRestConnector(gerritConfiguration);\n } else if (gerritConfiguration.getScheme().equals(GerritConstants.SCHEME_SSH)) {\n LOG.debug(\"[GERRIT PLUGIN] Using SSH connector.\");\n gerritConnector = new GerritSshConnector(gerritConfiguration);\n } else {\n LOG.error(\"[GERRIT PLUGIN] Unknown scheme.\");\n }\n }\n\n public GerritConnector getConnector() {\n return gerritConnector;\n }\n}", "public class MockitoExtension\n implements TestInstancePostProcessor, ParameterResolver {\n\n @Override\n public void postProcessTestInstance(Object testInstance,\n ExtensionContext context) {\n MockitoAnnotations.initMocks(testInstance);\n }\n\n @Override\n public boolean supportsParameter(ParameterContext parameterContext,\n ExtensionContext extensionContext) {\n return\n parameterContext.getParameter().isAnnotationPresent(Mock.class);\n }\n\n @Override\n public Object resolveParameter(ParameterContext parameterContext,\n ExtensionContext extensionContext) {\n return getMock(parameterContext.getParameter(), extensionContext);\n }\n\n private Object getMock(\n Parameter parameter, ExtensionContext extensionContext) {\n\n Class<?> mockType = parameter.getType();\n ExtensionContext.Store mocks = extensionContext.getStore(ExtensionContext.Namespace.create(\n MockitoExtension.class, mockType));\n String mockName = getMockName(parameter);\n\n if (mockName != null) {\n return mocks.getOrComputeIfAbsent(\n mockName, key -> mock(mockType, mockName));\n }\n else {\n return mocks.getOrComputeIfAbsent(\n mockType.getCanonicalName(), key -> mock(mockType));\n }\n }\n\n private String getMockName(Parameter parameter) {\n String explicitMockName = parameter.getAnnotation(Mock.class)\n .name().trim();\n if (!explicitMockName.isEmpty()) {\n return explicitMockName;\n }\n else if (parameter.isNamePresent()) {\n return parameter.getName();\n }\n return null;\n }\n}" ]
import fr.techad.sonar.GerritConfiguration; import fr.techad.sonar.GerritConstants; import fr.techad.sonar.GerritPluginException; import fr.techad.sonar.PropertyKey; import fr.techad.sonar.gerrit.GerritConnector; import fr.techad.sonar.gerrit.factory.GerritConnectorFactory; import fr.techad.sonar.mockito.MockitoExtension; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.mockserver.integration.ClientAndServer; import org.mockserver.model.Header; import org.sonar.api.config.internal.MapSettings; import java.io.IOException; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response;
settings.setProperty(PropertyKey.GERRIT_USERNAME, "").appendProperty(PropertyKey.GERRIT_PASSWORD, "") .setProperty(PropertyKey.GERRIT_BASE_PATH, "") .setProperty(PropertyKey.GERRIT_BRANCH, "branch/subbranch"); // when GerritRestConnector gerritRestConnector = getRestConnector(); // then assertEquals("/changes/project~branch%2Fsubbranch~changeid/revisions/revisionid", gerritRestConnector.rootUriBuilder()); } @Test public void shouldPrependCustomBasePathWhenAnonymous() throws GerritPluginException { // given settings.setProperty(PropertyKey.GERRIT_USERNAME, "").appendProperty(PropertyKey.GERRIT_PASSWORD, "") .setProperty(PropertyKey.GERRIT_BASE_PATH, "/r") .setProperty(PropertyKey.GERRIT_BRANCH, "branch/subbranch"); // when GerritRestConnector gerritRestConnector = getRestConnector(); // then assertEquals("/r/changes/project~branch%2Fsubbranch~changeid/revisions/revisionid", gerritRestConnector.rootUriBuilder()); } @Test public void shouldSetReview() throws IOException { mockServer.when( request() .withPath("/a/changes/project~branch~changeid/revisions/revisionid/review") .withMethod("POST")) .respond( response() .withStatusCode(200) .withHeaders( new Header("Content-Type", "application/json; charset=utf-8"), new Header("Cache-Control", "public, max-age=86400")) .withBody("{ message: 'Review committed' }") .withDelay(TimeUnit.SECONDS, 1) ); settings.setProperty(PropertyKey.GERRIT_USERNAME, "sonar") .setProperty(PropertyKey.GERRIT_PASSWORD, "sonar") .appendProperty(PropertyKey.GERRIT_BASE_PATH, "") .setProperty(PropertyKey.GERRIT_BRANCH, "branch"); String response = getRestConnector().setReview("review"); Assertions.assertEquals("{ message: 'Review committed' }", response); } @Test public void shouldSetReviewWithNullResponseBody() throws IOException { mockServer.when( request() .withPath("/a/changes/project~branch~changeid2/revisions/revisionid/review") .withMethod("POST")) .respond( response() .withStatusCode(200) .withHeaders( new Header("Content-Type", "application/json; charset=utf-8"), new Header("Cache-Control", "public, max-age=86400")) .withDelay(TimeUnit.SECONDS, 1) ); settings.setProperty(PropertyKey.GERRIT_USERNAME, "sonar") .setProperty(PropertyKey.GERRIT_PASSWORD, "sonar") .appendProperty(PropertyKey.GERRIT_BASE_PATH, "") .setProperty(PropertyKey.GERRIT_BRANCH, "branch") .setProperty(PropertyKey.GERRIT_CHANGE_ID, "changeid2") ; String response = getRestConnector().setReview("review"); Assertions.assertEquals(StringUtils.EMPTY, response); } @Test public void shouldSetReviewAsAnonymous() throws IOException { mockServer.when( request() .withPath("/changes/project~branch~changeid/revisions/revisionid/review") .withMethod("POST")) .respond( response() .withStatusCode(200) .withHeaders( new Header("Content-Type", "application/json; charset=utf-8"), new Header("Cache-Control", "public, max-age=86400")) .withBody("{ message: 'Review committed' }") .withDelay(TimeUnit.SECONDS, 1) ); settings.setProperty(PropertyKey.GERRIT_BRANCH, "branch"); String response = getRestConnector().setReview("review"); Assertions.assertEquals("{ message: 'Review committed' }", response); } @Test public void shouldListFiles() throws IOException { mockServer.when( request() .withPath("/a/changes/project~branch~changeid/revisions/revisionid/files/") .withMethod("GET")) .respond( response() .withStatusCode(200) .withHeaders( new Header("Content-Type", "application/json; charset=utf-8"), new Header("Cache-Control", "public, max-age=86400")) .withBody(listFiles) .withDelay(TimeUnit.SECONDS, 1) ); settings.setProperty(PropertyKey.GERRIT_USERNAME, "sonar") .setProperty(PropertyKey.GERRIT_PASSWORD, "sonar") .appendProperty(PropertyKey.GERRIT_BASE_PATH, "") .setProperty(PropertyKey.GERRIT_BRANCH, "branch"); String response = getRestConnector().listFiles(); Assertions.assertEquals(listFiles, response); } private GerritRestConnector getRestConnector() {
GerritConfiguration gerritConfiguration = new GerritConfiguration(settings);
0
fvalente/LogDruid
src/logdruid/ui/table/StatRecordingEditorTable.java
[ "public class Repository {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate ArrayList<Recording> recordings;\n\tprivate ArrayList<Source> sources;\n\tprivate String baseSourcePath;\n\tprivate ArrayList<DateFormat> dates;\n\tprivate boolean recursiveMode;\n\tprivate boolean onlyMatches;\n\tprivate boolean stats; // unused\n\tprivate boolean timings; // unused\n\tprivate HashMap<String, String> preferences;\n\n\tpublic Repository() {\n\t\tpreferences = new HashMap<String, String>();\n\t\tpreferences.put(\"timings\", \"false\");\n\t\tpreferences.put(\"stats\", \"true\");\n\t\tpreferences.put(\"chartSize\", \"350\");\n\t\tpreferences.put(\"ThreadPool_Group\", \"4\");\n\t\tpreferences.put(\"ThreadPool_File\", \"8\");\n\t\tpreferences.put(\"editorCommand\", \"gvim -R +$line $file\");\n\t\tpreferences.put(\"gatherstats\", \"true\");\n\t\tpreferences.put(\"gatherevents\", \"true\");\n\t\tpreferences.put(\"gatherreports\", \"true\");\n\t\trecordings = new ArrayList<Recording>();\n\t\tdates = new ArrayList<DateFormat>();\n\t\tsources = new ArrayList<Source>();\n\t\trecursiveMode = false;\n\t\t// logger.info(\"repository ArrayList initialized\");\n\t}\n\n\tpublic boolean isRecursiveMode() {\n\t\treturn recursiveMode;\n\t}\n\n\tpublic void setPreference(String key, String value) {\n\t\tpreferences.put(key, value);\n\t}\n\n\tpublic String getPreference(String key) {\n\t\treturn getPreferences().get(key);\n\t}\n\n\tpublic void setRecursiveMode(boolean recursiveMode) {\n\t\t// logger.info(\"recursive mode is :\"+recursiveMode);\n\t\tthis.recursiveMode = recursiveMode;\n\t}\n\n\tpublic ArrayList<Source> getSources() {\n\t\treturn sources;\n\t}\n\n\tpublic Source getSource(String name) {\n\t\tIterator sourceIterator = sources.iterator();\n\t\tint cnt = 0;\n\t\twhile (sourceIterator.hasNext()) {\n\t\t\tSource src = (Source) sourceIterator.next();\n\t\t\tif (src.getSourceName() == name) {\n\t\t\t\treturn src;\n\t\t\t}\n\t\t}\n\t\treturn (Source) null;\n\t}\n\n\tpublic void setSources(ArrayList<Source> sources) {\n\t\tthis.sources = sources;\n\t}\n\n\tpublic void addSource(Source s) {\n\t\tif (sources == null) {\n\t\t\tsources = new ArrayList<Source>();\n\t\t}\n\t\tsources.add(s);\n\t}\n\n\tpublic void deleteSource(int id) {\n\t\tsources.remove(id);\n\t}\n\n\tpublic Source getSource(int id) {\n\t\treturn sources.get(id);\n\t}\n\n\tpublic void updateSource(int id, String txtName, String txtRegularExp, Boolean active) {\n\t\tsources.get(id).setSourceName(txtName);\n\t\tsources.get(id).setSourcePattern(txtRegularExp);\n\t\tsources.get(id).setActive(active);\n\t}\n\n\tpublic ArrayList<Recording> getRecordings() {\n\t\t// logger.info(xstream.toXML(recordings));\n\t\treturn recordings;\n\t}\n\n\tpublic ArrayList<Recording> getRecordings(Class _class, boolean onlyActive) {\n\n\t\tArrayList<Recording> statRecordingArrayList = new ArrayList<Recording>();\n\t\tIterator recordingIterator = recordings.iterator();\n\t\tint cnt = 0;\n\t\twhile (recordingIterator.hasNext()) {\n\t\t\tRecording r = (Recording) recordingIterator.next();\n\t\t\tif (r.getClass().equals(_class)) { \n\t\t\t\tif (onlyActive){\n\t\t\t\t\tif (r.getIsActive())\n\t\t\t\t\tstatRecordingArrayList.add(r);\t\n\t\t\t\t} else {\n\t\t\t\tstatRecordingArrayList.add(r);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn (ArrayList<Recording>) statRecordingArrayList;\n\t}\n\n\n\tpublic ArrayList getReportRecordings(MineResultSet mineResultSet1, boolean b) {\n\t\tArrayList<Recording> temp = new ArrayList<Recording>();\n\t\tArrayList<Recording> returned= new ArrayList<Recording>();\t\t\n\t\tIterator<Map<Recording, Map<List<Object>, Long>>> it1 = mineResultSet1.getOccurenceReport().values().iterator();\n\t\twhile (it1.hasNext()){\n\t\t\tIterator test = (Iterator) it1.next().keySet().iterator();\n\t\t\twhile (test.hasNext())\n\t\t\t{\n\t\t\ttemp.add((Recording) test.next());\n\t\t\t}\n\t\t}\n\t\t\n\t\tIterator<Map<Recording, Map<List<Object>, Double>>> it2 =mineResultSet1.getSumReport().values().iterator();\n\t\twhile (it2.hasNext()){\n\t\t\tIterator test = (Iterator) it2.next().keySet().iterator();\n\t\t\twhile (test.hasNext())\n\t\t\t{\n\t\t\ttemp.add((Recording) test.next());\n\t\t\t}\n\t\t}\n\t\t\n\t\tIterator<Map<Recording, SortedMap<Double, List<Object>>>> it3 =mineResultSet1.getTop100Report().values().iterator();\n\t\twhile (it3.hasNext()){\n\t\t\tIterator test = (Iterator) it3.next().keySet().iterator();\n\t\t\twhile (test.hasNext())\n\t\t\t{\n\t\t\ttemp.add((Recording) test.next());\n\t\t\t}\n\t\t}\n\t\t\n\t\tArrayList<Recording> aL = getRecordings(ReportRecording.class, b);\n\t\tIterator ite = aL.iterator();\n\t\twhile (ite.hasNext()){\n\t\t\tRecording rec= (Recording) ite.next();\n\t\t\tif (temp.contains(rec))\t{\n\t\t\treturned.add(rec);\t\n\t\t\t}\n\t\t}\n\t\treturn returned;\n\t}\n\t\n\t\n\tpublic Recording getRecording(Class _class, int id, boolean onlyActive) {\n\t\treturn getRecordings(_class,onlyActive).get(id);\n\t}\n\n\tpublic HashMap<String, String> getPreferences() {\n\t\tif (preferences == null) {\n\t\t\tpreferences = new HashMap<String, String>();\n\t\t\tlogger.info(\"new preferences\");\n\t\t}\n\t\tif (!preferences.containsKey(\"timings\")) {\n\t\t\tpreferences.put(\"timings\", \"false\");\n\t\t}\n\n\t\tif (!preferences.containsKey(\"stats\")) {\n\t\t\tlogger.info(\"stats set to true\");\n\t\t\tpreferences.put(\"stats\", \"true\");\n\t\t}\n\n\t\tif (!preferences.containsKey(\"chartSize\")) {\n\t\t\tpreferences.put(\"chartSize\", \"350\");\n\t\t}\n\n\t\tif (!preferences.containsKey(\"ThreadPool_Group\")) {\n\t\t\tpreferences.put(\"ThreadPool_Group\", \"4\");\n\t\t}\n\t\tif (!preferences.containsKey(\"ThreadPool_File\")) {\n\t\t\tpreferences.put(\"ThreadPool_File\", \"8\");\n\t\t}\n\t\tif (!preferences.containsKey(\"editorCommand\")) {\n\t\t\tpreferences.put(\"editorCommand\", \"gvim -R +$line $file\");\n\t\t}\n\t\t\n\t\treturn preferences;\n\t}\n\n\tpublic void addRecording(Recording r) {\n\t\trecordings.add(r);\n\t\t// logger.info(xstream.toXML(recordings));<\n\t}\n\n\tpublic int getRecordingCount() {\n\t\treturn recordings.size();\n\t}\n\n\tpublic void deleteRecording(int id) {\n\t\trecordings.remove(id);\n\t\tArrayList<Source> sources= this.getSources();\n\t\tIterator<Source> ite=sources.iterator();\n\t\twhile (ite.hasNext()){\n\t\t\tSource src=(Source) ite.next();\n\t\t\tsrc.removeActiveRecording(recordings.get(id));\n\t\t}\n\t}\n\n\tpublic Recording getRecording(int id) {\n\t\treturn recordings.get(id);\n\t}\n\n\tpublic Recording getRecording(String _id) {\n\t\tIterator recordingIterator = recordings.iterator();\n\t\tRecording recReturn = null; \n\t\tint cnt = 0;\n\t\twhile (recordingIterator.hasNext()) {\n\t\t\tRecording r = (Recording) recordingIterator.next();\n\t\t\tif (r.getId() == _id) {\n\t\t\t\trecReturn = r;\n\t\t\t}\n\t\t}\n\t\treturn recReturn;\n\t}\n\n\tpublic void duplicateRecording(int id) {\n\t\tRecording newRecording = recordings.get(id).duplicate();\n\t\tthis.addRecording(newRecording);\n\t\tArrayList<Source> sources= this.getSources();\n\t\tIterator<Source> ite=sources.iterator();\n\t\tif (!MetadataRecording.class.isInstance(recordings.get(id))){\n\t\twhile (ite.hasNext()){\n\t\t\tSource src=(Source) ite.next();\n\t\t\tif (src.isActiveRecordingOnSource(recordings.get(id))){\n\t\t\t\tsrc.toggleActiveRecording(newRecording);\n\t\t\t}\n\t\t}}\n\t}\n\n\tpublic void update(Repository repo) {\n\t\trecordings = repo.getRecordings();\n\t}\n\n\tpublic void save(File file) {\n\n\t\tFileOutputStream fos = null;\n\t\ttry {\n\t\t\tString xml = new XStream(new StaxDriver()).toXML(recordings);\n\t\t\tfos = new FileOutputStream(file);\n\t\t\t// fos.write(\"<?xml version=\\\"1.0\\\"?>\".getBytes(\"UTF-8\"));\n\t\t\tbyte[] bytes = xml.getBytes(\"UTF-8\");\n\t\t\tfos.write(bytes);\n\n\t\t} catch (Exception e) {\n\t\t\tSystem.err.println(\"Error in XML Write: \" + e.getMessage());\n\t\t} finally {\n\t\t\tif (fos != null) {\n\t\t\t\ttry {\n\t\t\t\t\tfos.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void open(File file) {\n\t\t// XStream xstream = new XStream(new StaxDriver());\n\t\tFileOutputStream fos = null;\n\t\ttry {\n\t\t\trecordings = (ArrayList<Recording>) new XStream(new StaxDriver()).fromXML(file);\n\t\t\t/*\n\t\t\t * fos = new FileOutputStream(file);\n\t\t\t * \n\t\t\t * byte[] bytes = xml.getBytes(\"UTF-8\"); fos.write(bytes);\n\t\t\t */\n\t\t\tlogger.info(new XStream(new StaxDriver()).toXML(recordings));\n\t\t} catch (Exception e) {\n\t\t\tSystem.err.println(\"Error in XML Write: \" + e.getMessage());\n\t\t} finally {\n\t\t\tif (fos != null) {\n\t\t\t\ttry {\n\t\t\t\t\tfos.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setRecordings(ArrayList recordings) {\n\t\tthis.recordings = recordings;\n\t}\n\n\tpublic void save() {\n\n\t}\n\n\tpublic String getBaseSourcePath() {\n\t\treturn baseSourcePath;\n\t}\n\n\tpublic void setBaseSourcePath(String baseSourcePath) {\n\t\tthis.baseSourcePath = baseSourcePath;\n\t}\n\n\tpublic ArrayList<DateFormat> getDates() {\n\t\treturn dates;\n\t}\n\n\tpublic void setDates(ArrayList<DateFormat> hm) {\n\t\tdates = hm;\n\t}\n\n\tpublic void addDateFormat(DateFormat df) {\n\t\tif (dates == null) {\n\t\t\tdates = new ArrayList<DateFormat>();\n\t\t}\n\t\tdates.add(df);\n\t\t// logger.info(xstream.toXML(recordings));\n\t}\n\n\tpublic void deleteDateFormat(int id) {\n\t\tdates.remove(id);\n\t}\n\n\tpublic DateFormat getDateFormat(int id) {\n\t\treturn dates.get(id);\n\t}\n\n\tpublic DateFormat getDateFormat(String id) {\n\t\tIterator dateFormatIterator = dates.iterator();\n\t\tint cnt = 0;\n\t\twhile (dateFormatIterator.hasNext()) {\n\t\t\tDateFormat df = (DateFormat) dateFormatIterator.next();\n\t\t\tif (df.getId() == id) {\n\t\t\t\treturn df;\n\t\t\t}\n\t\t}\n\t\treturn (DateFormat) null;\n\t}\n\n\tpublic void setOnlyMatches(boolean selected) {\n\t\tonlyMatches = selected;\n\n\t}\n\n\tpublic boolean isOnlyMatches() {\n\t\treturn onlyMatches;\n\t}\n\n\tpublic boolean isStats() {\n\t\treturn Boolean.parseBoolean(getPreference(\"stats\"));\n\t}\n\n\tpublic void setStats(boolean stats) {\n\t\tsetPreference(\"stats\", Boolean.toString(stats));\n\t}\n\n\tpublic boolean isTimings() {\n\t\treturn Boolean.parseBoolean(getPreference(\"timings\"));\n\t}\n\n\tpublic void setTimings(boolean timings) {\n\t\tsetPreference(\"timings\", Boolean.toString(timings));\n\t}\n\n}", "public class EventRecording extends Recording {\n\tprivate static Logger logger = Logger.getLogger(EventRecording.class.getName());\n\tprivate String dateFormat;\n\n\tpublic EventRecording(String _name, String _regexp, String _exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, boolean _caseSensitive, ArrayList<RecordingItem> _recordingItem) {\n\t\tsetName(_name);\n\t\tsetRegexp(_regexp);\n\t\tsetExampleLine(_exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tsuper.id = generate();\n\t\tlogger.info(\"New EventRecording name: \" + _name + \", regexp: \" + _regexp + \", id: \" + super.id);\n\t\tif (recordingItem != null)\n\t\t\tlogger.info(\"New EventRecording with recordingItem ArrayList: \" + recordingItem.toString());\n\t}\n\n\tpublic String getType() {\n\t\treturn \"Event\";\n\t}\n\n\tpublic String getDateFormat() {\n\t\treturn dateFormat;\n\t}\n\n\tpublic void setDateFormat(String dateFormat) {\n\t\tthis.dateFormat = dateFormat;\n\t}\n\n\tpublic void setRecordingItem(ArrayList<RecordingItem> recordingItem) {\n\t\tthis.recordingItem = recordingItem;\n\t}\n\n\tpublic void update(String txtName, String txtRegularExp, String exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, Boolean _caseSensitive, ArrayList<RecordingItem> _recordingItem) {\n\t\tsetName(txtName);\n\t\tsetRegexp(txtRegularExp);\n\t\tsetExampleLine(exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tlogger.debug(\"RIArrayLit size: \"+ recordingItem.size());\n\t\tif (this.id == null) {\n\t\t\tsuper.id = generate();\n\t\t}\n\t}\n\n\tpublic Recording duplicate() {\n\n\t\tArrayList<RecordingItem> _recordingItem = null;\n\t\t// might need put back .toString() to those?? *** TBR\n\t\tString _name = getName().toString();\n\t\tString _regexp = getRegexp().toString();\n\t\tString _exampleLine = getExampleLine().toString();\n\t\tString _dateFormat = dateFormat.toString();\n\n\t\tBoolean _isActive = getIsActive().booleanValue();\n\t\tBoolean _caseSensitive = isCaseSensitive();\n\t\tBoolean _useSourceDateFormat=getUseSourceDateFormat();\n\t\tif (recordingItem != null) {\n\t\t\t_recordingItem = (ArrayList<RecordingItem>) recordingItem.clone();\n\t\t}\n\t\tEventRecording eR=new EventRecording(_name, _regexp, _exampleLine, _dateFormat, _isActive, _useSourceDateFormat, _caseSensitive, _recordingItem);\n\t\teR.setDateFormatID(this.getDateFormatID());\n\t\treturn eR;\n\t}\n}", "public class MetadataRecording extends Recording {\n\tprivate static Logger logger = Logger.getLogger(MetadataRecording.class.getName());\n\tprivate ArrayList recordingItem;\n\tprivate String dateFormat;\n\n\tpublic String getType() {\n\t\treturn \"File Grouping\";\n\t}\n\n\tpublic MetadataRecording(String _name, String _regexp, String _exampleLine, String _dateFormat, Boolean _isActive, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(_name);\n\t\tsetRegexp(_regexp);\n\t\tsetExampleLine(_exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tsuper.id = generate();\n\t\tlogger.info(\"New MetadataRecording name: \" + _name + \", regexp: \" + _regexp + \", id: \" + super.id);\n\t\tif (recordingItem != null)\n\t\t\tlogger.info(\"New MetadataRecording with recordingItem ArrayList: \" + recordingItem.toString());\n\t}\n\n\tpublic String getDateFormat() {\n\t\treturn dateFormat;\n\t}\n\n\tpublic void setDelimitator(String delimitator) {\n\t//\tthis.dateFormat = dateFormat;\n\t}\n\n\tpublic ArrayList getRecordingItem() {\n\t\t// logger.info(\"***********\"+recordingItem.toString()+recordingItem.size());\n\t\t// Thread.currentThread().dumpStack();\n\t\treturn (ArrayList) recordingItem;\n\t}\n\n\tpublic void setRecordingItem(ArrayList recordingItem) {\n\t\tthis.recordingItem = recordingItem;\n\t}\n\n\tpublic void update(String txtName, String txtRegularExp, String exampleLine, String _dateFormat, Boolean _isActive, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(txtName);\n\t\tsetRegexp(txtRegularExp);\n\t\tsetExampleLine(exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t}\n\n\tpublic Recording duplicate() {\n\n\t\tArrayList _recordingItem = null;\n\t\t// might need put back .toString() to those?? *** TBR\n\t\tString _name = getName().toString();\n\t\tString _regexp = getRegexp().toString();\n\t\tString _exampleLine = getExampleLine().toString();\n\t\tString _dateFormat = getDateFormat().toString();\n\n\t\tBoolean _isActive = getIsActive().booleanValue();\n\t\tBoolean _caseSensitive = isCaseSensitive();\n\t\tif (getRecordingItem() != null) {\n\t\t\t_recordingItem = (ArrayList) getRecordingItem().clone();\n\t\t}\n\t\t\n\t\tMetadataRecording eR=new MetadataRecording(_name, _regexp, _exampleLine, _dateFormat, _isActive, _caseSensitive, _recordingItem);\n\t\teR.setDateFormatID(this.getDateFormatID());\n\t\treturn eR;\n\t\t\n\t}\n\n}", "public abstract class Recording {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate String name;\n\tprivate String regexp;\n\tprotected ArrayList recordingItem;\n\tprivate String FastDateFormat;\n\tprivate String exampleLine;\n\tprivate Boolean isActive;\n\tprotected String id;\n\tprivate Boolean caseSensitive;\n\tprivate Boolean useSourceDateFormat;\n\tprivate String dateFormatID;\n\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String generate() {\n\t\tString generatedUniqueId = UUID.randomUUID().toString();\n\t\tlogger.info(\"unique ID: \" + generatedUniqueId);\n\t\treturn generatedUniqueId;\n\t}\n\n\tpublic ArrayList getRecordingItem() {\n\t\t// logger.info(\"***********\"+recordingItem.toString()+recordingItem.size());\n\t\t// Thread.currentThread().dumpStack();\n\t\treturn recordingItem;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getRegexp() {\n\t\treturn regexp;\n\t}\n\n\tpublic void setRegexp(String regexp) {\n\t\tthis.regexp = regexp;\n\t}\n\n\tpublic String getExampleLine() {\n\t\treturn exampleLine;\n\t}\n\n\tpublic void setExampleLine(String exampleLine) {\n\t\tthis.exampleLine = exampleLine;\n\t}\n\n\tpublic abstract String getType();\n\n\tpublic Boolean getIsActive() {\n\t\treturn isActive;\n\t}\n\n\tpublic boolean isCaseSensitive() {\n\t\tif (caseSensitive!=null){\n\t\t\treturn caseSensitive;\n\t\t}else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic void setCaseSensitive(boolean caseSensitive) {\n\t\tthis.caseSensitive = caseSensitive;\n\t}\n\n\tpublic void setIsActive(Boolean isActive) {\n\t\tthis.isActive = isActive;\n\t}\n\n\tabstract public Recording duplicate();\n\n\tpublic String getDateFormatID() {\n\t\treturn dateFormatID;\n\t}\n\n\tpublic void setDateFormatID(String dateFormatID) {\n\t\tthis.dateFormatID = dateFormatID;\n\t}\n\n\tpublic Boolean getUseSourceDateFormat() {\n\t\tif (useSourceDateFormat==null){\n\t\t\treturn false;\n\t\t} else{\n\t\treturn useSourceDateFormat;}\n\t}\n\n\tpublic void setUseSourceDateFormat(Boolean useSourceDateFormat) {\n\t\tthis.useSourceDateFormat = useSourceDateFormat;\n\t}\n\n}", "public class RecordingItem {\n\tprivate String processingType;\n\tprotected String name;\n\tprotected String before;\n\tprotected String after;\n\tprotected String type;\n\tprotected String inside;\n\tprotected String value;\n\tprotected boolean selected;\n\tprotected boolean show;\n\n\tpublic String getBefore() {\n\t\treturn before;\n\t}\n\n\tpublic void setBefore(String before) {\n\t\tthis.before = before;\n\t}\n\n\tpublic String getAfter() {\n\t\treturn after;\n\t}\n\n\tpublic void setAfter(String after) {\n\t\tthis.after = after;\n\t}\n\n\tpublic String getProcessingType() {\n\t\treturn processingType;\n\t}\n\n\tpublic void setProcessingType(String processingType) {\n\t\tthis.processingType = processingType;\n\t}\n\n\tpublic RecordingItem(String name, String before, String type, String processingType, String insideRegex, String after, Boolean isSelected, Boolean show, String value) {\n\t\tthis.name = name;\n\t\tthis.before = before;\n\t\tthis.after = after;\n\t\tthis.value = value;\n\t\tthis.type = type;\n\t\tthis.selected = isSelected;\n\t\tthis.processingType = processingType;\n\t\tthis.inside=insideRegex;\n\t\tthis.show=show;\n\t\t// super(name, before, type, after, isSelected, value);\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic RecordingItem(String name, String before, String type, String insideRegex, String after, Boolean isSelected, Boolean show, String value) {\n\t\tthis.name = name;\n\t\tthis.before = before;\n\t\tthis.after = after;\n\t\tthis.value = value;\n\t\tthis.type = type;\n\t\tthis.selected = isSelected;\n\t\tthis.inside=insideRegex;\n\t\tthis.show=show;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(String type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\tpublic void setValue(String value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic boolean isSelected() {\n\t\treturn selected;\n\t}\n\n\tpublic void setSelected(boolean selected) {\n\t\tthis.selected = selected;\n\t}\n\n\tpublic boolean isShow() {\n\t\treturn show;\n\t}\n\n\tpublic void setShow(boolean show) {\n\t\tthis.show = show;\n\t}\n\n\tpublic String getInside() {\n\t\treturn inside;\n\t}\n\n\tpublic void setInside(String _inside) {\n\t\tthis.inside = _inside;\n\t}\n\t\n\t\n\n}", "public class StatRecording extends Recording {\n\tprivate static Logger logger = Logger.getLogger(StatRecording.class.getName());\n//\tprivate ArrayList recordingItem;\n\tprivate String dateFormat;\n\n\tpublic String getType() {\n\t\treturn \"Stat\";\n\t}\n\n\tpublic StatRecording(String _name, String _regexp, String _exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(_name);\n\t\tsetRegexp(_regexp);\n\t\tsetExampleLine(_exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tsuper.id = generate();\n\t\t// logger.info(\"New EventRecording name: \"+_name + \", regexp: \"+ _regexp\n\t\t// + \", id: \"+ super.id +recordingItem.toString());\n\t}\n\n\tpublic String getDateFormat() {\n\t\treturn dateFormat;\n\t}\n\n\tpublic void setDelimitator(String delimitator) {\n\t//\tthis.dateFormat = dateFormat;\n\t}\n\n\tpublic ArrayList getRecordingItem() {\n\t\t// logger.info(\"***********\"+recordingItem.toString()+recordingItem.size());\n\t\t// Thread.currentThread().dumpStack();\n\t\treturn recordingItem;\n\t}\n\n\tpublic void setRecordingItem(ArrayList recordingItem) {\n\t\tthis.recordingItem = recordingItem;\n\t}\n\n\tpublic void update(String txtName, String txtRegularExp, String exampleLine, String _dateFormat, Boolean _isActive, Boolean _useSourceDateFormat, Boolean _caseSensitive, ArrayList _recordingItem) {\n\t\tsetName(txtName);\n\t\tsetRegexp(txtRegularExp);\n\t\tsetExampleLine(exampleLine);\n\t\tsetIsActive(_isActive);\n\t\tsetCaseSensitive(_caseSensitive);\n\t\tsetUseSourceDateFormat(_useSourceDateFormat);\n\t\tdateFormat = _dateFormat;\n\t\trecordingItem = _recordingItem;\n\t\tif (this.id == null) {\n\t\t\tsuper.id = generate();\n\t\t}\n\t}\n\n\tpublic Recording duplicate() {\n\n\t\tArrayList _recordingItem = null;\n\t\t// might need put back .toString() to those?? *** TBR\n\t\tString _name = getName().toString();\n\t\tString _regexp = getRegexp().toString();\n\t\tString _exampleLine = getExampleLine().toString();\n\t\tString _dateFormat = dateFormat.toString();\n\n\t\tBoolean _isActive = getIsActive().booleanValue();\n\t\tBoolean _caseSensitive = isCaseSensitive();\n\t\tBoolean _useSourceDateFormat=getUseSourceDateFormat();\n\t\tif (recordingItem != null) {\n\t\t\t_recordingItem = (ArrayList) recordingItem.clone();\n\t\t}\n\t\tStatRecording eR=new StatRecording(_name, _regexp, _exampleLine, _dateFormat, _isActive,_useSourceDateFormat, _caseSensitive, _recordingItem);\n\t\teR.setDateFormatID(this.getDateFormatID());\n\t\treturn eR;\n\t\t\n\t}\n}", "public class NoProcessingRegexTableRenderer extends DefaultTableCellRenderer {\n\tprivate static Logger logger = Logger.getLogger(NoProcessingRegexTableRenderer.class.getName());\n\t @Override\n\t public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n\t Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\t\n\t \n\t //inside type\n\t Object type = table.getValueAt(row, 2);\n\t Object regex = table.getValueAt(row, 3);\n\t \n\t if (column==1 || column==4){\n \t\t Color clr = new Color(233, 255, 229);\n \t\t component.setBackground(clr);\n\t }\n\t \n\t if (type != null && column==3) {\n\t \tif(((String)type).equals(\"manual\")){\n\t \t \t//logger.info(((String)type));\n\t \t\t Color clr = new Color(233, 255, 229);\n\t \t\t component.setBackground(clr);\n\t \t}else {\n\t \t\t Color clr = new Color(255, 229, 229);\n\t\t \t\t component.setBackground(clr);\n\t \t}\n\t }\n\t return component;\n\t }\n}", "public class DataMiner {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tstatic List<File> listOfFiles = null;\n\tprivate static ExecutorService ThreadPool_FileWorkers = null;\n\tprivate static ExecutorService ThreadPool_GroupWorkers = null;\n\tstatic long estimatedTime = 0;\n\tstatic long startTime = 0;\n\tstatic final Map<Source, Map<Recording, Map<List<Object>, Long>>> occurenceReport = new ConcurrentHashMap<Source, Map<Recording, Map<List<Object>, Long>>>();\n\tstatic final Map<Source, Map<Recording, Map<List<Object>, Double>>> sumReport = new ConcurrentHashMap<Source, Map<Recording, Map<List<Object>, Double>>>();\n\tstatic final Map<Source, Map<Recording, SortedMap<Double,List<Object>>>> top100Report = new ConcurrentHashMap<Source, Map<Recording, SortedMap<Double,List<Object>>>>();;\n\t\n\tpublic static MineResultSet gatherMsineResultSet(ChartData cd, final Repository repo, final MainFrame mainFrame) {\n\t\tString test = Preferences.getPreference(\"ThreadPool_Group\");\n\t\tint ini = Integer.parseInt(test);\n\t\tlogger.info(\"gatherMineResultSet parallelism: \" + ini);\n\t\tThreadPool_GroupWorkers = Executors.newFixedThreadPool(ini);\n\t//\tChartData cd = new ChartData();\n\t\tCollection<Callable<MineResult>> tasks = new ArrayList<Callable<MineResult>>();\n\t\tMineResultSet mineResultSet = new MineResultSet();\n\t\toccurenceReport.clear();\n\t\tsumReport.clear();\n\t\ttop100Report.clear();\n\t\t// tOP100Report = new ConcurrentHashMap<Recording,Map<String, Long>>();\n\n\t\tstartTime = System.currentTimeMillis();\n\t/*\ttry {\n\t\t\tcd = gatherSourceData(repo);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}*/\n\t\t\n\t\t// if (logger.isEnabledFor(Level.INFO))\n\t\t// logger.info(\"ArrayList sourceFileGroup\" + sourceFileGroup);\n\t\tIterator<Source> sourceIterator2 = repo.getSources().iterator();\n\t\tint progressCount = 0;\n\t\twhile (sourceIterator2.hasNext()) {\n\t\t\tfinal Source source = sourceIterator2.next();\n\t\t\t// sourceFiles contains all the matched files for a given source\n\t\t\tif (source.getActive() && source.getActiveMetadata()!=null) {\n\t\t\t\tIterator<Entry<String, ArrayList<FileRecord>>> it = cd.getGroupFilesMap(source).entrySet().iterator();\n\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\tfinal Map.Entry<String, ArrayList<FileRecord>> pairs = it.next();\n\t\t\t\t\tprogressCount = progressCount + pairs.getValue().size();\n\t\t\t\t\tlogger.debug(\"Source:\" + source.getSourceName() + \", group: \" + pairs.getKey() + \" = \" + pairs.getValue().toString());\n\t\t\t\t\ttasks.add(new Callable<MineResult>() {\n\t\t\t\t\t\tpublic MineResult call() throws Exception {\n\t\t\t\t\t\t\treturn DataMiner.mine(pairs.getKey(), pairs.getValue(), repo, source, Preferences.isStats(),\n\t\t\t\t\t\t\t\t\tPreferences.isTimings(), Preferences.isMatches(), mainFrame);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t});\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmainFrame.setMaxProgress(progressCount);\n\t\t// logger.info(\"progressCount \"+ progressCount);\n\t\t/*\n\t\t * invokeAll blocks until all service requests complete, or a max of\n\t\t * 1000 seconds.\n\t\t */\n\t\tList<Future<MineResult>> results = null;\n\t\ttry {\n\t\t\tresults = ThreadPool_GroupWorkers.invokeAll(tasks, 100000, TimeUnit.SECONDS);\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tfor (Future<MineResult> f : results) {\n\t\t\tMineResult mineRes = null;\n\t\t\ttry {\n\t\t\t\t// if (mineRes!=null)\n\t\t\t\tmineRes = f.get();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tif (mineRes != null) {\n\t\t\t\tmineResultSet.updateStartDate(mineRes.getStartDate());\n\t\t\t\tmineResultSet.updateEndDate(mineRes.getEndDate());\n\t\t\t\tif (!mineResultSet.mineResults.keySet().contains(mineRes.getSource())) {\n\t\t\t\t\tmineResultSet.mineResults.put(mineRes.getSource(), new HashMap<String, MineResult>());\n\t\t\t\t}\n\t\t\t\tmineResultSet.mineResults.get(mineRes.getSource()).put(mineRes.getSource().getSourceName() + mineRes.getGroup(), mineRes);\n\t\t\t}\n\t\t}\n\t\testimatedTime = System.currentTimeMillis() - startTime;\n\t\tlogger.info(\"gathering time: \" + estimatedTime);\n\t\t/*\n\t\t * Iterator oRIte= occurenceReport.keySet().iterator(); while\n\t\t * (oRIte.hasNext()) { String occString=(String) oRIte.next();\n\t\t * logger.info(\"nb: \"+ occurenceReport.get(occString)+\" string: \"\n\t\t * +occString); }\n\t\t */\n\t\tmineResultSet.setOccurenceReport(occurenceReport);\n\t\tmineResultSet.setTop100Report(top100Report);\n\t\tmineResultSet.setSumReport(sumReport);\t\n\n\t\treturn mineResultSet;\n\n\t}\n\t\n\t// handle gathering for ArrayList of file for one source-group\n\tpublic static MineResult mine(String group, ArrayList<FileRecord> arrayList, final Repository repo, final Source source, final boolean stats, final boolean timings,\n\t\t\tfinal boolean matches, final MainFrame mainFrame) {\n\t\tlogger.debug(\"call to mine for source \" + source.getSourceName() + \" on group \" + group);\n\t\tThreadPool_FileWorkers = Executors.newFixedThreadPool(Integer.parseInt(Preferences.getPreference(\"ThreadPool_File\")));\n\t\tDate startDate = null;\n\t\tDate endDate = null;\n\t\t// Map<String, ExtendedTimeSeries> statMap = HashObjObjMaps<String,\n\t\t// ExtendedTimeSeries>();\n\t\tMap<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, long[]> timingStatsMap = new HashMap<String, long[]>();\n\t\tMap<String, Map<Date, FileLine>> fileLine = new HashMap<String, Map<Date, FileLine>>();\n\t\tCollection<Callable<FileMineResult>> tasks = new ArrayList<Callable<FileMineResult>>();\n\t\t\n\t\tfinal Map<Recording, String> recMatch1 = getAllRegexSingleMap(repo, source); \n\n\t\tArrayList<Object> mapArrayList;\n\t\tmapArrayList = new ArrayList<>();\n\t\tif (logger.isEnabledFor(Level.INFO))\n\t\t\tlogger.info(\"mine called on \" + source.getSourceName());\n\t\tIterator<FileRecord> fileArrayListIterator = arrayList.iterator();\n\t\twhile (fileArrayListIterator.hasNext()) {\n\t\t\tfinal FileRecord fileRec = fileArrayListIterator.next();\n\t\t\ttasks.add(new Callable<FileMineResult>() {\n\t\t\t\tpublic FileMineResult call() throws Exception {\n\t\t\t\t\tlogger.debug(\"file mine on \" + fileRec);\n\t\t\t\t\treturn fileMine(fileRec, recMatch1, repo, source, stats, timings, matches, mainFrame);\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t}\n\t\tList<Future<FileMineResult>> results = null;\n\t\ttry {\n\t\t\tresults = ThreadPool_FileWorkers.invokeAll(tasks, 100000, TimeUnit.SECONDS);\n\t\t} catch (InterruptedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tfor (Future<FileMineResult> f : results) {\n\t\t\tFileMineResult fileMineRes = null;\n\t\t\ttry {\n\t\t\t\tif (f != null) {\n\t\t\t\t\tfileMineRes = f.get();\n\t\t\t\t}\n\t\t\t} catch (InterruptedException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (ExecutionException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (NullPointerException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t// e.printStackTrace();\n\t\t\t}\n\t\t\tif (fileMineRes != null) {\n\t\t\t\tmapArrayList.add(fileMineRes);\n\t\t\t}\n\n\t\t}\n\t\tArrayList<Object[]> fileDates = new ArrayList<Object[]>();\n\t\tIterator<Object> mapArrayListIterator = mapArrayList.iterator();\n\t\twhile (mapArrayListIterator.hasNext()) {\n\t\t\tFileMineResult fMR = (FileMineResult) mapArrayListIterator.next();\n\n\t\t\tif (startDate == null) {\n\t\t\t\tstartDate = fMR.getStartDate();\n\t\t\t}\n\t\t\tif (endDate == null) {\n\t\t\t\tendDate = fMR.getEndDate();\n\t\t\t}\n\t\t\tif (fMR.getEndDate() != null && fMR.getStartDate() != null) {\n\t\t\t\tif (fMR.getEndDate().after(endDate)) {\n\t\t\t\t\tendDate = fMR.getEndDate();\n\t\t\t\t} else if (fMR.getStartDate().before(startDate)) {\n\t\t\t\t\tstartDate = fMR.getStartDate();\n\t\t\t\t}\n\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\tlogger.debug(\"1: \" + fMR.getStartDate() + \"2: \" + fMR.getEndDate() + \"3: \" + fMR.getFile());\n\t\t\t\t}\n\t\t\t\tfileDates.add(new Object[] { fMR.getStartDate(), fMR.getEndDate(), fMR.getFile() });\n\t\t\t}\n\n\t\t\tMap<String, ExtendedTimeSeries> tempStatMap = fMR.statGroupTimeSeries;\n\t\t\ttempStatMap.entrySet();\n\t\t\tIterator it = tempStatMap.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, ExtendedTimeSeries> pairs = (Map.Entry<String, ExtendedTimeSeries>) it.next();\n\t\t\t\tif (!statMap.containsKey(pairs.getKey())) {\n\t\t\t\t\tstatMap.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t} else {\n\t\t\t\t\tExtendedTimeSeries ts = statMap.get(pairs.getKey());\n\t\t\t\t\tif (stats) {\n\t\t\t\t\t\tint[] array = { pairs.getValue().getStat()[0] + ts.getStat()[0], pairs.getValue().getStat()[1] + ts.getStat()[1] };\n\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t}\n\t\t\t\t\tts.getTimeSeries().addAndOrUpdate(pairs.getValue().getTimeSeries());\n\t\t\t\t\tstatMap.put(pairs.getKey(), ts);\n\t\t\t\t\t// logger.info(pairs.getKey());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMap tempEventMap = fMR.eventGroupTimeSeries;\n\t\t\ttempEventMap.entrySet();\n\t\t\tit = tempEventMap.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, ExtendedTimeSeries> pairs = (Map.Entry<String, ExtendedTimeSeries>) it.next();\n\t\t\t\tif (!eventMap.containsKey(pairs.getKey())) {\n\t\t\t\t\teventMap.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t} else {\n\t\t\t\t\tExtendedTimeSeries ts = eventMap.get(pairs.getKey());\n\t\t\t\t\tif (stats) {\n\t\t\t\t\t\tint[] array = { pairs.getValue().getStat()[0] + ts.getStat()[0], pairs.getValue().getStat()[1] + ts.getStat()[1] };\n\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t}\n\t\t\t\t\tts.getTimeSeries().addAndOrUpdate(pairs.getValue().getTimeSeries());\n\t\t\t\t\teventMap.put(pairs.getKey(), ts);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tit = fMR.matchingStats.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, long[]> pairs = (Map.Entry<String, long[]>) it.next();\n\t\t\t\tif (!timingStatsMap.containsKey(pairs.getKey())) {\n\t\t\t\t\ttimingStatsMap.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t} else {\n\t\t\t\t\tlong[] array = timingStatsMap.get(pairs.getKey());\n\t\t\t\t\t// 0-> sum of time for success matching of given\n\t\t\t\t\t// recording ; 1-> sum of time for failed\n\t\t\t\t\t// matching ; 2-> count of match attempts,\n\t\t\t\t\t// 3->count of success attempts\n\t\t\t\t\tlong[] array2 = { pairs.getValue()[0] + array[0], pairs.getValue()[1] + array[1], pairs.getValue()[2] + array[2],\n\t\t\t\t\t\t\tpairs.getValue()[3] + array[3] };\n\t\t\t\t\ttimingStatsMap.put(pairs.getKey(), array2);\n\t\t\t\t}\n\t\t\t}\n\t\t\tit = fMR.fileLineDateMap.entrySet().iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tMap.Entry<String, Map<Date, FileLine>> pairs = (Map.Entry<String, Map<Date, FileLine>>) it.next();\n\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\tlogger.debug(\"Entry<String,Map<Date, FileLine>> : \" + pairs);\n\t\t\t\t}\n\t\t\t\tif (!fileLine.containsKey(pairs.getKey())) {\n\t\t\t\t\tfileLine.put(pairs.getKey(), pairs.getValue());\n\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\tlogger.debug(\"groupFileLineMap.put \" + pairs.getKey() + \" -> \" + pairs.getValue());\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tMap<Date, FileLine> ts = fileLine.get(pairs.getKey());\n\t\t\t\t\tMap<Date, FileLine> newDateFileLineEntries = pairs.getValue();\n\t\t\t\t\tIterator it2 = newDateFileLineEntries.entrySet().iterator();\n\t\t\t\t\twhile (it2.hasNext()) {\n\t\t\t\t\t\tMap.Entry<Date, FileLine> pairs2 = (Map.Entry<Date, FileLine>) it2.next();\n\t\t\t\t\t\tfileLine.get(pairs.getKey()).put(pairs2.getKey(), pairs2.getValue());\n\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\tlogger.debug(\"groupFileLineMap.put \" + pairs2.getKey() + \" -> \" + pairs2.getValue().getFileId() + \":\" + pairs2.getValue().getLineNumber());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// logger.info(\"cont2: \"+groupFileLineMap.get(pairs.getKey()));\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tFileMineResultSet fMRS = new FileMineResultSet(fileDates, statMap, eventMap, timingStatsMap, fileLine, startDate, endDate);\n\t\treturn new MineResult(group, fMRS, arrayList, repo, source);\n\t}\n\n\tpublic static String readFileLine(Source src, FileLine fileLine, ChartData cd) {\n\t\tFileReader flstr = null;\n\t\tString line = \"\";\n\t\tFileRecord fileRecord = cd.sourceFileArrayListMap.get(src).get(fileLine.getFileId());\n\t\ttry {\n\t\t\tflstr = new FileReader(fileRecord.getCompletePath());\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tBufferedReader r = new BufferedReader(flstr);\n\t\tfor (int i = 0; i < fileLine.getLineNumber(); i++) {\n\t\t\ttry {\n\t\t\t\tline = r.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn line;\n\n\t}\n\n\t// handle gathering for a single file\n\tpublic static FileMineResult fileMine(FileRecord fileRecord, Map<Recording, String> recMatch1, Repository repo, Source source, boolean stats, boolean timings, boolean matches,\n\t\t\tfinal MainFrame mainFrame) {\n\t\tExtendedTimeSeries ts = null;\n\t\tPatternCache patternCache = new PatternCache();\n\t\tClassCache classCache = new ClassCache();\n\t\tDate startDate = null;\n\t\tDate endDate = null;\n\t\tDecimalFormat decimalFormat = new DecimalFormat(\"#.#\", new DecimalFormatSymbols(Locale.US));\n\t\tjava.text.DateFormat fastDateFormat = null;\n\t\tFileReader flstr = null;\n\t\tBufferedReader buf1st;\n\t\tMatcher matcher;\n\t\tMatcher matcher2;\n\t\tFixedMillisecond fMS = null;\n\t\tDateFormat df = null;\n\t\tint statHit = 0;\n\t\tint statMatch = 0;\n\t\tint eventHit = 0;\n\t\tint eventMatch = 0;\n\t\tlong[] arrayBefore;\n\t\tlong match0 = 0;\n\t\tlong match1 = 0;\n\t\tlong timing0 = 0;\n\t\tlong timing1 = 0;\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>(recMatch1);\n\t\tMap<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>();\n\t\tMap<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>();\n\t\tMap<String, long[]> matchTimings = new HashMap<String, long[]>();\n\t\tboolean gatherStats = Preferences.getBooleanPreference(\"gatherstats\");\n\t\tboolean gatherReports = Preferences.getBooleanPreference(\"gatherreports\");\n\t\tboolean gatherEvents = Preferences.getBooleanPreference(\"gatherevents\");\n\t\tlong recordingMatchStart = 0;\n\t\tlong recordingMatchEnd = 0;\n\t\ttry {\n\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\tlogger.debug(\"++file: \" + repo.getBaseSourcePath() + \" + \" + (String) fileRecord.getCompletePath().toString());\n\t\t\t}\n\t\t\tflstr = new FileReader(fileRecord.getCompletePath());\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\n\t\tif (!occurenceReport.containsKey(source)) {\n\t\t\toccurenceReport.put(source, new ConcurrentHashMap<Recording, Map<List<Object>, Long>>());\n\t\t}\n\t\tif (!top100Report.containsKey(source)) {\n\t\t\ttop100Report.put(source, new ConcurrentHashMap<Recording, SortedMap<Double,List<Object>>>());\n\t\t}\n\t\t\n\t\tif (!sumReport.containsKey(source)) {\n\t\t\tsumReport.put(source, new ConcurrentHashMap<Recording, Map<List<Object>, Double>>());\n\t\t}\n\t\t\n\t\tbuf1st = new BufferedReader(flstr);\n\t\tString line;\n\t\ttry {\n\t\t\t//recMatch = getRegexp(repo, source);\n\t\t\tint lineCount = 1;\n\t\t\twhile ((line = buf1st.readLine()) != null) {\n\t\t\t\t// check against one Recording pattern at a tim\n\t\t\t\t// if (logger.isDebugEnabled()) {\n\t\t\t\t// logger.debug(\"line \" + line);\n\t\t\t\t// }\n\t\t\t\tIterator<Entry<Recording, String>> recMatchIte = recMatch.entrySet().iterator();\n\t\t\t\twhile (recMatchIte.hasNext()) {\n\t\t\t\t\tif (timings) {\n\t\t\t\t\t\trecordingMatchStart = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t}\n\t\t\t\t\tEntry<Recording, String> me = recMatchIte.next();\n\t\t\t\t\tRecording rec = (Recording) me.getKey();\n\t\t\t\t\tmatcher = patternCache.getMatcher((String) (rec.getRegexp()),rec.isCaseSensitive(),line);\n\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\tBoolean isStatRecording = classCache.getClass(rec).equals(StatRecording.class);\n\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\tif (isStatRecording) {\n\t\t\t\t\t\t\t\tstatMatch++;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\teventMatch++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// logger.info(\"1**** matched: \" + line);\n\t\t\t\t\t\tArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();\n\t\t\t\t\t\tmatcher2 = patternCache.getMatcher((String) me.getValue(),rec.isCaseSensitive(),line);\n\t\t\t\t\t\tif (matcher2.find()) {\n\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\tif (isStatRecording) {\n\t\t\t\t\t\t\t\t\tstatHit++;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\teventHit++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!classCache.getClass(rec).equals(ReportRecording.class)) {\n\t\t\t\t\t\t\t\tint count = 1;\n\t\t\t\t\t\t\t\tDate date1 = null;\n\t\t\t\t\t\t\t\t// handling capture for each recording item\n\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t// logger.info(\"3A**** \" +\n\t\t\t\t\t\t\t\t\t// recItem2.getType());\n\t\t\t\t\t\t\t\t\tif (recItem2.getType().equals(\"date\")) {\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tdf = repo.getDateFormat(rec.getDateFormatID());\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"4**** rec name\" + rec.getName() + \" df: \" + df.getId());\n\t\t\t\t\t\t\t\t\t\t\tfastDateFormat =ThreadLocalDateFormatMap.getInstance().createSimpleDateFormat(df.getDateFormat());\n\t\t\t\t\t\t\t\t\t\t//\tfastDateFormat = FastDateFormat.getInstance(df.getDateFormat());\n\t\t\t\t\t\t\t\t\t\t\tdate1 = fastDateFormat.parse(matcher2.group(count));\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"4b**** \" + df.getDateFormat() + \" date: \" + date1.toString());\n\t\t\t\t\t\t\t\t\t\t\t// logger.info(\"4**** \" +\n\t\t\t\t\t\t\t\t\t\t\t// date1.toString());\n\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t// TODO Auto-generated catch\n\t\t\t\t\t\t\t\t\t\t\t// block\n\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else if (date1 != null) {\n\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"FileRecord: \" + fileRecord.getFile().getName() + \", Source: \" + source.getSourceName() + \", \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ recItem2.getName() + \", \" + fileRecord.getFile().getName() + \", \" + lineCount);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// recording line of match in file\n\t\t\t\t\t\t\t\t\t\t\t// in map RIFileLineDateMap - note\n\t\t\t\t\t\t\t\t\t\t\t// the FileLine object use an int to\n\t\t\t\t\t\t\t\t\t\t\t// identify the files to save memory\n\t\t\t\t\t\t\t\t\t\t\tMap<Date, FileLine> dateFileLineMap = null;\n\t\t\t\t\t\t\t\t\t\t\t//change this to recItem2 to differentiate recording items with same name ?? TBD\n\t\t\t\t\t\t\t\t\t\t\t//if (RIFileLineDateMap.containsKey(recItem2.getName())) {\n\t\t\t\t\t\t\t\t\t\t\t\tdateFileLineMap = RIFileLineDateMap.get(recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\tif (dateFileLineMap==null){\n\t\t\t\t\t\t\t\t\t\t\t\t\tdateFileLineMap = new HashMap<Date, FileLine>();\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tdateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount));\n\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(fileRecord.getFile().getName() + \" dateFileLineMap put: \" + date1 + \"groupFileLineMap: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ new FileLine(fileRecord.getId(), lineCount));\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(fileRecord.getFile().getName() + \" FileRecord: \" + fileRecord.getFile().getName()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \", RIFileLineDateMap.put: \" + recItem2.getName() + \", line: \" + lineCount\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \" RIFileLineDateMap size: \" + RIFileLineDateMap.size() + \" dateFileLineMap size: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ dateFileLineMap.size());\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tRIFileLineDateMap.put(recItem2.getName(), dateFileLineMap);\n\n\t\t\t\t\t\t\t\t\t\t\tif (startDate == null) {\n\t\t\t\t\t\t\t\t\t\t\t\tstartDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (endDate == null) {\n\t\t\t\t\t\t\t\t\t\t\t\tendDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (date1.after(startDate)) {\n\t\t\t\t\t\t\t\t\t\t\t\tendDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t} else if (date1.before(startDate)) {\n\t\t\t\t\t\t\t\t\t\t\t\tstartDate = date1;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tif (isStatRecording && (gatherStats)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts = statMap.get(recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\t if (ts==null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts = new ExtendedTimeSeries(recItem2, FixedMillisecond.class);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"5**** Adding record to Map: \" + recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tfMS = new FixedMillisecond(date1);\n\t\t\t\t\t\t\t\t\t\t\t\tif (matcher2.group(count) == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(\"null in match on \" + recItem2.getName() + \" at \" + fileRecord.getFile().getName()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ \" line cnt:\" + lineCount);\n\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(\"line : \" + line);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getType().equals(\"long\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS, Long.valueOf((String) matcher2.group(count)))));\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.parse((String) matcher2.group(count).replace(',', '.')))))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tint[] array = ts.getStat();\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[1] = array[1] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[0] = array[0] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"stats \" + array[0] + \" \" + array[1]);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tstatMap.put(recItem2.getName(), ts);\n\t\t\t\t\t\t\t\t\t\t\t\t// performance: add the\n\t\t\t\t\t\t\t\t\t\t\t\t// TmeSeriesDataItem to the\n\t\t\t\t\t\t\t\t\t\t\t\t// TimeSeries instead of\n\t\t\t\t\t\t\t\t\t\t\t\t// updating\n\t\t\t\t\t\t\t\t\t\t\t\t// the TimeSeries in the Map\n\n\t\t\t\t\t\t\t\t\t\t\t} else if (classCache.getClass(rec).equals(EventRecording.class) && (gatherEvents )) {\n\t\t\t\t\t\t\t\t\t\t\t\tts = eventMap.get(recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\tif (ts==null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tts = new ExtendedTimeSeries(recItem2, FixedMillisecond.class);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"5**** Adding record to Map: \" + recItem2.getName());\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t//\t\tSimpleTimePeriod stp = new SimpleTimePeriod(date1,DateUtils.addMilliseconds(date1,1));\n\t\t\t\t\t\t\t\t\t\t\t\tfMS = new FixedMillisecond(date1);\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (((RecordingItem) recItem2).getProcessingType().equals(\"occurrences\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tTimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (t != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS, (double)t.getValue()+1))); // +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// (double)t.getValue()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// need some way to show\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// several occurrences\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 1)));\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t} else if (((RecordingItem) recItem2).getProcessingType().equals(\"duration\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat.parse(matcher2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.group(count)))))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Auto-generated\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// catch block\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t// ts.addOrUpdate((new\n\t\t\t\t\t\t\t\t\t\t\t\t// TimeSeriesDataItem(fMS,\n\t\t\t\t\t\t\t\t\t\t\t\t// 100)));\n\t\t\t\t\t\t\t\t\t\t\t} else if (((RecordingItem) recItem2).getProcessingType().equals(\"sum\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tTimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (t != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!recItem2.getType().equals(\"date\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().addOrUpdate(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDouble.parseDouble(String.valueOf(decimalFormat.parse(matcher2.group(count)))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ ts.getTimeSeries().getDataItem(fMS).getValue()))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(ts.getTimeSeries().getDataItem(fMS).getValue());\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Auto-generated\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// catch block\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// to improve - should use the right type here\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tts.getTimeSeries().add(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat.parse(matcher2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.group(count)))))));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t} catch (ParseException e) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Auto-generated\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// catch block\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t} else if (((RecordingItem) recItem2).getProcessingType().equals(\"capture\")) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t\t\t\t\t// logger.debug(recItem2.getName()\n\t\t\t\t\t\t\t\t\t\t\t\t// +\n\t\t\t\t\t\t\t\t\t\t\t\t// \" \" +\n\t\t\t\t\t\t\t\t\t\t\t\t// Double.parseDouble((matcher2.group(count))));\n\t\t\t\t\t\t\t\t\t\t\t\tif (stats) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tint[] array = ts.getStat();\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[1] = array[1] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tarray[0] = array[0] + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\tts.setStat(array);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (logger.isDebugEnabled())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.debug(\"stats \" + array[0] + \" \" + array[1]);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\teventMap.put(recItem2.getName(), ts);\n\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} // rec.getClass().equals(ReportRecording.class)\n\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t// logger.info(\"event statistics: \"+eventMatch\n\t\t\t\t\t\t\t\t\t// +\n\t\t\t\t\t\t\t\t\t// \" and \" +eventHit +\n\t\t\t\t\t\t\t\t\t// \" ; stat statistics: \"+statMatch +\n\t\t\t\t\t\t\t\t\t// \" and \"\n\t\t\t\t\t\t\t\t\t// +statHit);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else { if (gatherReports){\n\t\t\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\t\t\tif (((ReportRecording) rec).getSubType().equals(\"histogram\") && rec.getIsActive()) {\n\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tMap<List<Object>,Long> occMap = occurenceReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\tif (occMap==null) {\n\t\t\t\t\t\t\t\t\t\toccurenceReport.get(source).put(rec, new ConcurrentHashMap<List<Object>, Long>());\n\t\t\t\t\t\t\t\t\t\toccMap = occurenceReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsynchronized (occMap) {\n\t\t\t\t\t\t\t\t\tObject occ = occMap.get(temp);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif (occ==null) {\n\t\t\t\t\t\t\t\t\t\toccMap.put(temp, (long) 1);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toccMap.put(temp, (long) occ + 1);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (((ReportRecording) rec).getSubType().equals(\"top100\") && rec.getIsActive()) {\n\t\t\t\t\t\t\t\t\tdouble itemIndex = 0;\n\n\t\t\t\t\t\t\t\t\tSortedMap<Double,List<Object>> t100 = top100Report.get(source).get(rec);\n\t\t\t\t\t\t\t\t\tif (t100==null) {\n\t\t\t\t\t\t\t\t\t\ttop100Report.get(source).put(rec, Collections.synchronizedSortedMap(new TreeMap<Double,List<Object>>()));\n\t\t\t\t\t\t\t\t\t\tt100 = top100Report.get(source).get(rec);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\titemIndex = (double)Double.valueOf(matcher2.group(((ReportRecording) rec).getTop100RecordID()+1));\n\t\t\t\t\t\t\t\t\t} catch (NullPointerException npe){\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t//nothing\n\t\t\t\t\t\t\t\t\t}\t\t\n\t\t\t\t\t\t\t\t\tcatch (NumberFormatException nfe){\n\t\t\t\t\t\t\t\t\t\t//nothing\n\t\t\t\t\t\t\t\t\t\tlogger.info(matcher2.group(0));\n\t\t\t\t\t\t\t\t\t\tlogger.info(matcher2.group(((ReportRecording) rec).getTop100RecordID()+1));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsynchronized (t100) {\n\t\t\t\t\t\t\t\t\tif (t100.size()<100){\t\t\t\n\t\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getProcessingType().equals(\"top100\")){\n\t\t\t\t\t\t\t\t\t\t\t\titemIndex=(double)Double.valueOf(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\t\tt100.put(itemIndex, temp);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if (t100.size()==100){\n\t\t\t\t\t\t\t\t\t\t\tif (itemIndex>t100.firstKey()){\n\t\t\t\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getProcessingType().equals(\"top100\")){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\titemIndex=(double)Double.valueOf(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tt100.remove(t100.firstKey());\n\t\t\t\t\t\t\t\t\t\t\t\tt100.put(itemIndex, temp);\t\n\t\t\t\t\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t} \n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\telse if (((ReportRecording) rec).getSubType().equals(\"sum\") && rec.getIsActive()) {\n\t\t\t\t\t\t\t\t\tdouble itemIndex = 0;\n\t\t\t\t\t\t\t\t\tList<Object> temp = new ArrayList<Object>();\n\t\t\t\t\t\t\t\t\tIterator<RecordingItem> recItemIte2 = recordingItem.iterator();\n\t\t\t\t\t\t\t\t\twhile (recItemIte2.hasNext()) {\n\t\t\t\t\t\t\t\t\t\tRecordingItem recItem2 = recItemIte2.next();\n\t\t\t\t\t\t\t\t\t\tif (recItem2.isSelected()) {\n\t\t\t\t\t\t\t\t\t\t\tif (recItem2.getProcessingType().equals(\"sum\")){\n\t\t\t\t\t\t\t\t\t\t\titemIndex=(double)Double.valueOf(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\ttemp.add(matcher2.group(count + 1));\n\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tMap<List<Object>,Double> sumMap = sumReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\tif (sumMap==null) {\n\t\t\t\t\t\t\t\t\t\tsumReport.get(source).put(rec, new ConcurrentHashMap<List<Object>, Double>());\n\t\t\t\t\t\t\t\t\t\tsumMap = sumReport.get(source).get(rec);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tsynchronized (sumMap) {\n\t\t\t\t\t\t\t\t\tObject sum = sumMap.get(temp);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif (sum==null) {\n\t\t\t\t\t\t\t\t\t\tsumMap.put(temp, (double)itemIndex);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tsumMap.put(temp, (double) sum + itemIndex);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\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\tif (timings || matches) {\n\t\t\t\t\t\t\t\tarrayBefore = matchTimings.get(rec.getName());\n\t\t\t\t\t\t\t\tif (arrayBefore!=null) {\n\t\t\t\t\t\t\t\t// logger.info(file.getName() + \" contains \" +\n\t\t\t\t\t\t\t\t// arrayBefore);\n\t\t\t\t\t\t\t\t// 0-> sum of time for success matching of given\n\t\t\t\t\t\t\t\t// recording ; 1-> sum of time for failed\n\t\t\t\t\t\t\t\t// matching ; 2-> count of match attempts,\n\t\t\t\t\t\t\t\t// 3->count of success attempts\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\ttiming0 = arrayBefore[0] + recordingMatchEnd - recordingMatchStart;\n\t\t\t\t\t\t\t\t\ttiming1 = arrayBefore[1];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (matches) {\n\t\t\t\t\t\t\t\t\tmatch0 = arrayBefore[2] + 1;\n\t\t\t\t\t\t\t\t\tmatch1 = arrayBefore[3] + 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlong[] array = { timing0, timing1, match0, match1 };\n\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\tlong[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\t\t\tlong[] array = { 0, 0, 1, 1 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\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} else {\n\t\t\t\t\t\tif (timings || matches) {\n\t\t\t\t\t\t\t\tarrayBefore = matchTimings.get(rec.getName());\n\t\t\t\t\t\t\t\tif (arrayBefore!=null) {\n\t\t\t\t\t\t\t\t// logger.info(file.getName() + \" contains \" +\n\t\t\t\t\t\t\t\t// arrayBefore);\n\t\t\t\t\t\t\t\t// 0-> sum of time for success matching of given\n\t\t\t\t\t\t\t\t// recording ; 1-> sum of time for failed\n\t\t\t\t\t\t\t\t// matching ; 2-> count of match attempts,\n\t\t\t\t\t\t\t\t// 3->count of success attempts\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\ttiming0 = arrayBefore[0];\n\t\t\t\t\t\t\t\t\ttiming1 = arrayBefore[1] + recordingMatchEnd - recordingMatchStart;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (matches) {\n\t\t\t\t\t\t\t\t\tmatch0 = arrayBefore[2] + 1;\n\t\t\t\t\t\t\t\t\tmatch1 = arrayBefore[3];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlong[] array = { timing0, timing1, match0, match1 };\n\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (timings) {\n\t\t\t\t\t\t\t\t\trecordingMatchEnd = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();\n\t\t\t\t\t\t\t\t\tlong[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\n\t\t\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\t\t\tlong[] array = { 0, 0, 1, 0 };\n\t\t\t\t\t\t\t\t\tmatchTimings.put(rec.getName(), array);\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\t\t\t\t}\n\t\t\t\tlineCount++;\n\n\t\t\t\t// timing\n\t\t\t}\n\t\t} catch (NumberFormatException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tbuf1st.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\tmainFrame.progress();\n\t\treturn new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate, endDate);\n\t}\n\n\t/*\n\t * public Map<String,ArrayList> getSourceFileGroup(ArrayList<String>\n\t * sourceFiles,Source src) { String patternString = \"\";\n\t * Map<String,ArrayList> Map=new\n\t * Map<String,ArrayList>(); while (it.hasNext()){ it.next(); }}\n\t * \n\t * returns Map with group id in key and a ArrayList of matching files in\n\t * value.\n\t * \n\t * @param repo\n\t */\n\tpublic static Map<String, ArrayList<FileRecord>> getSourceFileGroup(Map<Integer, FileRecord> sourceFiles, Source src, Repository repo, boolean order) {\n\t\tPatternCache patternCache = new PatternCache();\n\t\tString patternString = \"\";\n\t\tMap<String, ArrayList<FileRecord>> sourceFileGroup = new HashMap<String, ArrayList<FileRecord>>();\n\t\tArrayList<FileRecord> groupedFiles = new ArrayList<FileRecord>();\n\t\tMatcher matcher = null;\n\t\tRecording rec = src.getActiveMetadata();\n\t\tif (src!=null && rec!=null){\n\t\t\t\t\tArrayList<RecordingItem> rIV = ((MetadataRecording) rec).getRecordingItem();\n\t\t\t\t\tIterator<RecordingItem> itV = rIV.iterator();\n\t\t\t\t\tint nbRec = 0;\n\t\t\t\t\twhile (itV.hasNext()) {\n\t\t\t\t\t\tRecordingItem rI = itV.next();\n\t\t\t\t\t\tString type = rI.getType();\n\t\t\t\t\t\tif (type == \"date\") {\n\t\t\t\t\t\t\tpatternString += rI.getBefore() + \"(\" + repo.getDateFormat(rec.getDateFormatID()) + \")\" + rI.getAfter();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpatternString += rI.getBefore() + \"(\" + DataMiner.getTypeString(type) + \")\" + rI.getAfter();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// logger.info(\"patternString: \" + patternString\n\t\t\t\t\t\t// + \" getType: \" +\n\t\t\t\t\t\t// DataMiner.getTypeString(rI.getType()));\n\t\t\t\t\t\tnbRec++;\n\t\t\t\t\t}\n\t\t\t\t\tIterator<FileRecord> sourceFileIterator = sourceFiles.values().iterator();\n\t\t\t\t\tString key = \"\";\n\t\t\t\t\t// tempV = new ArrayList<String>();\n\t\t\t\t\twhile (sourceFileIterator.hasNext()) {\n\t\t\t\t\t\tgroupedFiles.clear();\n\t\t\t\t\t\tFileRecord fileName = sourceFileIterator.next();\n\t\t\t\t\t\t// logger.info(\"file: \"+fileName);\n\t\t\t\t\t\ttry {\n\n\t\t\t\t\t\t\tif (logger.isTraceEnabled()){\n\t\t\t\t\t\t\t\tlogger.trace(\"patternString: \" + patternString);\n\t\t\t\t\t\t\t\tlogger.trace(\"filename: \" + fileName);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmatcher = patternCache.getMatcher(patternString + \".*\",rec.isCaseSensitive(),\n\t\t\t\t\t\t\t\t\tnew File(repo.getBaseSourcePath()).toURI().relativize(new File(fileName.getFile().getCanonicalPath()).toURI()).getPath());\n\t\t\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\tlogger.trace(\"found filename \" + fileName + \" with group\");\n\n\t\t\t\t\t\t\t\tkey = \"\";\n\t\t\t\t\t\t\t\tint i = 0;\n\t\t\t\t\t\t\t\tfor (i = 0; i < matcher.groupCount(); i++) {\n\t\t\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\t\t\tlogger.trace(\"group matched : \" + matcher.group(i));\n\t\t\t\t\t\t\t\t\t\tkey += matcher.group(i + 1) + \" \";\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\tlogger.trace(\"i : \" + i + \" nbRec: \" + nbRec);\n\t\t\t\t\t\t\t\tif (i == nbRec) {\n\t\t\t\t\t\t\t\t\tif (!sourceFileGroup.containsKey(key)) {\n\t\t\t\t\t\t\t\t\t\tArrayList<FileRecord> v = new ArrayList<FileRecord>();\n\t\t\t\t\t\t\t\t\t\tv.add(fileName);\n\t\t\t\t\t\t\t\t\t\tsourceFileGroup.put(key, v);\n\t\t\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\t\t\tlogger.trace(\" to key: \" + key + \" added : \" + fileName);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tsourceFileGroup.get(key).add(fileName);\n\t\t\t\t\t\t\t\t\t\tif (logger.isTraceEnabled())\n\t\t\t\t\t\t\t\t\t\t\tlogger.trace(\" to key: \" + key + \" added : \" + fileName);\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t * if (tempV != null) { sourceFileGroup.put(key,\n\t\t\t\t\t\t\t\t * tempV); logger.info(\"Added file \" + fileName\n\t\t\t\t\t\t\t\t * + \" to group \" + key.toString());\n\t\t\t\t\t\t\t\t * logger.info(\"files \" + tempV);\n\t\t\t\t\t\t\t\t * \n\t\t\t\t\t\t\t\t * }\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} catch (Exception e1) {\n\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t// System.exit(1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// logger.info(\"found group \" + key + \"with \" +\n\t\t\t\t\t\t// groupedFiles.size() + \" files in source \" +\n\t\t\t\t\t\t// src.getSourceName());\n\t\t\t\t\t\t\n\t\t\t\t\t\t//option for ordering files by date of lines - useless at this point\n\t\t\t\t\t\tif (order)\n\t\t\t\t\t\t\t{sourceFileGroup.put(key,Tools.orderFiles(sourceFileGroup.get(key),src));\n\t\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\t\tsourceFileGroup.put(key,sourceFileGroup.get(key));\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\treturn sourceFileGroup;\n\t\t}\nelse {return null;}\n\t}\n\t\n\tprivate static Map<Class,Map<Recording, String>> getAllRegexp(Repository repo, Source source) {\n\t\tMap<Class,Map<Recording, String>> recMatch = new HashMap<Class,Map<Recording, String>>();\n\t\trecMatch.put(StatRecording.class,getRegexp(repo,source,StatRecording.class));\n\t\trecMatch.put(EventRecording.class,getRegexp(repo,source,StatRecording.class));\n\t\trecMatch.put(ReportRecording.class,getRegexp(repo,source,StatRecording.class));\n\t\treturn recMatch;\n\t}\n\n\tpublic static Map<Recording, String> getAllRegexSingleMap(Repository repo, Source source) {\n\t\tlong startTime = System.currentTimeMillis();\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>();\n\t\tif (Preferences.getBooleanPreference(\"gatherstats\")){\n\t\t\tMap<Recording, String> g1= getRegexp(repo,source,StatRecording.class);\n\t\t\tif (g1!=null){\n\t\t\trecMatch.putAll(g1);\n\t\t\t}\n\t\t}\n\t\tif (Preferences.getBooleanPreference(\"gatherevents\")){\n\t\t\tMap<Recording, String> g2= getRegexp(repo,source,EventRecording.class);\n\t\t\tif (g2!=null){\n\t\t\t\trecMatch.putAll(g2);\t\n\t\t\t}\n\t\t}\n\t\tif (Preferences.getBooleanPreference(\"gatherreports\")){\n\t\t\tMap<Recording, String> g3= getRegexp(repo,source,ReportRecording.class);\n\t\t\tif (g3!=null){\n\t\t\trecMatch.putAll(g3);\n\t\t\t}\n\t\t}\n\t\testimatedTime = System.currentTimeMillis() - startTime;\n\t\tlogger.debug(\"getAllRegexSingleMap time: \" + estimatedTime);\n\t\treturn recMatch;\n\t}\n\t\n\t\n\tprivate static Map<Recording, String> getRegexp(Repository repo, Source source, Class recordingClass) {\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>();\n\t\tMap<Recording, Boolean> activeRecordingOnSourceCache = new HashMap<Recording, Boolean>();\n\t\tArrayList<Recording> recordings;\n\t\tStringBuffer sb = new StringBuffer(200);\n\t\trecordings = repo.getRecordings(recordingClass,true);\n\t\tIterator<Recording> recordingIterator = recordings.iterator();\n\t\tboolean forceSourceDateFormat = Preferences.getBooleanPreference(\"ForceSourceDateFormat\");\n\t\t\n\t\twhile (recordingIterator.hasNext()) {\n\t\t\tRecording rec = recordingIterator.next();\n\t\t\tif (!activeRecordingOnSourceCache.containsKey(rec)) {\n\t\t\t\tactiveRecordingOnSourceCache.put(rec, source.isActiveRecordingOnSource(rec));\n\t\t\t}\n\t\t\tif (activeRecordingOnSourceCache.get(rec)) {\n\t\t\t\tif (rec.getIsActive() == true) {\n\t\t\t\t\tArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();\n\t\t\t\t\tIterator<RecordingItem> recItemIte = recordingItem.iterator();\n\t\t\t\t\tif (logger.isTraceEnabled()) {\n\t\t\t\t\t\tlogger.trace(\"Record: \" + rec.getName());\n\t\t\t\t\t}\n\t\t\t\t\tsb.setLength(0);\n\t\t\t\t\t// processing each line of the table\n\t\t\t\t\twhile (recItemIte.hasNext()) {\n\t\t\t\t\t\tRecordingItem recItem = recItemIte.next();\n\t\t\t\t\t\tString stBefore = (String) recItem.getBefore();\n\t\t\t\t\t\tString stType = (String) recItem.getType();\n\t\t\t\t\t\tString stAfter = (String) recItem.getAfter();\n\t\t\t\t\t\tString stInside = recItem.getInside();\n\t\t\t\t\t\tsb.append(stBefore);\n\t\t\t\t\t\tsb.append(\"(\");\n\t\t\t\t\t\tif (forceSourceDateFormat){\n\t\t\t\t\t\t\tsb.append(getMainRegex(stType,stInside,source.getDateFormat()));\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tsb.append(getMainRegex(stType,stInside,repo.getDateFormat(rec.getDateFormatID())));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsb.append(\")\");\n\t\t\t\t\t\tsb.append(stAfter);\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\trecMatch.put(rec, sb.toString());\n\t\t\t\t\tif (logger.isTraceEnabled()) {\n\t\t\t\t\t\tlogger.trace(\"regexp: \" +rec.getRegexp());\n\t\t\t\t\t\tlogger.trace(\"Pattern: \" + sb.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn recMatch;\n\t}\n\n\tpublic static String getMainRegex(String stType, String stInside, DateFormat dateFormat) {\n\t\tif (stType.equals(\"date\")) {\n\t\treturn dateFormat.getPattern();\n\t\t} else{\n\t\t\tif (!stType.equals(\"manual\")){\n\t\t\t\treturn (getTypeString(stType));\n\t\t\t} else {\n\t\t\t\treturn (stInside);\n\t\t\t}}\n\t}\n\n\t// public static get\n\tpublic static String getTypeString(String type) {\n\t\tString typeString = \"\";\n\t\tswitch (type) {\n\t\tcase \"integer\":\n\t\t\ttypeString = \"\\\\d+\";\n\t\t\tbreak;\n\t\tcase \"percent\":\n\t\t\ttypeString = \"\\\\d+\";\n\t\t\tbreak;\n\t\tcase \"word\":\n\t\t\ttypeString = \"\\\\w+\";\n\t\t\tbreak;\n\t\tcase \"stringminimum\":\n\t\t\ttypeString = \".*?\";\n\t\t\tbreak;\n\t\tcase \"string\":\n\t\t\ttypeString = \".*\";\n\t\t\tbreak;\n\t\tcase \"double\":\n\t\t\ttypeString = \"[-+]?[0-9]*.?[0-9]+(?:[eE][-+]?[0-9]+)?\";\n\t\t\tbreak;\n\t\tcase \"long\": // keeping for compatibility with older templates\n\t\t\ttypeString = \"\\\\d+\";\n\t\t\tbreak;\n\t\t/*\n\t\t * case \"date\": typeString = repo.getDateFormat(rec.getDateFormatID());\n\t\t * break;\n\t\t */\n\t\tdefault:\n\t\t\ttypeString = \".*\";\n\t\t\tbreak;\n\t\t}\n\t\treturn typeString;\n\t}\n\t\n\tpublic static ChartData gatherSourceData(final Repository repo, boolean order) {\n\n\t\tPatternCache patternCache = new PatternCache();\n\t\tChartData cd = new ChartData();\n\t\tList<File> listOfFiles = null;\n\t\tlogger.debug(\"Base file path: \" + repo.getBaseSourcePath());\n\t\tif (repo.getBaseSourcePath() == null)\n\t\t\treturn null;\n\t\tFile folder = new File(repo.getBaseSourcePath());\n\t\ttry {\n\t\t\tif (repo.isRecursiveMode()) {\n\t\t\t\tlistOfFiles = FileListing.getFileListing(folder);\n\t\t\t} else {\n\t\t\t\tlistOfFiles = Arrays.asList(folder.listFiles());\n\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tif (listOfFiles != null)\n\t\t\tlogger.debug(\"number of files: \" + listOfFiles.size());\n\t\tcd.sourceArrayList = repo.getSources();\n\t\tIterator<Source> sourceIterator = cd.sourceArrayList.iterator();\n\n\t\twhile (sourceIterator.hasNext()) {\n\t\t\tfinal Source source = sourceIterator.next();\n\t\t\tcd.selectedSourceFiles = new HashMap<Integer, FileRecord>();\n\t\t\t// sourceFiles contains all the matched files for a given source\n\t\t\tif (source.getActive()) {\n\t\t\t\tfor (int i = 0; i < listOfFiles.size(); i++) {\n\t\t\t\t\tif (listOfFiles.get(i).isFile()) {\n\t\t\t\t\t\tString s1 = source.getSourcePattern();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tMatcher matcher = patternCache.getMatcher(s1,true,\n\t\t\t\t\t\t\t\t\tnew File(repo.getBaseSourcePath()).toURI().relativize(new File(listOfFiles.get(i).getCanonicalPath()).toURI()).getPath());\n\n\t\t\t\t\t\t\tif (logger.isTraceEnabled()) {\n\t\t\t\t\t\t\t\tlogger.trace(i\n\t\t\t\t\t\t\t\t\t\t+ \" matching file: \"\n\t\t\t\t\t\t\t\t\t\t+ new File(repo.getBaseSourcePath()).toURI().relativize(new File(listOfFiles.get(i).getCanonicalPath()).toURI())\n\t\t\t\t\t\t\t\t\t\t\t\t.getPath() + \" with pattern: \" + s1);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (matcher.find()) {\n\n\t\t\t\t\t\t\t\tFileRecord tempFileRecord = new FileRecord(i, new File(listOfFiles.get(i).getCanonicalPath()));\n\t\t\t\t\t\t\t\tcd.selectedSourceFiles.put(i, tempFileRecord);\n\t\t\t\t\t\t\t\tif (logger.isTraceEnabled()) {\n\n\t\t\t\t\t\t\t\t\tlogger.trace(\"Source: \" + source.getSourceName() + \" file: \" + listOfFiles.get(i).getCanonicalPath());\n\t\t\t\t\t\t\t\t\tlogger.trace(\" Graphpanel file: \"\n\t\t\t\t\t\t\t\t\t\t\t+ new File(repo.getBaseSourcePath()).toURI().relativize(new File(listOfFiles.get(i).getCanonicalPath()).toURI())\n\t\t\t\t\t\t\t\t\t\t\t\t\t.getPath());\n\t\t\t\t\t\t\t\t\tlogger.trace(tempFileRecord.getCompletePath());\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (logger.isEnabledFor(Level.DEBUG))\n\t\t\t\t\tlogger.debug(\"matched file: \" + cd.selectedSourceFiles.size() + \" to source \" + source.getSourceName());\n\t\t\t}\n\t\t\tcd.sourceFileArrayListMap.put(source, cd.selectedSourceFiles);\n\t\t}\n\t\tMap<String, ArrayList<FileRecord>> sourceFileGroup = null;\n\t\tIterator<Entry<Source, Map<Integer, FileRecord>>> ite = cd.sourceFileArrayListMap.entrySet().iterator();\n\t\twhile (ite.hasNext()) {\n\t\t\tfinal Map.Entry sourcePairs = ite.next();\n\t\t\tfinal Source src = (Source) sourcePairs.getKey();\n\t\t\tMap<Integer, FileRecord> sourceFiles = (Map<Integer, FileRecord>) sourcePairs.getValue();\n\t\t\tsourceFileGroup = getSourceFileGroup(sourceFiles, src, repo,order);\n\t\t\tif (sourceFileGroup!=null && sourceFileGroup.keySet().size()>0)\n\t\t\t\tlogger.info(\"matched groups: \" + (sourceFileGroup!=null? sourceFileGroup.keySet().size():\"\") + \" for source \" + src.getSourceName());\n\t\t//\tlogger.debug(sourceFileGroup.toString());\n\t\t\tcd.setGroupFilesArrayListMap(src, sourceFileGroup);\n\t\t}\n\t\treturn cd;\n\t}\n\n\tpublic static void populateRecordingSamples(Repository repo) {\n\t\tPatternCache patternCache = new PatternCache();\n\t\tFileReader flstr = null;\n\t\tBufferedReader buf1st;\n\t\tMap<Recording, String> recMatch = new HashMap<Recording, String>();\n\t\tMatcher matcher;\n\t\tMatcher matcher2;\n\t\tif (repo.getBaseSourcePath() == null)\n\t\t\treturn;\n\t\tFile folder = new File(repo.getBaseSourcePath());\n\t\ttry {\n\t\t\tif (repo.isRecursiveMode()) {\n\t\t\t\tlistOfFiles = FileListing.getFileListing(folder);\n\t\t\t} else {\n\t\t\t\tlistOfFiles = Arrays.asList(folder.listFiles());\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t}\n\t\tif (repo != null && repo.getBaseSourcePath() != null) {\n\t\t\tChartData cd = DataMiner.gatherSourceData(repo,false);\n\t\t\tArrayList sources = repo.getSources();\n\t\t\tIterator sourceArrayListIte = sources.iterator();\n\t\t\twhile (sourceArrayListIte.hasNext()) {\n\n\t\t\t\t// Map<Recording, String> regMap=getRegexp(repo, src);\n\t\t\t\tcd.sourceArrayList = repo.getSources();\n\t\t\t\tIterator<Source> sourceIterator = cd.sourceArrayList.iterator();\n\n\t\t\t\tSource src = (Source) sourceArrayListIte.next();\n\t\t\t\tMap<String, ArrayList<FileRecord>> hm = cd.getGroupFilesMap(src);\n\t\t\t\tlogger.info(\"population\");\n\t\t\t\tif (hm != null && hm.entrySet() != null) {\n\t\t\t\t\tIterator it = hm.entrySet().iterator();\n\t\t\t\t\twhile (it.hasNext()) {\n\t\t\t\t\t\tfinal Map.Entry pairs = (Map.Entry) it.next();\n\t\t\t\t\t\tlogger.info(\"populating: \" + pairs.getKey());\n\t\t\t\t\t\tArrayList<FileRecord> grouFile = (ArrayList<FileRecord>) pairs.getValue();\n\t\t\t\t\t\t// return DataMiner.mine((String) pairs.getKey(),\n\t\t\t\t\t\t// (ArrayList<String>) pairs.getValue(), repo, source,\n\t\t\t\t\t\t// repo.isStats(), repo.isTimings());\n\t\t\t\t\t\tIterator<FileRecord> fileArrayListIterator = grouFile.iterator();\n\t\t\t\t\t\twhile (fileArrayListIterator.hasNext()) {\n\t\t\t\t\t\t\tfinal FileRecord fileName = fileArrayListIterator.next();\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tflstr = new FileReader(new File(fileName.getCompletePath()));\n\t\t\t\t\t\t\t} catch (FileNotFoundException e1) {\n\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbuf1st = new BufferedReader(flstr);\n\t\t\t\t\t\t\tString line;\n\t\t\t\t\t\t\tlogger.info(\"matched file:\" + fileName);\n\t\t\t\t\t\t\trecMatch = getAllRegexSingleMap(repo, src);\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\twhile ((line = buf1st.readLine()) != null) {\n\t\t\t\t\t\t\t\t\t// check against one Recording pattern at a\n\t\t\t\t\t\t\t\t\t// tim\n\t\t\t\t\t\t\t\t\t// if (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\t\t// logger.debug(\"line \" + line);\n\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\tIterator recMatchIte = recMatch.entrySet().iterator();\n\t\t\t\t\t\t\t\t\twhile (recMatchIte.hasNext()) {\n\t\t\t\t\t\t\t\t\t\tMap.Entry me = (Map.Entry) recMatchIte.next();\n\t\t\t\t\t\t\t\t\t\tRecording rec = (Recording) me.getKey();\n\t\t\t\t\t\t\t\t\t\tmatcher = patternCache.getMatcher((String) (rec.getRegexp()), rec.isCaseSensitive(),line);\n\t\t\t\t\t\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\t\t\t\t\t\t// logger.info(\"1**** matched: \" +\n\t\t\t\t\t\t\t\t\t\t\t// line);\n\t\t\t\t\t\t\t\t\t\t\tArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();\n\t\t\t\t\t\t\t\t\t\t\tint cnt = 0;\n\t\t\t\t\t\t\t\t\t\t\tmatcher2 = patternCache.getMatcher((String) me.getValue(), rec.isCaseSensitive(),line);\n\t\t\t\t\t\t\t\t\t\t\tif (matcher2.find()) {\n\n\t\t\t\t\t\t\t\t\t\t\t\tDataVault.addMatchedLines(rec, line);\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\tDataVault.addUnmatchedLines(rec, line);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (IOException e1) {\n\t\t\t\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\t\t\t\te1.printStackTrace();\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\t\t\t}\n\t\t}\n\t}\n\n/*\tpublic static ArrayList<Map> exportData(Repository repo) {\n\t\tgatherMineResultSet(null,repo, null);\n\t\treturn null;\n\n\t}*/\n\t/*\n\t * public static ArrayList<Map> exportData(Repository repo) { PatternCache\n\t * patternCache = new PatternCache(); Matcher matcher = null; ArrayList<Map>\n\t * expVec = new ArrayList<Map>(); File folder = new\n\t * File(repo.getBaseSourcePath()); try { if (repo.isRecursiveMode()) {\n\t * listOfFiles = FileListing.getFileListing(folder); } else { listOfFiles =\n\t * Arrays.asList(folder.listFiles());\n\t * \n\t * } } catch (FileNotFoundException e) { // TODO Auto-generated catch block\n\t * e.printStackTrace(); } if (logger.isEnabledFor(Level.INFO))\n\t * logger.info(\"number of files: \" + listOfFiles.size()); // int[][]\n\t * fileListMatches = new int[listOfFiles.size()][3];\n\t * \n\t * Iterator sourceIterator = repo.getSources().iterator();\n\t * \n\t * while (sourceIterator.hasNext()) { Source r = (Source)\n\t * sourceIterator.next(); ArrayList<String> sourceFiles = new\n\t * ArrayList<String>(); // sourceFiles contains all the matched files for a\n\t * given source\n\t * \n\t * if (r.getActive()) {\n\t * \n\t * for (int i = 0; i < listOfFiles.size(); i++) { if\n\t * (listOfFiles.get(i).isFile()) { // logger.info(\"File \" + //\n\t * listOfFiles.get(i).getName()); String s1 = r.getSourcePattern(); matcher\n\t * = patternCache.getPattern(s1).matcher(listOfFiles.get(i).getName()); if\n\t * (matcher.find()) { try { sourceFiles.add(new\n\t * File(repo.getBaseSourcePath()).toURI().relativize(new\n\t * File(listOfFiles.get(i).getCanonicalPath()).toURI()) .getPath());\n\t * \n\t * //\n\t * logger.info(\" Graphpanel file1: \"+listOfFiles.get(i).getCanonicalPath());\n\t * // logger.info(\" Graphpanel file: \"+new //\n\t * File(repo.getBaseSourcePath()).toURI() // .relativize(new //\n\t * File(listOfFiles.get(i).getCanonicalPath()).toURI()).getPath()); } catch\n\t * (IOException e) { // TODO Auto-generated catch block e.printStackTrace();\n\t * } // sourceFiles.add(listOfFiles.get(i).getAbsolutePath() // +\n\t * listOfFiles.get(i).getName()); } } } logger.info(\"matched file: \" +\n\t * sourceFiles.size() + \" to source group \" + r.getSourceName()); }\n\t * Map<String, ArrayList<String>> sourceFileGroup =\n\t * getSourceFileGroup(sourceFiles, r, repo); expVec.add(sourceFileGroup);\n\t * logger.info(\"matched groups: \" + sourceFileGroup.keySet().size() +\n\t * \" for source \" + r.getSourceName()); Iterator it =\n\t * sourceFileGroup.entrySet().iterator(); while (it.hasNext()) { Map.Entry\n\t * pairs = (Map.Entry) it.next(); logger.info(pairs.getKey().toString() +\n\t * \" = \" + pairs.getValue()); // it.remove(); // avoids a\n\t * ConcurrentModificationException\n\t * \n\t * FileMineResultSet fMR = fastMine((ArrayList<String>) pairs.getValue(),\n\t * repo, r, false, false);\n\t * \n\t * expVec.add(fMR.eventGroupTimeSeries);\n\t * expVec.add(fMR.statGroupTimeSeries); } } return expVec; }\n\t */\n}", "public class PatternCache {\n//\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate Map<String, Pattern> pattern = new HashMap<String, Pattern>();\n\tprivate Map<String, Matcher> matcher = new HashMap<String, Matcher>();\n\n\tpublic Pattern getPattern(String regexp, boolean caseSensitive) {\n\t\tPattern temp = pattern.get(regexp+Boolean.toString(caseSensitive));\n\t\tif (temp!=null){\n\t\t\treturn temp;\n\t\t} else{\n\t\t\tif (caseSensitive){\n\t\t\t\tpattern.put(regexp+caseSensitive, Pattern.compile(regexp));\n\t\t\t}else{\n\t\t\t\tpattern.put(regexp+caseSensitive, Pattern.compile(regexp, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));\n\t\t\t}\t\t\t\n\t\t}\n\t\treturn pattern.get(regexp+caseSensitive);\n\t}\n\t\n\tpublic Matcher getMatcher(String regexp, boolean caseSensitive,String str) {\n\t\tMatcher tempMatcher=matcher.get(regexp+caseSensitive);\n\t\tif (tempMatcher!=null){\n\t\t\treturn tempMatcher.reset(str);\n\t\t} else{\n\t\t\tif (caseSensitive){\n\t\t\t\tmatcher.put(regexp+caseSensitive, getPattern(regexp,caseSensitive).matcher(str));\n\t\t\t}else{\n\t\t\t\tmatcher.put(regexp+caseSensitive, getPattern(regexp,caseSensitive).matcher(str));\t\n\t\t\t}\n\t\t}\n\t\treturn matcher.get(regexp+caseSensitive);\n\t}\n\t\n\tpublic Matcher getNewMatcher(String regexp, boolean caseSensitive,String str) {\n\t\treturn getPattern(regexp,caseSensitive).matcher(str);\n\t}\n\t\n}" ]
import javax.swing.JPanel; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import org.apache.log4j.Logger; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.text.ParseException; import org.apache.commons.lang3.time.FastDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import logdruid.data.Repository; import logdruid.data.record.EventRecording; import logdruid.data.record.MetadataRecording; import logdruid.data.record.Recording; import logdruid.data.record.RecordingItem; import logdruid.data.record.StatRecording; import logdruid.ui.NoProcessingRegexTableRenderer; import logdruid.util.DataMiner; import logdruid.util.PatternCache;
/******************************************************************************* * LogDruid : Generate charts and reports using data gathered in log files * Copyright (C) 2016 Frederic Valente ([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 logdruid.ui.table; public class StatRecordingEditorTable extends JPanel { private static Logger logger = Logger.getLogger(DataMiner.class.getName()); private boolean DEBUG = false; static Matcher m; static ArrayList records = null; private MyTableModel model; private String[] header = { "Name", "Before", "Inside type", "Inside regex", "After", "Active", "Show", "Value" }; private ArrayList<Object[]> data = new ArrayList<Object[]>(); JTable table = null; private String theLine = ""; private JTextPane examplePane; private Repository rep = null; private Recording recording; /** * @wbp.parser.constructor */ @SuppressWarnings("unchecked") public StatRecordingEditorTable(JTextPane textPane) { super(new GridLayout(1, 0)); model = new MyTableModel(data, header); table = new JTable(model); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setFont(new Font("SansSerif", Font.PLAIN, 11)); // table.setPreferredScrollableViewportSize(new Dimension(500, 200)); table.setPreferredScrollableViewportSize(table.getPreferredSize()); table.setFillsViewportHeight(true); this.theLine = textPane.getText(); this.examplePane = textPane; // Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); // Set up column sizes. initColumnSizes(table); // Fiddle with the Type column's cell editors/renderers. setUpTypeColumn(table, table.getColumnModel().getColumn(2)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(1)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(3)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(4)); // Add the scroll pane to this panel. add(scrollPane); //Add(); FixValues(); } public StatRecordingEditorTable(Repository repo, Recording re, JTextPane textPane) { super(new GridLayout(1, 0)); this.examplePane = textPane; model = new MyTableModel(data, header); table = new JTable(model); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); rep = repo; this.theLine = textPane.getText(); recording = re; // Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); // Set up column sizes. initColumnSizes(table); // Fiddle with the Type column's cell editors/renderers. setUpTypeColumn(table, table.getColumnModel().getColumn(2)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(3)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(1)); setUpInsideRegexColumn(table, table.getColumnModel().getColumn(4)); // Add the scroll pane to this panel. add(scrollPane);
records = ((StatRecording) re).getRecordingItem();
5
grennis/MongoExplorer
app/src/main/java/com/innodroid/mongobrowser/ui/ConnectionDetailFragment.java
[ "public class Events {\n public static void postAddConnection() {\n EventBus.getDefault().post(new AddConnection());\n }\n\n public static void postConnectionSelected(long connectionID) {\n EventBus.getDefault().post(new ConnectionSelected(connectionID));\n }\n\n public static void postConnected(long connectionID) {\n EventBus.getDefault().post(new Connected(connectionID));\n }\n\n public static void postConnectionDeleted() {\n EventBus.getDefault().post(new ConnectionDeleted());\n }\n\n public static void postCollectionSelected(long connectionId, int index) {\n EventBus.getDefault().post(new CollectionSelected(connectionId, index));\n }\n\n public static void postAddDocument() {\n EventBus.getDefault().post(new AddDocument());\n }\n\n public static void postDocumentSelected(int index) {\n EventBus.getDefault().post(new DocumentSelected(index));\n }\n\n public static void postDocumentClicked(int index) {\n EventBus.getDefault().post(new DocumentClicked(index));\n }\n\n public static void postCreateCollection(String name) {\n EventBus.getDefault().post(new CreateCollection(name));\n }\n\n public static void postRenameCollection(String name) {\n EventBus.getDefault().post(new RenameCollection(name));\n }\n\n public static void postCollectionRenamed(String name) {\n EventBus.getDefault().post(new CollectionRenamed(name));\n }\n\n public static void postCollectionDropped() {\n EventBus.getDefault().post(new CollectionDropped());\n }\n\n public static void postConnectionAdded(long connectionId) {\n EventBus.getDefault().post(new ConnectionAdded(connectionId));\n }\n\n public static void postConnectionUpdated(long connectionId) {\n EventBus.getDefault().post(new ConnectionUpdated(connectionId));\n }\n\n public static void postEditDocument(int index) {\n EventBus.getDefault().post(new EditDocument(index));\n }\n\n public static void postDocumentEdited(int index) {\n EventBus.getDefault().post(new DocumentEdited(index));\n }\n\n public static void postDocumentCreated(String content) {\n EventBus.getDefault().post(new DocumentCreated(content));\n }\n\n public static void postDocumentDeleted() {\n EventBus.getDefault().post(new DocumentDeleted());\n }\n\n public static void postChangeDatabase(String name) {\n EventBus.getDefault().post(new ChangeDatabase(name));\n }\n\n public static void postQueryNamed(String name) {\n EventBus.getDefault().post(new QueryNamed(name));\n }\n\n public static void postQueryUpdated(String query) {\n EventBus.getDefault().post(new QueryUpdated(query));\n }\n\n public static void postSettingsChanged() {\n EventBus.getDefault().post(new SettingsChanged());\n }\n\n public static class AddConnection {\n }\n\n public static class AddDocument {\n }\n\n public static class DocumentDeleted {\n }\n\n public static class ConnectionSelected {\n public long ConnectionId;\n\n public ConnectionSelected(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class ConnectionDeleted {\n }\n\n public static class Connected {\n public long ConnectionId;\n\n public Connected(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class CollectionSelected {\n public long ConnectionId;\n public int Index;\n\n public CollectionSelected(long connectionId, int index) {\n ConnectionId = connectionId;\n Index = index;\n }\n }\n\n public static class DocumentSelected {\n public int Index;\n\n public DocumentSelected(int index) {\n Index = index;\n }\n }\n\n public static class DocumentClicked {\n public int Index;\n\n public DocumentClicked(int index) {\n Index = index;\n }\n }\n\n public static class EditDocument {\n public int Index;\n\n public EditDocument(int index) {\n Index = index;\n }\n }\n\n public static class DocumentCreated {\n public String Content;\n\n public DocumentCreated(String content) {\n Content = content;\n }\n }\n\n public static class ChangeDatabase {\n public String Name;\n\n public ChangeDatabase(String name) {\n Name = name;\n }\n }\n\n public static class QueryNamed {\n public String Name;\n\n public QueryNamed(String name) {\n Name = name;\n }\n }\n\n public static class QueryUpdated {\n public String Content;\n\n public QueryUpdated(String content) {\n Content = content;\n }\n }\n\n public static class DocumentEdited {\n public int Index;\n\n public DocumentEdited(int index) {\n Index = index;\n }\n }\n\n public static class CollectionRenamed {\n public String Name;\n\n public CollectionRenamed(String name) {\n Name = name;\n }\n }\n\n public static class RenameCollection {\n public String Name;\n\n public RenameCollection(String name) {\n Name = name;\n }\n }\n\n public static class CreateCollection {\n public String Name;\n\n public CreateCollection(String name) {\n Name = name;\n }\n }\n\n public static class CollectionDropped {\n }\n\n public static class ConnectionAdded {\n public long ConnectionId;\n\n public ConnectionAdded(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class ConnectionUpdated {\n public long ConnectionId;\n\n public ConnectionUpdated(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class SettingsChanged {\n }\n}", "public class MongoHelper {\n\tprivate static MongoClient Connection;\n\tprivate static MongoDatabase Database;\n\tprivate static String DatabaseName;\n\tprivate static String Server;\n\tprivate static int Port;\n\tprivate static String User;\n\tprivate static String Password;\n\t\n\tpublic static void connect(String server, int port, String dbname, String user, String pass) throws UnknownHostException {\n\t\tdisconnect();\n\n\t\tServerAddress sa = new ServerAddress(server, port);\n\n\t\tif (user != null && user.length() > 0) {\n\t\t\tList<MongoCredential> creds = new ArrayList<>();\n\t\t\tcreds.add(MongoCredential.createScramSha1Credential(user, dbname, pass.toCharArray()));\n\t\t\tConnection = new MongoClient(sa, creds);\n\t\t} else {\n\t\t\tConnection = new MongoClient(sa);\n\t\t}\n\n \tDatabase = Connection.getDatabase(dbname);\n \tServer = server;\n \tPort = port;\n \tDatabaseName = dbname;\n \t\n \tUser = user;\n \tPassword = pass;\n \t\n \tConnection.setWriteConcern(WriteConcern.SAFE);\n\t\tDatabase.listCollectionNames().first();\n\t}\n\t\n private static void disconnect() {\n \ttry {\n\t \tif (Connection != null) {\n\t \t\tConnection.close();\n\t \t\tConnection = null;\n\t \t\tDatabase = null;\n\t \t}\n \t} catch (Exception ex) {\n \t\tex.printStackTrace();\n \t}\n\t}\n \n private static void reconnect() throws UnknownHostException {\n \tdisconnect();\n \tconnect(Server, Port, DatabaseName, User, Password);\n }\n\n public static void changeDatabase(String name) throws UnknownHostException {\n \tLog.i(\"MONGO\", \"Change to database \" + name);\n\t\tdisconnect();\n\t\tconnect(Server, Port, name, User, Password);\n }\n \n\tpublic static List<MongoCollectionRef> getCollectionNames(boolean includeSystemPrefs) {\n\t\tMongoIterable<String> names = Database.listCollectionNames();\n \tArrayList<MongoCollectionRef> list = new ArrayList<>();\n \t\n \tfor (String str : names)\n \t\tif (includeSystemPrefs || !str.startsWith(\"system.\"))\n \t\t\tlist.add(new MongoCollectionRef(str));\n\n\t\treturn list;\n }\n\n\tpublic static ArrayList<String> getDatabaseNames() {\n \tArrayList<String> list = new ArrayList<String>();\n\n \tfor (String str : Connection.getDatabaseNames())\n\t\t\tlist.add(str);\n\n \treturn list;\n }\n\t\n\tpublic static long getCollectionCount(String name) {\n\t\treturn Database.getCollection(name).count();\n\t}\n\t\n\tpublic static void createCollection(String name) throws Exception {\n\t\tDatabase.createCollection(name);\n\t}\n\t\n\tpublic static void renameCollection(String oldName, String newName) throws UnknownHostException {\n\t\treconnect();\n\t\tMongoNamespace ns = new MongoNamespace(Database.getName() + \".\" + newName);\n\t\tDatabase.getCollection(oldName).renameCollection(ns);\n\t}\n\n\tpublic static List<MongoDocument> getPageOfDocuments(String collection, String queryText, int start, int take) {\n\t\tMongoCollection coll = Database.getCollection(collection);\n\t\tFindIterable main = (queryText == null) ? coll.find() : coll.find(Document.parse(queryText));\n\t\tFindIterable items = main.skip(start).limit(take);\n\t\tfinal ArrayList<MongoDocument> results = new ArrayList<>();\n\n\t\titems.forEach(new Block<Document>() {\n\t\t\t@Override\n\t\t\tpublic void apply(final Document document) {\n\t\t\t\tresults.add(new MongoDocument(document.toJson()));\n\t\t\t}\n\t\t});\n\n\t\treturn results;\n\t}\n\n\tpublic static void dropCollection(String name) {\n\t\tDatabase.getCollection(name).drop();\n\t}\n\n\tpublic static String saveDocument(String collectionName, String content) {\n\t\tDocument doc = Document.parse(content);\n\n\t\tif (doc.containsKey(\"_id\")) {\n\t\t\tDocument filter = new Document(\"_id\", doc.get(\"_id\"));\n\t\t\tDatabase.getCollection(collectionName).findOneAndReplace(filter, doc);\n\t\t} else {\n\t\t\tDatabase.getCollection(collectionName).insertOne(doc);\n\t\t}\n\n\t\treturn doc.toJson();\n\t}\n\n\tpublic static void deleteDocument(String collectionName, String content) {\n\t\tDocument doc = Document.parse(content);\n\n\t\tif (doc.containsKey(\"_id\")) {\n\t\t\tDocument filter = new Document(\"_id\", doc.get(\"_id\"));\n\t\t\tDatabase.getCollection(collectionName).findOneAndDelete(filter);\n\t\t}\n\t}\n}", "public class Constants {\n\tpublic static final String LOG_TAG = \"mongoexp\";\n\n\tpublic static final String ARG_CONNECTION_ID = \"connid\";\n\tpublic static final String ARG_COLLECTION_INDEX = \"collname\";\n\tpublic static final String ARG_ACTIVATE_ON_CLICK = \"actonclick\";\n\tpublic static final String ARG_DOCUMENT_TITLE = \"doctitle\";\n\tpublic static final String ARG_DOCUMENT_INDEX = \"doccontent\";\n\tpublic static final String ARG_CONTENT = \"thecontent\";\n\n\tpublic static final long SLIDE_ANIM_DURATION = 600;\n\t\n\tpublic static final String NEW_DOCUMENT_CONTENT = \"{\\n \\n}\\n\";\n\tpublic static final String NEW_DOCUMENT_CONTENT_PADDED = \"{\\n \\n}\\n\\n\\n\\n\\n\";\n}", "public class MongoBrowserProvider extends ContentProvider {\n\n\tprivate static final String LOG_TAG = \"MongoBrowserProvider\";\n\tprivate static final String DATABASE_NAME = \"mongobrowser.db\";\n\tpublic static final String TABLE_NAME_CONNECTIONS = \"connections\";\n\tpublic static final String TABLE_NAME_QUERIES = \"queries\";\n\tprivate static final int DATABASE_VERSION = 20;\n\n\tpublic static final int INDEX_CONNECTION_ID = 0;\n\tpublic static final int INDEX_CONNECTION_NAME = 1;\n\tpublic static final int INDEX_CONNECTION_SERVER = 2;\n public static final int INDEX_CONNECTION_PORT = 3; \n public static final int INDEX_CONNECTION_DB = 4; \n\tpublic static final int INDEX_CONNECTION_USER = 5;\n\tpublic static final int INDEX_CONNECTION_PASSWORD = 6;\n\tpublic static final int INDEX_CONNECTION_FLAGS = 7;\n\tpublic static final int INDEX_CONNECTION_LAST_CONNECT = 8;\n\t\n\tpublic static final String NAME_CONNECTION_NAME = \"name\";\n\tpublic static final String NAME_CONNECTION_SERVER = \"server\";\n public static final String NAME_CONNECTION_PORT = \"port\"; \n public static final String NAME_CONNECTION_DB = \"dbname\"; \n\tpublic static final String NAME_CONNECTION_USER = \"usernm\";\n\tpublic static final String NAME_CONNECTION_PASSWORD = \"pass\";\n\tpublic static final String NAME_CONNECTION_FLAGS = \"cflags\";\n\tpublic static final String NAME_CONNECTION_LAST_CONNECT = \"lastconn\";\n\n\tpublic static final int INDEX_QUERY_ID = 0;\n\tpublic static final int INDEX_QUERY_NAME = 1;\n\tpublic static final int INDEX_QUERY_CONN_ID = 2;\n\tpublic static final int INDEX_QUERY_COLL_NAME = 3;\n\tpublic static final int INDEX_QUERY_TEXT = 4;\n\t\n\tpublic static final String NAME_QUERY_NAME = \"qname\";\n\tpublic static final String NAME_QUERY_CONN_ID = \"connid\";\n\tpublic static final String NAME_QUERY_COLL_NAME = \"coll\";\n\tpublic static final String NAME_QUERY_TEXT = \"qtext\";\n\n\t//setup authority for provider\n\tprivate static final String AUTHORITY = \"com.innodroid.provider.mongobrowser\";\n\n\t//URI's to consume this provider\n\tpublic static final Uri CONNECTION_URI = Uri.parse(\"content://\" + AUTHORITY + \"/connections\");\n\tpublic static final String CONNECTION_ITEM_TYPE = \"vnd.android.cursor.item/vnd.innodroid.connection\";\n public static final String CONNECTION_LIST_TYPE = \"vnd.android.cursor.dir/vnd.innodroid.connection\";\n\n\tpublic static final Uri QUERY_URI = Uri.parse(\"content://\" + AUTHORITY + \"/queries\");\n\tpublic static final String QUERY_ITEM_TYPE = \"vnd.android.cursor.item/vnd.innodroid.query\";\n public static final String QUERY_LIST_TYPE = \"vnd.android.cursor.dir/vnd.innodroid.query\";\n\n //Create the statics used to differentiate between the different URI requests\n private static final int CONNECTION_ONE = 1; \n private static final int CONNECTION_ALL = 2;\n private static final int QUERY_ONE = 3; \n private static final int QUERY_ALL = 4;\n\n\t//database members\n\tprivate SQLiteOpenHelper mOpenHelper;\n private SQLiteDatabase mDatabase;\n\n\tprivate static final UriMatcher URI_MATCHER;\n\t\n static \n\t{\n URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);\n\n URI_MATCHER.addURI(AUTHORITY, \"connections/#\", CONNECTION_ONE);\n URI_MATCHER.addURI(AUTHORITY, \"connections\", CONNECTION_ALL);\n URI_MATCHER.addURI(AUTHORITY, \"queries/#\", QUERY_ONE);\n URI_MATCHER.addURI(AUTHORITY, \"queries\", QUERY_ALL);\n }\n\n\t@Override\n\tpublic boolean onCreate() {\n\t\t mOpenHelper = new DatabaseHelper(getContext());\n\t\t mDatabase = mOpenHelper.getWritableDatabase();\n\t\t return true;\n\t}\n\n\t@Override\n\tpublic String getType(Uri uri) {\n\t\tswitch (URI_MATCHER.match(uri)) {\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\treturn CONNECTION_LIST_TYPE;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\treturn CONNECTION_ITEM_TYPE;\n\t\t\tcase QUERY_ALL:\n\t\t\t\treturn QUERY_LIST_TYPE;\n\t\t\tcase QUERY_ONE:\n\t\t\t\treturn QUERY_ITEM_TYPE;\n\t\t\tdefault: \n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {\n\t\tCursor cursor;\n\t\t\n\t\tswitch (URI_MATCHER.match(uri)) {\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_CONNECTIONS, projection, selection, selectionArgs, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\tString xid = uri.getPathSegments().get(1);\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_CONNECTIONS, projection, BaseColumns._ID + \" = ?\", new String[] { xid }, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_QUERIES, projection, selection, selectionArgs, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ONE:\n\t\t\t\tString yid = uri.getPathSegments().get(1);\n\t\t\t\tcursor = mDatabase.query(TABLE_NAME_QUERIES, projection, BaseColumns._ID + \" = ?\", new String[] { yid }, null, null, sortOrder);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\t\t\t\t\n\t\t}\n\t\t\n\t\tcursor.setNotificationUri(getContext().getContentResolver(), uri);\t\t\t\t\t\n\t\treturn cursor;\n\t}\n\n\t@Override\n\tpublic Uri insert(Uri uri, ContentValues values) {\n\t\tString table;\n\t\tUri newUri;\n\t\t\n\t\tswitch (URI_MATCHER.match(uri)) {\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\ttable = TABLE_NAME_CONNECTIONS;\n\t\t\t\tnewUri = CONNECTION_URI;\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\ttable = TABLE_NAME_QUERIES;\n\t\t\t\tnewUri = QUERY_URI;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unknown URI \" + uri);\t\t\t\n\t\t}\n\n\t\tlong id = mDatabase.insert(table, null, values);\n\t\tnewUri = ContentUris.withAppendedId(newUri, id);\n\t\tgetContext().getContentResolver().notifyChange(newUri, null);\n\t\tLog.d(LOG_TAG, \"Insert \" + id);\n\n\t\treturn newUri;\n\t}\n\t\n\t@Override\n\tpublic int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {\n\t\tint count = 0;\n\t\t\n\t\tswitch (URI_MATCHER.match(uri))\n\t\t{\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_CONNECTIONS, values, selection, selectionArgs);\n\t\t\t\tbreak;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\tString xid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_CONNECTIONS, values, BaseColumns._ID + \" = ?\", new String[] { xid });\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_QUERIES, values, selection, selectionArgs);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ONE:\n\t\t\t\tString yid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.update(TABLE_NAME_QUERIES, values, BaseColumns._ID + \" = ?\", new String[] { yid });\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\t\t\t\t\n\t\t}\n\n\t\tgetContext().getContentResolver().notifyChange(uri, null);\n\t\treturn count;\n\t}\n\n\t@Override\n\tpublic int delete(Uri uri, String where, String[] whereArgs) {\n\t\tint count=0;\n\n\t\tswitch (URI_MATCHER.match(uri))\n\t\t{\n\t\t\tcase CONNECTION_ALL:\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_CONNECTIONS, where, whereArgs);\n\t\t\t\tbreak;\n\t\t\tcase CONNECTION_ONE:\n\t\t\t\tString xid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_CONNECTIONS, BaseColumns._ID + \" = ?\", new String[] { xid });\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ALL:\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_QUERIES, where, whereArgs);\n\t\t\t\tbreak;\n\t\t\tcase QUERY_ONE:\n\t\t\t\tString yid = uri.getPathSegments().get(1);\n\t\t\t\tcount = mDatabase.delete(TABLE_NAME_QUERIES, BaseColumns._ID + \" = ?\", new String[] { yid });\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unsupported URI:\" + uri);\t\t\t\t\n\t\t}\n\t\t\n\t\tgetContext().getContentResolver().notifyChange(uri, null);\n\t\treturn count;\n\t}\n\n\tprivate static class DatabaseHelper extends SQLiteOpenHelper {\n\t\tDatabaseHelper(Context context) {\n\t\t\tsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onCreate(SQLiteDatabase db) {\n\t\t createDatabase(db);\n\t\t}\n\n\t\tprivate void createDatabase(SQLiteDatabase db) {\n\t\t\tcreateConnectionsTable(db);\n\t\t\tcreateQueriesTable(db);\n\n\t\t\t/*\n\t\t\tinsertConnection(db, \"Lumenbox DEV\", \"dbh61.mongolab.com\", 27617, \"lumenbox_dev\", \"lumenuser\", \"hellolumen\");\n\t\t\tinsertConnection(db, \"Lumenbox PROD\", \"ds031277.mongolab.com\", 31277, \"lumenbox\", \"user\", \"user\");\n\t\t\tinsertConnection(db, \"imMeta DEV\", \"ds031637.mongolab.com\", 31637, \"immeta_dev\", \"imm3ta\", \"passw0rd\");\n\t\t\tinsertConnection(db, \"imMeta PROD\", \"ds029817.mongolab.com\", 29817, \"immeta_prod\", \"pr0dm3ta\", \"passw0rd\");\n\t\t\tinsertConnection(db, \"atWork DEV\", \"ds033487.mongolab.com\", 33487, \"atwork_dev\", \"atwork\", \"!hello1!\");\n\t\t\tinsertConnection(db, \"guag\", \"alex.mongohq.com\", 10053, \"getupandgreen\", \"admin\", \"hello123\");\t\n\t\t\t*/\t\n\t\t\t\n\t\t\t/* This used for screenshots */\n\t\t\t/*\n\t\t\tinsertConnection(db, \"Demo App QA\", \"demo.mongolab.com\", 57323, \"demo_qa\", \"app_login\", \"passw0rd\");\n\t\t\tinsertConnection(db, \"Demo App PROD\", \"demo.mongolab.com\", 33487, \"atwork_dev\", \"atwork\", \"!hello1!\");\n\t\t\tinsertConnection(db, \"Support Database\", \"alex.mongohq.com\", 10007, \"support\", \"app_login\", \"hello123\");\t\t\n\t\t\t */\t\t\t\n\t\t}\n\n\t\tprivate void createConnectionsTable(SQLiteDatabase db) {\n\t\t\tLog.w(LOG_TAG, \"Creating a new table - \" + TABLE_NAME_CONNECTIONS);\n\t\t\tdb.execSQL(\n\t\t\t\t\"CREATE TABLE \" + TABLE_NAME_CONNECTIONS + \"(\" + BaseColumns._ID + \" INTEGER PRIMARY KEY, \" \n\t\t\t\t + NAME_CONNECTION_NAME + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_SERVER + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_PORT + \" INTEGER, \"\n\t\t\t\t + NAME_CONNECTION_DB + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_USER + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_PASSWORD + \" TEXT, \"\n\t\t\t\t + NAME_CONNECTION_FLAGS + \" INTEGER, \"\n\t\t\t\t + NAME_CONNECTION_LAST_CONNECT + \" INTEGER\"\n\t\t\t\t + \" );\"\n\t\t\t);\t\t\t\n\t\t}\n\n\t\tprivate void createQueriesTable(SQLiteDatabase db) {\n\t\t\tLog.w(LOG_TAG, \"Creating a new table - \" + TABLE_NAME_QUERIES);\n\t\t\tdb.execSQL(\n\t\t\t\t\"CREATE TABLE \" + TABLE_NAME_QUERIES + \"(\" + BaseColumns._ID + \" INTEGER PRIMARY KEY, \" \n\t\t\t\t + NAME_QUERY_NAME + \" TEXT, \"\n\t\t\t\t + NAME_QUERY_CONN_ID + \" INTEGER, \"\n\t\t\t\t + NAME_QUERY_COLL_NAME + \" TEXT, \"\n\t\t\t\t + NAME_QUERY_TEXT + \" TEXT\"\n\t\t\t\t + \" );\"\n\t\t\t);\t\t\t\n\t\t}\n\t\t\n/*\n\t\tprivate long insertConnection(SQLiteDatabase dbx, String name, String server, int port, String db, String user, String pass) {\n\t\t\tContentValues cv = MongoBrowserProviderHelper.getContentValuesForConnection(name, server, port, db, user, pass);\n\t\t\treturn dbx.insert(TABLE_NAME_CONNECTIONS, null, cv);\n\t\t}\n*/\n\t\t\n\t\t@Override\n\t\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\tLog.w(LOG_TAG, \"Upgrade database\");\n\n\t\t\tif (oldVersion < 20) {\n\t\t\t\tcreateQueriesTable(db);\n\t\t\t}\n\t\t}\n\t}\n}", "public class MongoBrowserProviderHelper {\n\tprivate static final String LOG_TAG = \"MongoBrowserProviderHelper\";\n\tprivate ContentResolver mResolver;\n\n\tpublic MongoBrowserProviderHelper(ContentResolver resolver) {\n\t\tmResolver = resolver;\n\t}\n\n\tpublic long addConnection(String name, String server, int port, String db, String user, String pass) {\n\t\tLog.i(LOG_TAG, \"Adding Connection\");\n\n\t\tContentValues values = getContentValuesForConnection(name, server, port, db, user, pass);\n\t\tUri uri = mResolver.insert(MongoBrowserProvider.CONNECTION_URI, values);\n\t\treturn ContentUris.parseId(uri);\n\t}\n\t\n\tpublic void updateConnection(long id, String name, String server, int port, String db, String user, String pass) {\n\t\tLog.i(LOG_TAG, \"Updating Connection\");\n\n\t\tContentValues values = getContentValuesForConnection(name, server, port, db, user, pass);\n\t\tmResolver.update(MongoBrowserProvider.CONNECTION_URI, values, BaseColumns._ID + \" = ?\", new String[] { Long.toString(id) });\n\t}\n\n\tpublic void updateConnectionLastConnect(long id) {\n\t\tLog.i(LOG_TAG, \"Updating Connection\");\n\t\tlong lastConnect = System.currentTimeMillis();\n\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_LAST_CONNECT, lastConnect);\n\t\tmResolver.update(MongoBrowserProvider.CONNECTION_URI, cv, BaseColumns._ID + \" = ?\", new String[] { Long.toString(id) });\n\t}\n\n\tpublic long saveQuery(long id, String name, long connectionId, String collectionName, String text) {\n\t\tLog.i(LOG_TAG, \"Saving query\");\n\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_TEXT, text);\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_NAME, name);\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_CONN_ID, connectionId);\n\t\tcv.put(MongoBrowserProvider.NAME_QUERY_COLL_NAME, collectionName);\n\n\t\tif (id > 0) {\n\t\t\tUri uri = ContentUris.withAppendedId(MongoBrowserProvider.QUERY_URI, id);\n\t\t\tmResolver.update(uri, cv, null, null);\n\t\t\treturn id;\n\t\t} else {\n\t\t\tUri result = mResolver.insert(MongoBrowserProvider.QUERY_URI, cv);\t\t\t\n\t\t\treturn Long.parseLong(result.getLastPathSegment());\n\t\t}\n\t}\n\n\tpublic void deleteConnection(long id) {\n\t\tLog.i(LOG_TAG, \"Deleting Connection\");\n\n\t\tmResolver.delete(MongoBrowserProvider.CONNECTION_URI, BaseColumns._ID + \" = ?\", new String[] { Long.toString(id) });\n\t}\n\n\tpublic int deleteAllConnections() {\n\t\tLog.i(LOG_TAG, \"Deleting all Connections\");\n\t\treturn mResolver.delete(MongoBrowserProvider.CONNECTION_URI, null, null);\n\t}\n\t\n\tpublic Cursor findQuery(String name, long connectionId, String collectionName) {\n\t\treturn mResolver.query(MongoBrowserProvider.QUERY_URI, null, MongoBrowserProvider.NAME_QUERY_NAME + \" = ? and \" + MongoBrowserProvider.NAME_QUERY_CONN_ID + \" = ? and \" + MongoBrowserProvider.NAME_QUERY_COLL_NAME + \" = ?\", new String[] { name, Long.toString(connectionId), collectionName }, null);\n\t}\n\t\n\tpublic Cursor getNamedQueries(long connectionId, String collectionName) {\n\t\treturn mResolver.query(MongoBrowserProvider.QUERY_URI, null, MongoBrowserProvider.NAME_QUERY_CONN_ID + \" = ? and \" + MongoBrowserProvider.NAME_QUERY_COLL_NAME + \" = ?\", new String[] { Long.toString(connectionId), collectionName }, null);\n\t}\n\n\tpublic static ContentValues getContentValuesForConnection(String name, String server, int port, String db, String user, String pass) {\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_NAME, name);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_SERVER, server);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_PORT, port);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_DB, db);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_USER, user);\n\t\tcv.put(MongoBrowserProvider.NAME_CONNECTION_PASSWORD, pass);\n\t\treturn cv;\n\t}\n\n\tpublic int getConnectionCount() {\n\t\tCursor cursor = mResolver.query(MongoBrowserProvider.CONNECTION_URI, null, null, null, null);\n\t\tint count = cursor.getCount();\n\t\tcursor.close();\n\t\treturn count;\n\t}\n}", "public abstract class SafeAsyncTask<T, U, V> extends AsyncTask<T, U, V>{\n\tprivate Exception mException;\n\tprivate FragmentActivity mFragmentActivity;\n\tprivate ProgressDialog mDialog;\n\t\n\tprotected abstract V safeDoInBackground(T... params) throws Exception;\n\tprotected abstract void safeOnPostExecute(V result);\n\tprotected abstract String getErrorTitle();\n\t\n\tpublic SafeAsyncTask(FragmentActivity activity) {\t\t\n\t\tmFragmentActivity = activity;\n\t}\n\t\n\t@Override\n\tprotected void onPreExecute() {\n\t\tsuper.onPreExecute();\n\t\t\n\t\tString caption = getProgressMessage();\n\t\t\n\t\tif (caption != null)\n\t\t\tmDialog = ProgressDialog.show(mFragmentActivity, null, caption, true, false);\t\t\n\t}\n\t\n\t@Override\n\tprotected V doInBackground(T... params) {\n\t\tmException = null;\n\n\t\ttry {\n\t\t\treturn safeDoInBackground(params);\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tmException = ex;\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onPostExecute(V result) {\n\t\tsuper.onPostExecute(result);\n\n\t\tif (mDialog != null)\n\t\t\tmDialog.dismiss();\n\n\t\tif (mException == null)\n\t\t\tsafeOnPostExecute(result);\n\t\telse\n\t\t\tExceptionDetailDialogFragment.newInstance(getErrorTitle(), mException).show(mFragmentActivity.getSupportFragmentManager(), null);\n\t}\n\n\tprotected String getProgressMessage() {\n\t\treturn null;\n\t}\n}", "public class UiUtils {\n\tpublic interface AlertDialogCallbacks {\n\t\tboolean onOK();\n\t\tboolean onNeutralButton();\n\t}\n\t\n\tpublic interface ConfirmCallbacks {\n\t\tboolean onConfirm();\n\t}\n\n\tpublic static AlertDialogCallbacks EmptyAlertCallbacks = new AlertDialogCallbacks() {\n\t\t@Override\n\t\tpublic boolean onOK() {\n\t\t\treturn true;\n\t\t}\t\t\n\n\t\t@Override\n\t\tpublic boolean onNeutralButton() {\n\t\t\treturn true;\n\t\t}\t\t\n\t};\n\t\n\tpublic static Dialog buildAlertDialog(View view, int icon, int title, boolean hasCancel, int middleButtonText, final AlertDialogCallbacks callbacks) {\n\t\treturn buildAlertDialog(view, icon, view.getResources().getString(title), hasCancel, middleButtonText, callbacks);\n\t}\n\t\n\tpublic static Dialog buildAlertDialog(View view, int icon, String title, boolean hasCancel, int middleButtonText, final AlertDialogCallbacks callbacks) {\n AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext())\n\t .setIcon(icon)\n\t .setView(view)\n\t .setTitle(title)\n\t .setPositiveButton(android.R.string.ok,\n\t new DialogInterface.OnClickListener() {\n\t public void onClick(DialogInterface dialog, int whichButton) {\n\t }\n\t }\n\t );\n \n if (hasCancel) {\n\t builder.setCancelable(true).setNegativeButton(android.R.string.cancel,\n\t\t new DialogInterface.OnClickListener() {\n\t\t public void onClick(DialogInterface dialog, int whichButton) {\n\t\t }\n\t\t }\n\t\t ); \t\n }\n\n if (middleButtonText != 0) {\n\t builder.setNeutralButton(middleButtonText,\n\t\t new DialogInterface.OnClickListener() {\n\t\t public void onClick(DialogInterface dialog, int whichButton) {\n\t\t }\n\t\t }\n\t\t ); \t\n }\n\n final AlertDialog dialog = builder.create();\n\n dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface di) {\n Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);\n b.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n \tif (callbacks.onOK())\n \t\tdialog.dismiss();\n }\n });\n\n b = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);\n b.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n \tif (callbacks.onNeutralButton())\n \t\tdialog.dismiss();\n }\n });\n }\n }); \n \n return dialog;\n\t}\n\t\n\tpublic static Dialog buildAlertDialog(Context context, ListAdapter adapter, OnClickListener listener, int icon, String title) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context)\n\t .setIcon(icon)\n\t .setAdapter(adapter, listener)\n\t .setTitle(title);\n \n builder.setCancelable(true);\n\n final AlertDialog dialog = builder.create();\n\n return dialog;\n\t}\n\n\tpublic static void message(Context context, int title, int message) {\n DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {\n\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t}\n\t\t};\n\n\t\tmessage(context, title, message, onClick);\n\t}\n\n\tpublic static void message(Context context, int title, int message, DialogInterface.OnClickListener onClick) {\n\t\tnew AlertDialog.Builder(context)\n\t\t\t\t.setIcon(R.drawable.ic_info_black)\n\t\t\t\t.setMessage(message)\n\t\t\t\t.setTitle(title)\n\t\t\t\t.setCancelable(true)\n\t\t\t\t.setPositiveButton(android.R.string.ok, onClick)\n\t\t\t\t.create().show();\n\t}\n\n\tpublic static void confirm(Context context, int message, final ConfirmCallbacks callbacks) {\n new AlertDialog.Builder(context)\n\t .setIcon(R.drawable.ic_warning_black)\n\t .setMessage(message)\n\t .setTitle(R.string.title_confirm)\n\t .setCancelable(true)\n\t .setPositiveButton(android.R.string.ok,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t\t\tcallbacks.onConfirm();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t .setNegativeButton(android.R.string.cancel,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t .create().show();\n\t}\n\n\tpublic static String getAppVersionString(Context context) {\n\t\ttry {\n\t\t\tPackageInfo info = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);\n\t\t\treturn \"v\" + info.versionName + \" (Build \" + info.versionCode + \")\";\n\t\t} catch (PackageManager.NameNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn \"\";\n\t\t}\n\t}\n}", "public interface ConfirmCallbacks {\n\tboolean onConfirm();\n}" ]
import java.net.UnknownHostException; import android.content.ContentUris; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.innodroid.mongobrowser.Events; import com.innodroid.mongobrowser.util.MongoHelper; import com.innodroid.mongobrowser.Constants; import com.innodroid.mongobrowser.R; import com.innodroid.mongobrowser.data.MongoBrowserProvider; import com.innodroid.mongobrowser.data.MongoBrowserProviderHelper; import com.innodroid.mongobrowser.util.SafeAsyncTask; import com.innodroid.mongobrowser.util.UiUtils; import com.innodroid.mongobrowser.util.UiUtils.ConfirmCallbacks; import butterknife.Bind; import butterknife.OnClick;
package com.innodroid.mongobrowser.ui; public class ConnectionDetailFragment extends BaseFragment implements LoaderCallbacks<Cursor> { @Bind(R.id.connection_detail_title) TextView mTitle; @Bind(R.id.connection_detail_server) TextView mServer; @Bind(R.id.connection_detail_port) TextView mPort; @Bind(R.id.connection_detail_db) TextView mDB; @Bind(R.id.connection_detail_user) TextView mUser; @Bind(R.id.connection_detail_last_connect) TextView mLastConnect; private long mConnectionID; public ConnectionDetailFragment() { } @NonNull public static ConnectionDetailFragment newInstance(long id) { Bundle arguments = new Bundle(); arguments.putLong(Constants.ARG_CONNECTION_ID, id); ConnectionDetailFragment fragment = new ConnectionDetailFragment(); fragment.setArguments(arguments); return fragment; } @Override public int getTitleText() { return R.string.connection_detail; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); mConnectionID = getArguments().getLong(Constants.ARG_CONNECTION_ID); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(R.layout.fragment_connection_detail, inflater, container, savedInstanceState); getLoaderManager().initLoader(0, getArguments(), this); return view; } @OnClick(R.id.connection_detail_connect) public void clickConnect() { new ConnectTask().execute(); } @OnClick(R.id.fab_edit) public void clickEdit() { editConnection(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.connection_detail_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_connection_detail_delete: deleteConnection(); return true; } return super.onOptionsItemSelected(item); } public Loader<Cursor> onCreateLoader(int arg0, Bundle args) { Uri uri = ContentUris.withAppendedId(MongoBrowserProvider.CONNECTION_URI, mConnectionID); return new CursorLoader(getActivity(), uri, null, null, null, null); } public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { Resources res = getResources(); if (!cursor.moveToFirst()) return; mTitle.setText(cursor.getString(MongoBrowserProvider.INDEX_CONNECTION_NAME)); mServer.setText(res.getString(R.string.server) + " : " + cursor.getString(MongoBrowserProvider.INDEX_CONNECTION_SERVER)); mPort.setText(res.getString(R.string.port) + " : " + cursor.getString(MongoBrowserProvider.INDEX_CONNECTION_PORT)); mDB.setText(res.getString(R.string.database) + " : " + cursor.getString(MongoBrowserProvider.INDEX_CONNECTION_DB)); mUser.setText(res.getString(R.string.user) + " : " + cursor.getString(MongoBrowserProvider.INDEX_CONNECTION_USER)); long lastConnect = cursor.getLong(MongoBrowserProvider.INDEX_CONNECTION_LAST_CONNECT); if (lastConnect == 0) mLastConnect.setText(getResources().getString(R.string.never_connected)); else mLastConnect.setText(String.format(getResources().getString(R.string.last_connected), DateUtils.getRelativeTimeSpanString(lastConnect))); } public void onLoaderReset(Loader<Cursor> arg0) { } private void editConnection() { DialogFragment fragment = ConnectionEditDialogFragment.newInstance(mConnectionID); fragment.show(getFragmentManager(), null); } private void deleteConnection() {
UiUtils.confirm(getActivity(), R.string.confirm_delete_connection, new ConfirmCallbacks() {
6
xuie0000/vlc-android
vlc-android/src/org/videolan/vlc/gui/video/VideoGridFragment.java
[ "public class MediaDatabase {\n public final static String TAG = \"VLC/MediaDatabase\";\n\n private static MediaDatabase instance;\n\n private SQLiteDatabase mDb;\n private static final String DB_NAME = \"vlc_database\";\n private static final int DB_VERSION = 21;\n private static final int CHUNK_SIZE = 50;\n\n private static final String DIR_TABLE_NAME = \"directories_table\";\n private static final String DIR_ROW_PATH = \"path\";\n\n private static final String MEDIA_TABLE_NAME = \"media_table\";\n private static final String MEDIA_VIRTUAL_TABLE_NAME = \"media_table_fts\";\n public static final String MEDIA_LOCATION = \"_id\"; //standard key for primary key, needed for search suggestions\n private static final String MEDIA_TIME = \"time\";\n private static final String MEDIA_LENGTH = \"length\";\n private static final String MEDIA_TYPE = \"type\";\n private static final String MEDIA_PICTURE = \"picture\";\n public static final String MEDIA_TITLE = \"title\";\n private static final String MEDIA_ARTIST = \"artist\";\n private static final String MEDIA_GENRE = \"genre\";\n private static final String MEDIA_ALBUM = \"album\";\n private static final String MEDIA_ALBUMARTIST = \"albumartist\";\n private static final String MEDIA_WIDTH = \"width\";\n private static final String MEDIA_HEIGHT = \"height\";\n private static final String MEDIA_ARTWORKURL = \"artwork_url\";\n private static final String MEDIA_AUDIOTRACK = \"audio_track\";\n private static final String MEDIA_SPUTRACK = \"spu_track\";\n private static final String MEDIA_TRACKNUMBER = \"track_number\";\n private static final String MEDIA_DISCNUMBER = \"disc_number\";\n private static final String MEDIA_LAST_MODIFIED = \"last_modified\";\n\n private static final String PLAYLIST_TABLE_NAME = \"playlist_table\";\n private static final String PLAYLIST_NAME = \"name\";\n\n private static final String PLAYLIST_MEDIA_TABLE_NAME = \"playlist_media_table\";\n private static final String PLAYLIST_MEDIA_ID = \"id\";\n private static final String PLAYLIST_MEDIA_PLAYLISTNAME = \"playlist_name\";\n private static final String PLAYLIST_MEDIA_MEDIALOCATION = \"media_location\";\n private static final String PLAYLIST_MEDIA_ORDER = \"playlist_order\";\n\n private static final String SEARCHHISTORY_TABLE_NAME = \"searchhistory_table\";\n private static final String SEARCHHISTORY_DATE = \"date\";\n private static final String SEARCHHISTORY_KEY = \"key\";\n\n private static final String MRL_TABLE_NAME = \"mrl_table\";\n private static final String MRL_DATE = \"date\";\n private static final String MRL_URI = \"uri\";\n private static final String MRL_TABLE_SIZE = \"100\";\n\n private static final String NETWORK_FAV_TABLE_NAME = \"fav_table\";\n private static final String NETWORK_FAV_URI = \"uri\";\n private static final String NETWORK_FAV_TITLE = \"title\";\n\n public enum mediaColumn {\n MEDIA_TABLE_NAME, MEDIA_PATH, MEDIA_TIME, MEDIA_LENGTH,\n MEDIA_TYPE, MEDIA_PICTURE, MEDIA_TITLE, MEDIA_ARTIST, MEDIA_GENRE, MEDIA_ALBUM,\n MEDIA_ALBUMARTIST, MEDIA_WIDTH, MEDIA_HEIGHT, MEDIA_ARTWORKURL, MEDIA_AUDIOTRACK,\n MEDIA_SPUTRACK, MEDIA_TRACKNUMBER, MEDIA_DISCNUMBER, MEDIA_LAST_MODIFIED\n }\n\n /**\n * Constructor\n *\n * @param context\n */\n private MediaDatabase(Context context) {\n // create or open database\n DatabaseHelper helper = new DatabaseHelper(context);\n this.mDb = helper.getWritableDatabase();\n }\n\n public synchronized static MediaDatabase getInstance() {\n if (instance == null) {\n instance = new MediaDatabase(VLCApplication.getAppContext());\n }\n return instance;\n }\n\n private static class DatabaseHelper extends SQLiteOpenHelper {\n\n public DatabaseHelper(Context context) {\n super(context, DB_NAME, null, DB_VERSION);\n }\n\n @Override\n public SQLiteDatabase getWritableDatabase() {\n SQLiteDatabase db;\n try {\n return super.getWritableDatabase();\n } catch(SQLiteException e) {\n try {\n db = SQLiteDatabase.openOrCreateDatabase(VLCApplication.getAppContext().getDatabasePath(DB_NAME), null);\n } catch(SQLiteException e2) {\n Log.w(TAG, \"SQLite database could not be created! Media library cannot be saved.\");\n db = SQLiteDatabase.create(null);\n }\n }\n int version = db.getVersion();\n if (version != DB_VERSION) {\n db.beginTransaction();\n try {\n if (version == 0) {\n onCreate(db);\n } else {\n onUpgrade(db, version, DB_VERSION);\n }\n db.setVersion(DB_VERSION);\n db.setTransactionSuccessful();\n } finally {\n db.endTransaction();\n }\n }\n return db;\n }\n\n public void dropMediaTableQuery(SQLiteDatabase db) {\n try {\n String query = \"DROP TABLE \" + MEDIA_TABLE_NAME + \";\";\n db.execSQL(query);\n query = \"DROP TABLE \" + MEDIA_VIRTUAL_TABLE_NAME + \";\";\n db.execSQL(query);\n } catch(SQLiteException e)\n {\n Log.w(TAG, \"SQLite tables could not be dropped! Maybe they were missing...\");\n }\n }\n\n public void createMediaTableQuery(SQLiteDatabase db) {\n String query = \"CREATE TABLE IF NOT EXISTS \"\n + MEDIA_TABLE_NAME + \" (\"\n + MEDIA_LOCATION + \" TEXT PRIMARY KEY NOT NULL, \"\n + MEDIA_TIME + \" INTEGER, \"\n + MEDIA_LENGTH + \" INTEGER, \"\n + MEDIA_TYPE + \" INTEGER, \"\n + MEDIA_PICTURE + \" BLOB, \"\n + MEDIA_TITLE + \" TEXT, \"\n + MEDIA_ARTIST + \" TEXT, \"\n + MEDIA_GENRE + \" TEXT, \"\n + MEDIA_ALBUM + \" TEXT, \"\n + MEDIA_ALBUMARTIST + \" TEXT, \"\n + MEDIA_WIDTH + \" INTEGER, \"\n + MEDIA_HEIGHT + \" INTEGER, \"\n + MEDIA_ARTWORKURL + \" TEXT, \"\n + MEDIA_AUDIOTRACK + \" INTEGER, \"\n + MEDIA_SPUTRACK + \" INTEGER, \"\n + MEDIA_TRACKNUMBER + \" INTEGER, \"\n + MEDIA_DISCNUMBER + \" INTEGER, \"\n + MEDIA_LAST_MODIFIED + \" INTEGER\"\n + \");\";\n db.execSQL(query);\n db.execSQL(\"PRAGMA recursive_triggers='ON'\"); //Needed for delete trigger\n query = \"CREATE VIRTUAL TABLE \"\n + MEDIA_VIRTUAL_TABLE_NAME + \" USING FTS3 (\"\n + MEDIA_LOCATION + \", \"\n + MEDIA_TITLE + \", \"\n + MEDIA_ARTIST + \", \"\n + MEDIA_GENRE + \", \"\n + MEDIA_ALBUM + \", \"\n + MEDIA_ALBUMARTIST\n + \");\";\n db.execSQL(query);\n query = \" CREATE TRIGGER media_insert_trigger AFTER INSERT ON \"+\n MEDIA_TABLE_NAME+ \" BEGIN \"+\n \"INSERT INTO \"+MEDIA_VIRTUAL_TABLE_NAME+\" (\"+MEDIA_LOCATION+\", \"+MEDIA_TITLE+\n \", \"+MEDIA_ARTIST+\", \"+MEDIA_GENRE+\", \"+MEDIA_ALBUM+\", \"+MEDIA_ALBUMARTIST+\" )\"+\n \" VALUES (new.\"+MEDIA_LOCATION+\", new.\"+MEDIA_TITLE+\", new.\"+MEDIA_ARTIST+\n \", new.\"+MEDIA_GENRE+\", new.\"+MEDIA_ALBUM+\", new.\"+MEDIA_ALBUMARTIST+\n \"); END;\";\n db.execSQL(query);\n query = \" CREATE TRIGGER media_delete_trigger AFTER DELETE ON \"+MEDIA_TABLE_NAME+ \" BEGIN \"+\n \"DELETE FROM \"+MEDIA_VIRTUAL_TABLE_NAME+\" WHERE \"+MEDIA_LOCATION+\" = old.\"+MEDIA_LOCATION+\";\"+\n \" END;\";\n db.execSQL(query);\n }\n\n private void createPlaylistTablesQuery(SQLiteDatabase db) {\n String createPlaylistTableQuery = \"CREATE TABLE IF NOT EXISTS \" +\n PLAYLIST_TABLE_NAME + \" (\" +\n PLAYLIST_NAME + \" VARCHAR(200) PRIMARY KEY NOT NULL);\";\n\n db.execSQL(createPlaylistTableQuery);\n\n String createPlaylistMediaTableQuery = \"CREATE TABLE IF NOT EXISTS \" +\n PLAYLIST_MEDIA_TABLE_NAME + \" (\" +\n PLAYLIST_MEDIA_ID + \" INTEGER PRIMARY KEY AUTOINCREMENT, \" +\n PLAYLIST_MEDIA_PLAYLISTNAME + \" VARCHAR(200) NOT NULL,\" +\n PLAYLIST_MEDIA_MEDIALOCATION + \" TEXT NOT NULL,\" +\n PLAYLIST_MEDIA_ORDER + \" INTEGER NOT NULL);\";\n\n db.execSQL(createPlaylistMediaTableQuery);\n }\n\n private void createMRLTableQuery(SQLiteDatabase db) {\n String createMrlTableQuery = \"CREATE TABLE IF NOT EXISTS \" +\n MRL_TABLE_NAME + \" (\" +\n MRL_URI + \" TEXT PRIMARY KEY NOT NULL,\"+\n MRL_DATE + \" DATETIME NOT NULL\"\n +\");\";\n db.execSQL(createMrlTableQuery);\n createMrlTableQuery = \" CREATE TRIGGER mrl_history_trigger AFTER INSERT ON \"+\n MRL_TABLE_NAME+ \" BEGIN \"+\n \" DELETE FROM \"+MRL_TABLE_NAME+\" where \"+MRL_URI+\" NOT IN (SELECT \"+MRL_URI+\n \" from \"+MRL_TABLE_NAME+\" ORDER BY \"+MRL_DATE+\" DESC LIMIT \"+MRL_TABLE_SIZE+\");\"+\n \" END\";\n db.execSQL(createMrlTableQuery);\n }\n\n public void dropMRLTableQuery(SQLiteDatabase db) {\n try {\n String query = \"DROP TABLE \" + MRL_TABLE_NAME + \";\";\n db.execSQL(query);\n } catch(SQLiteException e)\n {\n Log.w(TAG, \"SQLite tables could not be dropped! Maybe they were missing...\");\n }\n }\n\n private void createNetworkFavTableQuery(SQLiteDatabase db) {\n String createMrlTableQuery = \"CREATE TABLE IF NOT EXISTS \" +\n NETWORK_FAV_TABLE_NAME + \" (\" +\n NETWORK_FAV_URI + \" TEXT PRIMARY KEY NOT NULL, \" +\n NETWORK_FAV_TITLE + \" TEXT NOT NULL\" +\n \");\";\n db.execSQL(createMrlTableQuery);\n }\n\n public void dropNetworkFavTableQuery(SQLiteDatabase db) {\n try {\n String query = \"DROP TABLE \" + NETWORK_FAV_TABLE_NAME + \";\";\n db.execSQL(query);\n } catch(SQLiteException e) {\n Log.w(TAG, \"SQLite tables could not be dropped! Maybe they were missing...\");\n }\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n\n String createDirTabelQuery = \"CREATE TABLE IF NOT EXISTS \"\n + DIR_TABLE_NAME + \" (\"\n + DIR_ROW_PATH + \" TEXT PRIMARY KEY NOT NULL\"\n + \");\";\n\n // Create the directories table\n db.execSQL(createDirTabelQuery);\n\n // Create the media table\n createMediaTableQuery(db);\n\n // Create playlist tables\n createPlaylistTablesQuery(db);\n\n String createSearchhistoryTabelQuery = \"CREATE TABLE IF NOT EXISTS \"\n + SEARCHHISTORY_TABLE_NAME + \" (\"\n + SEARCHHISTORY_KEY + \" VARCHAR(200) PRIMARY KEY NOT NULL, \"\n + SEARCHHISTORY_DATE + \" DATETIME NOT NULL\"\n + \");\";\n\n // Create the searchhistory table\n db.execSQL(createSearchhistoryTabelQuery);\n\n createMRLTableQuery(db);\n\n createNetworkFavTableQuery(db);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n dropMediaTableQuery(db);\n createMediaTableQuery(db);\n\n // Upgrade incrementally from oldVersion to newVersion\n for(int i = oldVersion+1; i <= newVersion; i++) {\n switch(i) {\n case 9:\n // Remodelled playlist tables: re-create them\n db.execSQL(\"DROP TABLE \" + PLAYLIST_MEDIA_TABLE_NAME + \";\");\n db.execSQL(\"DROP TABLE \" + PLAYLIST_TABLE_NAME + \";\");\n createPlaylistTablesQuery(db);\n break;\n case 11:\n createMRLTableQuery(db);\n break;\n case 13:\n createNetworkFavTableQuery(db);\n break;\n case 17:\n dropMRLTableQuery(db);\n createMRLTableQuery(db);\n break;\n case 18:\n dropNetworkFavTableQuery(db);\n createNetworkFavTableQuery(db);\n break;\n default:\n break;\n }\n }\n }\n }\n\n /**\n * Get all playlists in the database\n *\n * @return An array of all the playlist names\n */\n public String[] getPlaylists() {\n ArrayList<String> playlists = new ArrayList<String>();\n Cursor c = mDb.query(\n PLAYLIST_TABLE_NAME,\n new String[] { PLAYLIST_NAME },\n null, null, null, null, null);\n\n if (c != null) {\n while (c.moveToNext())\n playlists.add(c.getString(c.getColumnIndex(PLAYLIST_NAME)));\n c.close();\n }\n return playlists.toArray(new String[playlists.size()]);\n }\n\n /**\n * Add new playlist\n *\n * @param name Unique name of the playlist\n * @return False if invalid name or already exists, true otherwise\n */\n public boolean playlistAdd(String name) {\n // Check length\n if(name.length() >= 200)\n return false;\n\n // Check if already exists\n if(playlistExists(name))\n return false;\n\n // Create new playlist\n ContentValues values = new ContentValues();\n values.put(PLAYLIST_NAME, name);\n long res = mDb.insert(PLAYLIST_TABLE_NAME, \"NULL\", values);\n return res != -1;\n }\n\n /**\n * Delete a playlist and all of its entries.\n *\n * @param name Unique name of the playlist\n */\n public void playlistDelete(String name) {\n mDb.delete(PLAYLIST_TABLE_NAME, PLAYLIST_NAME + \"=?\",\n new String[]{ name });\n mDb.delete(PLAYLIST_MEDIA_TABLE_NAME, PLAYLIST_MEDIA_PLAYLISTNAME\n + \"=?\", new String[] { name });\n }\n\n /**\n * Check if the playlist in question exists.\n *\n * @param name Unique name of the playlist\n * @return true if playlist exists, false otherwise\n */\n public boolean playlistExists(String name) {\n // Check duplicates\n Cursor c = mDb.query(PLAYLIST_TABLE_NAME,\n new String[] { PLAYLIST_NAME }, PLAYLIST_NAME + \"= ?\",\n new String[] { name }, null, null, \"1\");\n if (c != null) {\n final int count = c.getCount();\n c.close();\n return (count > 0);\n } else\n return false;\n }\n\n /**\n * Get all items in the specified playlist.\n *\n * @param playlistName Unique name of the playlist\n * @return Array containing MRLs of the playlist in order, or null on error\n */\n @Nullable\n public String[] playlistGetItems(String playlistName) {\n if(!playlistExists(playlistName))\n return null;\n\n Cursor c = mDb.query(\n PLAYLIST_MEDIA_TABLE_NAME,\n new String[] { PLAYLIST_MEDIA_MEDIALOCATION },\n PLAYLIST_MEDIA_PLAYLISTNAME + \"= ?\",\n new String[] { playlistName }, null, null,\n PLAYLIST_MEDIA_ORDER + \" ASC\");\n\n if (c != null) {\n int count = c.getCount();\n String ret[] = new String[count];\n int i = 0;\n while (c.moveToNext()) {\n ret[i] = c.getString(c.getColumnIndex(PLAYLIST_MEDIA_MEDIALOCATION));\n i++;\n }\n c.close();\n return ret;\n } else\n return null;\n }\n\n /**\n * Insert an item with location into playlistName at the specified position\n *\n * @param playlistName Unique name of the playlist\n * @param position Position to insert into\n * @param mrl MRL of the media\n */\n public void playlistInsertItem(String playlistName, int position, String mrl) {\n playlistShiftItems(playlistName, position, 1);\n\n ContentValues values = new ContentValues();\n values.put(PLAYLIST_MEDIA_PLAYLISTNAME, playlistName);\n values.put(PLAYLIST_MEDIA_MEDIALOCATION, mrl);\n values.put(PLAYLIST_MEDIA_ORDER, position);\n mDb.insert(PLAYLIST_MEDIA_TABLE_NAME, \"NULL\", values);\n }\n\n /**\n * Shifts all items starting at position by the given factor.\n *\n * For instance:\n * Before:\n * 0 - A\n * 1 - B\n * 2 - C\n * 3 - D\n *\n * After playlistShiftItems(playlist, 1, 1):\n * 0 - A\n * 2 - B\n * 3 - C\n * 4 - D\n *\n * @param playlistName Unique name of the playlist\n * @param position Position to start shifting at\n * @param factor Factor to shift the order by\n */\n private void playlistShiftItems(String playlistName, int position, int factor) {\n // Increment all media orders by 1 after the insert position\n Cursor c = mDb.query(\n PLAYLIST_MEDIA_TABLE_NAME,\n new String[] { PLAYLIST_MEDIA_ID, PLAYLIST_MEDIA_ORDER },\n PLAYLIST_MEDIA_PLAYLISTNAME + \"=? AND \" + PLAYLIST_MEDIA_ORDER + \" >= ?\",\n new String[] { playlistName, String.valueOf(position) },\n null, null,\n PLAYLIST_MEDIA_ORDER + \" ASC\");\n if (c != null) {\n while (c.moveToNext()) {\n ContentValues cv = new ContentValues();\n int ii = c.getInt(c.getColumnIndex(PLAYLIST_MEDIA_ORDER)) + factor;\n Log.d(TAG, \"ii = \" + ii);\n cv.put(PLAYLIST_MEDIA_ORDER, ii /* i */);\n mDb.update(PLAYLIST_MEDIA_TABLE_NAME, cv, PLAYLIST_MEDIA_ID + \"=?\",\n new String[]{c.getString(c.getColumnIndex(PLAYLIST_MEDIA_ID))});\n }\n c.close();\n }\n }\n\n /**\n * Removes the item at the given position\n *\n * @param playlistName Unique name of the playlist\n * @param position Position to remove\n */\n public void playlistRemoveItem(String playlistName, int position) {\n mDb.delete(PLAYLIST_MEDIA_TABLE_NAME,\n PLAYLIST_MEDIA_PLAYLISTNAME + \"=? AND \" +\n PLAYLIST_MEDIA_ORDER + \"=?\",\n new String[] { playlistName, Integer.toString(position) });\n\n playlistShiftItems(playlistName, position + 1, -1);\n }\n\n /**\n * Rename the specified playlist.\n *\n * @param playlistName Unique name of the playlist\n * @param newPlaylistName New name of the playlist\n * @return false on error, if playlist doesn't exist or if the new name\n * already exists, true otherwise\n */\n public boolean playlistRename(String playlistName, String newPlaylistName) {\n if(!playlistExists(playlistName) || playlistExists(newPlaylistName))\n return false;\n\n // Update playlist table\n ContentValues values = new ContentValues();\n values.put(PLAYLIST_NAME, newPlaylistName);\n mDb.update(PLAYLIST_TABLE_NAME, values, PLAYLIST_NAME + \" =?\",\n new String[] { playlistName });\n\n // Update playlist media table\n values = new ContentValues();\n values.put(PLAYLIST_MEDIA_PLAYLISTNAME, newPlaylistName);\n mDb.update(PLAYLIST_MEDIA_TABLE_NAME, values,\n PLAYLIST_MEDIA_PLAYLISTNAME + \" =?\",\n new String[]{ playlistName });\n\n return true;\n }\n\n private static void safePut(ContentValues values, String key, String value) {\n if (value == null)\n values.putNull(key);\n else\n values.put(key, value);\n }\n\n /**\n * Add a new media to the database. The picture can only added by update.\n * @param media which you like to add to the database\n */\n public synchronized void addMedia(MediaWrapper media) {\n\n ContentValues values = new ContentValues();\n\n values.put(MEDIA_LOCATION, media.getUri().toString());\n values.put(MEDIA_TIME, media.getTime());\n values.put(MEDIA_LENGTH, media.getLength());\n values.put(MEDIA_TYPE, media.getType());\n values.put(MEDIA_TITLE, media.getTitle());\n safePut(values, MEDIA_ARTIST, media.getArtist());\n safePut(values, MEDIA_GENRE, media.getGenre());\n safePut(values, MEDIA_ALBUM, media.getAlbum());\n safePut(values, MEDIA_ALBUMARTIST, media.getAlbumArtist());\n values.put(MEDIA_WIDTH, media.getWidth());\n values.put(MEDIA_HEIGHT, media.getHeight());\n values.put(MEDIA_ARTWORKURL, media.getArtworkURL());\n values.put(MEDIA_AUDIOTRACK, media.getAudioTrack());\n values.put(MEDIA_SPUTRACK, media.getSpuTrack());\n values.put(MEDIA_TRACKNUMBER, media.getTrackNumber());\n values.put(MEDIA_DISCNUMBER, media.getDiscNumber());\n values.put(MEDIA_LAST_MODIFIED, media.getLastModified());\n\n mDb.replace(MEDIA_TABLE_NAME, \"NULL\", values);\n\n }\n\n /**\n * Check if the item is already in the database\n * @param location of the item (primary key)\n * @return True if the item exists, false if it does not\n */\n public synchronized boolean mediaItemExists(Uri uri) {\n try {\n Cursor cursor = mDb.query(MEDIA_TABLE_NAME,\n new String[] { MEDIA_LOCATION },\n MEDIA_LOCATION + \"=?\",\n new String[] { uri.toString() },\n null, null, null);\n if (cursor != null) {\n final boolean exists = cursor.moveToFirst();\n cursor.close();\n return exists;\n } else\n return false;\n } catch (Exception e) {\n Log.e(TAG, \"Query failed\");\n return false;\n }\n }\n\n /**\n * Get all paths from the items in the database\n * @return list of File\n */\n @SuppressWarnings(\"unused\")\n private synchronized HashSet<File> getMediaFiles() {\n\n HashSet<File> files = new HashSet<File>();\n Cursor cursor;\n\n cursor = mDb.query(\n MEDIA_TABLE_NAME,\n new String[] { MEDIA_LOCATION },\n null, null, null, null, null);\n if (cursor != null) {\n cursor.moveToFirst();\n if (!cursor.isAfterLast()) {\n do {\n File file = new File(cursor.getString(0));\n files.add(file);\n } while (cursor.moveToNext());\n }\n cursor.close();\n }\n\n return files;\n }\n\n public synchronized Cursor queryMedia(String query){\n String[] queryColumns = new String[]{MEDIA_LOCATION, MEDIA_TITLE};\n return mDb.query(MEDIA_VIRTUAL_TABLE_NAME, queryColumns, MEDIA_VIRTUAL_TABLE_NAME+\" MATCH ?\",\n new String[]{query + \"*\"}, null, null, null, null);\n }\n\n public synchronized ArrayList<String> searchMedia(String filter){\n\n ArrayList<String> mediaList = new ArrayList<String>();\n Cursor cursor = queryMedia(filter);\n if (cursor != null) {\n if (cursor.moveToFirst()) {\n do {\n mediaList.add(cursor.getString(0));\n } while (cursor.moveToNext());\n }\n cursor.close();\n }\n return mediaList;\n }\n\n public synchronized HashMap<String, MediaWrapper> getMedias() {\n\n Cursor cursor;\n HashMap<String, MediaWrapper> medias = new HashMap<String, MediaWrapper>();\n int chunk_count = 0;\n int count;\n\n do {\n count = 0;\n cursor = mDb.rawQuery(String.format(Locale.US,\n \"SELECT %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s FROM %s LIMIT %d OFFSET %d\",\n MEDIA_LOCATION, //0 string\n MEDIA_TIME, //1 long\n MEDIA_LENGTH, //2 long\n MEDIA_TYPE, //3 int\n MEDIA_TITLE, //4 string\n MEDIA_ARTIST, //5 string\n MEDIA_GENRE, //6 string\n MEDIA_ALBUM, //7 string\n MEDIA_ALBUMARTIST, //8 string\n MEDIA_WIDTH, //9 int\n MEDIA_HEIGHT, //10 int\n MEDIA_ARTWORKURL, //11 string\n MEDIA_AUDIOTRACK, //12 int\n MEDIA_SPUTRACK, //13 int\n MEDIA_TRACKNUMBER, // 14 int\n MEDIA_DISCNUMBER, //15 int\n MEDIA_LAST_MODIFIED, //16 long\n MEDIA_TABLE_NAME,\n CHUNK_SIZE,\n chunk_count * CHUNK_SIZE), null);\n\n if (cursor != null) {\n if (cursor.moveToFirst()) {\n try {\n do {\n final Uri uri = AndroidUtil.LocationToUri(cursor.getString(0));\n MediaWrapper media = new MediaWrapper(uri,\n cursor.getLong(1), // MEDIA_TIME\n cursor.getLong(2), // MEDIA_LENGTH\n cursor.getInt(3), // MEDIA_TYPE\n null, // MEDIA_PICTURE\n cursor.getString(4), // MEDIA_TITLE\n cursor.getString(5), // MEDIA_ARTIST\n cursor.getString(6), // MEDIA_GENRE\n cursor.getString(7), // MEDIA_ALBUM\n cursor.getString(8), // MEDIA_ALBUMARTIST\n cursor.getInt(9), // MEDIA_WIDTH\n cursor.getInt(10), // MEDIA_HEIGHT\n cursor.getString(11), // MEDIA_ARTWORKURL\n cursor.getInt(12), // MEDIA_AUDIOTRACK\n cursor.getInt(13), // MEDIA_SPUTRACK\n cursor.getInt(14), // MEDIA_TRACKNUMBER\n cursor.getInt(15), // MEDIA_DISCNUMBER\n cursor.getLong(16)); // MEDIA_LAST_MODIFIED\n medias.put(media.getUri().toString(), media);\n\n count++;\n } while (cursor.moveToNext());\n } catch (IllegalStateException e) {\n } //Google bug causing IllegalStateException, see https://code.google.com/p/android/issues/detail?id=32472\n }\n\n cursor.close();\n }\n chunk_count++;\n } while (count == CHUNK_SIZE);\n\n return medias;\n }\n\n public synchronized HashMap<String, Long> getVideoTimes() {\n\n Cursor cursor;\n HashMap<String, Long> times = new HashMap<String, Long>();\n int chunk_count = 0;\n int count;\n\n do {\n count = 0;\n cursor = mDb.rawQuery(String.format(Locale.US,\n \"SELECT %s,%s FROM %s WHERE %s=%d LIMIT %d OFFSET %d\",\n MEDIA_LOCATION, //0 string\n MEDIA_TIME, //1 long\n MEDIA_TABLE_NAME,\n MEDIA_TYPE,\n MediaWrapper.TYPE_VIDEO,\n CHUNK_SIZE,\n chunk_count * CHUNK_SIZE), null);\n\n if (cursor != null) {\n if (cursor.moveToFirst()) {\n do {\n String location = cursor.getString(0);\n long time = cursor.getLong(1);\n times.put(location, time);\n count++;\n } while (cursor.moveToNext());\n }\n\n cursor.close();\n }\n chunk_count++;\n } while (count == CHUNK_SIZE);\n\n return times;\n }\n\n public synchronized MediaWrapper getMedia(Uri uri) {\n\n Cursor cursor;\n MediaWrapper media = null;\n\n try {\n cursor = mDb.query(\n MEDIA_TABLE_NAME,\n new String[] {\n MEDIA_TIME, //0 long\n MEDIA_LENGTH, //1 long\n MEDIA_TYPE, //2 int\n MEDIA_TITLE, //3 string\n MEDIA_ARTIST, //4 string\n MEDIA_GENRE, //5 string\n MEDIA_ALBUM, //6 string\n MEDIA_ALBUMARTIST, //7 string\n MEDIA_WIDTH, //8 int\n MEDIA_HEIGHT, //9 int\n MEDIA_ARTWORKURL, //10 string\n MEDIA_AUDIOTRACK, //11 int\n MEDIA_SPUTRACK, //12 int\n MEDIA_TRACKNUMBER, //13 int\n MEDIA_DISCNUMBER, //14 int\n MEDIA_LAST_MODIFIED, //15 long\n },\n MEDIA_LOCATION + \"=?\",\n new String[] { uri.toString() },\n null, null, null);\n } catch(IllegalArgumentException e) {\n // java.lang.IllegalArgumentException: the bind value at index 1 is null\n return null;\n }\n if (cursor != null) {\n if (cursor.moveToFirst()) {\n media = new MediaWrapper(uri,\n cursor.getLong(0),\n cursor.getLong(1),\n cursor.getInt(2),\n null, // lazy loading, see getPicture()\n cursor.getString(3),\n cursor.getString(4),\n cursor.getString(5),\n cursor.getString(6),\n cursor.getString(7),\n cursor.getInt(8),\n cursor.getInt(9),\n cursor.getString(10),\n cursor.getInt(11),\n cursor.getInt(12),\n cursor.getInt(13),\n cursor.getInt(14),\n cursor.getLong(15));\n }\n cursor.close();\n }\n return media;\n }\n\n public synchronized Bitmap getPicture(Uri uri) {\n /* Used for the lazy loading */\n Cursor cursor;\n Bitmap picture = null;\n byte[] blob;\n\n cursor = mDb.query(\n MEDIA_TABLE_NAME,\n new String[] { MEDIA_PICTURE },\n MEDIA_LOCATION + \"=?\",\n new String[] { uri.toString() },\n null, null, null);\n if (cursor != null) {\n if (cursor.moveToFirst()) {\n blob = cursor.getBlob(0);\n if (blob != null && blob.length > 1 && blob.length < 500000) {\n try {\n picture = BitmapFactory.decodeByteArray(blob, 0, blob.length);\n } catch (OutOfMemoryError e) {\n picture = null;\n } finally {\n blob = null;\n }\n }\n }\n cursor.close();\n }\n return picture;\n }\n\n public synchronized void removeMedia(Uri uri) {\n mDb.delete(MEDIA_TABLE_NAME, MEDIA_LOCATION + \"=?\", new String[]{uri.toString()});\n }\n\n public void removeMedias(Collection<Uri> uris) {\n mDb.beginTransaction();\n try {\n for (Uri uri : uris)\n removeMedia(uri);\n mDb.setTransactionSuccessful();\n } finally {\n mDb.endTransaction();\n }\n }\n\n public void removeMediaWrappers(Collection<MediaWrapper> mws) {\n mDb.beginTransaction();\n try {\n for (MediaWrapper mw : mws)\n removeMedia(mw.getUri());\n mDb.setTransactionSuccessful();\n } finally {\n mDb.endTransaction();\n }\n }\n\n public synchronized void updateMedia(Uri uri, mediaColumn col,\n Object object) {\n\n if (uri == null)\n return;\n\n ContentValues values = new ContentValues();\n switch (col) {\n case MEDIA_PICTURE:\n if (object != null) {\n Bitmap picture = (Bitmap) object;\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n picture.compress(Bitmap.CompressFormat.JPEG, 90, out);\n values.put(MEDIA_PICTURE, out.toByteArray());\n }\n else {\n values.put(MEDIA_PICTURE, new byte[1]);\n }\n break;\n case MEDIA_TIME:\n if (object != null)\n values.put(MEDIA_TIME, (Long)object);\n break;\n case MEDIA_AUDIOTRACK:\n if (object != null)\n values.put(MEDIA_AUDIOTRACK, (Integer)object);\n break;\n case MEDIA_SPUTRACK:\n if (object != null)\n values.put(MEDIA_SPUTRACK, (Integer)object);\n break;\n case MEDIA_LENGTH:\n if (object != null)\n values.put(MEDIA_LENGTH, (Long)object);\n break;\n default:\n return;\n }\n mDb.update(MEDIA_TABLE_NAME, values, MEDIA_LOCATION + \"=?\", new String[]{uri.toString()});\n }\n\n /**\n * Add directory to the directories table\n *\n * @param path\n */\n public synchronized void addDir(String path) {\n ContentValues values = new ContentValues();\n values.put(DIR_ROW_PATH, path);\n mDb.insert(DIR_TABLE_NAME, null, values);\n }\n\n /**\n * Delete directory from directories table\n *\n * @param path\n */\n public synchronized void removeDir(String path) {\n mDb.delete(DIR_TABLE_NAME, DIR_ROW_PATH + \"=?\", new String[]{path});\n }\n\n /**\n * Delete all matching directories from directories table\n *\n * @param path\n */\n public synchronized void recursiveRemoveDir(String path) {\n for(File f : getMediaDirs()) {\n final String dirPath = f.getPath();\n if(dirPath.startsWith(path))\n mDb.delete(DIR_TABLE_NAME, DIR_ROW_PATH + \"=?\", new String[] { dirPath });\n }\n\n }\n\n /**\n *\n * @return\n */\n public synchronized List<File> getMediaDirs() {\n\n List<File> paths = new ArrayList<File>();\n Cursor cursor;\n\n cursor = mDb.query(\n DIR_TABLE_NAME,\n new String[] { DIR_ROW_PATH },\n null, null, null, null, null);\n if (cursor != null) {\n cursor.moveToFirst();\n if (!cursor.isAfterLast()) {\n do {\n File dir = new File(cursor.getString(0));\n paths.add(dir);\n } while (cursor.moveToNext());\n }\n cursor.close();\n }\n\n return paths;\n }\n\n private synchronized boolean mediaDirExists(String path) {\n Cursor cursor = mDb.query(DIR_TABLE_NAME,\n new String[] { DIR_ROW_PATH },\n DIR_ROW_PATH + \"=?\",\n new String[] { path },\n null, null, null);\n boolean exists = cursor.moveToFirst();\n cursor.close();\n return exists;\n }\n\n /**\n *\n * @param key\n */\n public synchronized void addSearchhistoryItem(String key) {\n // set the format to sql date time\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.US);\n Date date = new Date();\n ContentValues values = new ContentValues();\n values.put(SEARCHHISTORY_KEY, key);\n values.put(SEARCHHISTORY_DATE, dateFormat.format(date));\n\n mDb.replace(SEARCHHISTORY_TABLE_NAME, null, values);\n }\n\n public synchronized ArrayList<String> getSearchhistory(int size) {\n ArrayList<String> history = new ArrayList<String>();\n\n Cursor cursor = mDb.query(SEARCHHISTORY_TABLE_NAME,\n new String[]{SEARCHHISTORY_KEY},\n null, null, null, null,\n SEARCHHISTORY_DATE + \" DESC\",\n Integer.toString(size));\n\n while (cursor.moveToNext()) {\n history.add(cursor.getString(0));\n }\n cursor.close();\n\n return history;\n }\n\n public synchronized void clearSearchHistory() {\n mDb.delete(SEARCHHISTORY_TABLE_NAME, null, null);\n }\n\n public synchronized void addMrlhistoryItem(String uri) {\n // set the format to sql date time\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.US);\n Date date = new Date();\n ContentValues values = new ContentValues();\n values.put(MRL_URI, uri);\n values.put(MRL_DATE, dateFormat.format(date));\n\n mDb.replace(MRL_TABLE_NAME, null, values);\n }\n\n public synchronized ArrayList<String> getMrlhistory() {\n ArrayList<String> history = new ArrayList<String>();\n\n Cursor cursor = mDb.query(MRL_TABLE_NAME,\n new String[] { MRL_URI },\n null, null, null, null,\n MRL_DATE + \" DESC\",\n MRL_TABLE_SIZE);\n\n if (cursor != null) {\n while (cursor.moveToNext()) {\n history.add(cursor.getString(0));\n }\n cursor.close();\n }\n\n return history;\n }\n\n public synchronized void deleteMrlUri(String uri) {\n mDb.delete(MRL_TABLE_NAME, MRL_URI + \"=?\", new String[]{uri});\n }\n\n public synchronized void clearMrlHistory() {\n mDb.delete(MRL_TABLE_NAME, null, null);\n }\n\n\n public synchronized void addNetworkFavItem(Uri uri, String title) {\n ContentValues values = new ContentValues();\n values.put(NETWORK_FAV_URI, uri.toString());\n values.put(NETWORK_FAV_TITLE, Uri.encode(title));\n mDb.replace(NETWORK_FAV_TABLE_NAME, null, values);\n }\n\n public synchronized boolean networkFavExists(Uri uri) {\n Cursor cursor = mDb.query(NETWORK_FAV_TABLE_NAME,\n new String[] { NETWORK_FAV_URI },\n NETWORK_FAV_URI + \"=?\",\n new String[] { uri.toString() },\n null, null, null);\n if (cursor != null) {\n final boolean exists = cursor.moveToFirst();\n cursor.close();\n return exists;\n } else\n return false;\n }\n\n public synchronized ArrayList<MediaWrapper> getAllNetworkFav() {\n ArrayList<MediaWrapper> favs = new ArrayList<MediaWrapper>();\n\n MediaWrapper mw;\n Cursor cursor = mDb.query(NETWORK_FAV_TABLE_NAME,\n new String[] { NETWORK_FAV_URI , NETWORK_FAV_TITLE},\n null, null, null, null, null);\n if (cursor != null) {\n while (cursor.moveToNext()) {\n mw = new MediaWrapper(Uri.parse(cursor.getString(0)));\n mw.setTitle(Uri.decode(cursor.getString(1)));\n mw.setType(MediaWrapper.TYPE_DIR);\n favs.add(mw);\n }\n cursor.close();\n }\n\n return favs;\n }\n\n public synchronized void deleteNetworkFav(Uri uri) {\n mDb.delete(NETWORK_FAV_TABLE_NAME, NETWORK_FAV_URI + \"=?\", new String[] { uri.toString() });\n }\n\n public synchronized void clearNetworkFavTable() {\n mDb.delete(NETWORK_FAV_TABLE_NAME, null, null);\n }\n /**\n * Empty the database for debugging purposes\n */\n public synchronized void emptyDatabase() {\n mDb.delete(MEDIA_TABLE_NAME, null, null);\n }\n\n public static void setPicture(MediaWrapper m, Bitmap p) {\n Log.d(TAG, \"Setting new picture for \" + m.getTitle());\n try {\n getInstance().updateMedia(\n m.getUri(),\n mediaColumn.MEDIA_PICTURE,\n p);\n } catch (SQLiteFullException e) {\n Log.d(TAG, \"SQLiteFullException while setting picture\");\n }\n m.setPictureParsed(true);\n }\n}", "public class MediaLibrary {\n public final static String TAG = \"VLC/MediaLibrary\";\n\n public static final int MEDIA_ITEMS_UPDATED = 100;\n\n private static MediaLibrary mInstance;\n private final ArrayList<MediaWrapper> mItemList;\n private final ArrayList<Handler> mUpdateHandler;\n private final ReadWriteLock mItemListLock;\n private boolean isStopping = false;\n private boolean mRestart = false;\n protected Thread mLoadingThread;\n private WeakReference<IBrowser> mBrowser = null;\n\n public final static HashSet<String> FOLDER_BLACKLIST;\n static {\n final String[] folder_blacklist = {\n \"/alarms\",\n \"/notifications\",\n \"/ringtones\",\n \"/media/alarms\",\n \"/media/notifications\",\n \"/media/ringtones\",\n \"/media/audio/alarms\",\n \"/media/audio/notifications\",\n \"/media/audio/ringtones\",\n \"/Android/data/\" };\n\n FOLDER_BLACKLIST = new HashSet<String>();\n for (String item : folder_blacklist)\n FOLDER_BLACKLIST.add(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY + item);\n }\n\n private MediaLibrary() {\n mInstance = this;\n mItemList = new ArrayList<MediaWrapper>();\n mUpdateHandler = new ArrayList<Handler>();\n mItemListLock = new ReentrantReadWriteLock();\n }\n\n public void loadMediaItems(boolean restart) {\n if (restart && isWorking()) {\n /* do a clean restart if a scan is ongoing */\n mRestart = true;\n isStopping = true;\n } else {\n loadMediaItems();\n }\n }\n\n public void loadMediaItems() {\n if (mLoadingThread == null || mLoadingThread.getState() == State.TERMINATED) {\n isStopping = false;\n Util.actionScanStart();\n // 开启线程进行加载》GetMediaItemsRunnable()\n mLoadingThread = new Thread(new GetMediaItemsRunnable());\n mLoadingThread.start();\n }\n }\n\n public void stop() {\n isStopping = true;\n }\n\n public boolean isWorking() {\n if (mLoadingThread != null &&\n mLoadingThread.isAlive() &&\n mLoadingThread.getState() != State.TERMINATED &&\n mLoadingThread.getState() != State.NEW)\n return true;\n return false;\n }\n\n public synchronized static MediaLibrary getInstance() {\n if (mInstance == null)\n mInstance = new MediaLibrary();\n return mInstance;\n }\n\n public void addUpdateHandler(Handler handler) {\n mUpdateHandler.add(handler);\n }\n\n public void removeUpdateHandler(Handler handler) {\n mUpdateHandler.remove(handler);\n }\n\n public ArrayList<MediaWrapper> searchMedia(String query){\n ArrayList<MediaWrapper> mediaList = new ArrayList<MediaWrapper>();\n ArrayList<String> pathList = MediaDatabase.getInstance().searchMedia(query);\n if (!pathList.isEmpty()){\n for (String path : pathList) {\n mediaList.add(getMediaItem(path));\n }\n }\n return mediaList;\n }\n\n public ArrayList<MediaWrapper> getVideoItems() {\n ArrayList<MediaWrapper> videoItems = new ArrayList<MediaWrapper>();\n mItemListLock.readLock().lock();\n for (int i = 0; i < mItemList.size(); i++) {\n MediaWrapper item = mItemList.get(i);\n if (item != null && item.getType() == MediaWrapper.TYPE_VIDEO) {\n videoItems.add(item);\n }\n }\n mItemListLock.readLock().unlock();\n return videoItems;\n }\n\n public ArrayList<MediaWrapper> getAudioItems() {\n ArrayList<MediaWrapper> audioItems = new ArrayList<MediaWrapper>();\n mItemListLock.readLock().lock();\n for (int i = 0; i < mItemList.size(); i++) {\n MediaWrapper item = mItemList.get(i);\n if (item.getType() == MediaWrapper.TYPE_AUDIO) {\n audioItems.add(item);\n }\n }\n mItemListLock.readLock().unlock();\n return audioItems;\n }\n\n public ArrayList<MediaWrapper> getPlaylistFilesItems() {\n ArrayList<MediaWrapper> playlistItems = new ArrayList<MediaWrapper>();\n mItemListLock.readLock().lock();\n for (int i = 0; i < mItemList.size(); i++) {\n MediaWrapper item = mItemList.get(i);\n if (item.getType() == MediaWrapper.TYPE_PLAYLIST) {\n playlistItems.add(item);\n }\n }\n mItemListLock.readLock().unlock();\n return playlistItems;\n }\n\n public ArrayList<AudioBrowserListAdapter.ListItem> getPlaylistDbItems() {\n ArrayList<AudioBrowserListAdapter.ListItem> playlistItems = new ArrayList<AudioBrowserListAdapter.ListItem>();\n AudioBrowserListAdapter.ListItem playList;\n MediaDatabase db = MediaDatabase.getInstance();\n String[] items, playlistNames = db.getPlaylists();\n for (String playlistName : playlistNames){\n items = db.playlistGetItems(playlistName);\n if (items == null)\n continue;\n playList = new AudioBrowserListAdapter.ListItem(playlistName, null, null, false);\n for (String track : items){\n playList.mMediaList.add(new MediaWrapper(AndroidUtil.LocationToUri(track)));\n }\n playlistItems.add(playList);\n }\n return playlistItems;\n }\n\n public ArrayList<MediaWrapper> getMediaItems() {\n return mItemList;\n }\n\n public MediaWrapper getMediaItem(String location) {\n mItemListLock.readLock().lock();\n for (int i = 0; i < mItemList.size(); i++) {\n MediaWrapper item = mItemList.get(i);\n if (item.getLocation().equals(location)) {\n mItemListLock.readLock().unlock();\n return item;\n }\n }\n mItemListLock.readLock().unlock();\n return null;\n }\n\n public ArrayList<MediaWrapper> getMediaItems(List<String> pathList) {\n ArrayList<MediaWrapper> items = new ArrayList<MediaWrapper>();\n for (int i = 0; i < pathList.size(); i++) {\n MediaWrapper item = getMediaItem(pathList.get(i));\n items.add(item);\n }\n return items;\n }\n\n private class GetMediaItemsRunnable implements Runnable {\n\n private final Stack<File> directories = new Stack<File>();\n private final HashSet<String> directoriesScanned = new HashSet<String>();\n\n public GetMediaItemsRunnable() {\n }\n\n @Override\n public void run() {\n LibVLC libVlcInstance = VLCInstance.get();\n\n // Initialize variables\n final MediaDatabase mediaDatabase = MediaDatabase.getInstance();\n\n // show progressbar in footer\n if (mBrowser != null && mBrowser.get() != null)\n mBrowser.get().showProgressBar();\n\n List<File> mediaDirs = mediaDatabase.getMediaDirs();\n if (mediaDirs.size() == 0) {\n // Use all available storage directories as our default\n String storageDirs[] = AndroidDevices.getMediaDirectories();\n for (String dir: storageDirs) {\n File f = new File(dir);\n if (f.exists())\n mediaDirs.add(f);\n }\n }\n directories.addAll(mediaDirs);\n\n // get all existing media items\n HashMap<String, MediaWrapper> existingMedias = mediaDatabase.getMedias();\n\n // list of all added files\n HashSet<String> addedLocations = new HashSet<String>();\n\n // clear all old items\n mItemListLock.writeLock().lock();\n mItemList.clear();\n mItemListLock.writeLock().unlock();\n\n MediaItemFilter mediaFileFilter = new MediaItemFilter();\n\n int count = 0;\n\n LinkedList<File> mediaToScan = new LinkedList<File>();\n try {\n LinkedList<String> dirsToIgnore = new LinkedList<String>();\n // Count total files, and stack them\n while (!directories.isEmpty()) {\n File dir = directories.pop();\n String dirPath = dir.getAbsolutePath();\n\n // Skip some system folders\n if (dirPath.startsWith(\"/proc/\") || dirPath.startsWith(\"/sys/\") || dirPath.startsWith(\"/dev/\"))\n continue;\n\n // Do not scan again if same canonical path\n try {\n dirPath = dir.getCanonicalPath();\n } catch (IOException e) {\n e.printStackTrace();\n }\n if (directoriesScanned.contains(dirPath))\n continue;\n else\n directoriesScanned.add(dirPath);\n\n // Do no scan media in .nomedia folders\n if (new File(dirPath + \"/.nomedia\").exists()) {\n dirsToIgnore.add(\"file://\"+dirPath);\n continue;\n }\n\n // Filter the extensions and the folders\n try {\n String[] files = dir.list();\n if (files != null) {\n for (String fileName : files) {\n File file = new File(dirPath, fileName);\n if (mediaFileFilter.accept(file)){\n if (file.isFile())\n mediaToScan.add(file);\n else if (file.isDirectory())\n directories.push(file);\n }\n }\n }\n } catch (Exception e){\n // listFiles can fail in OutOfMemoryError, go to the next folder\n continue;\n }\n\n if (isStopping) {\n Log.d(TAG, \"Stopping scan\");\n return;\n }\n }\n\n //Remove ignored files\n HashSet<Uri> mediasToRemove = new HashSet<Uri>();\n String path;\n outloop:\n for (Map.Entry<String, MediaWrapper> entry : existingMedias.entrySet()){\n path = entry.getKey();\n for (String dirPath : dirsToIgnore) {\n if (path.startsWith(dirPath)) {\n mediasToRemove.add(entry.getValue().getUri());\n mItemList.remove(existingMedias.get(path));\n continue outloop;\n }\n }\n }\n mediaDatabase.removeMedias(mediasToRemove);\n\n // Process the stacked items\n for (File file : mediaToScan) {\n String fileURI = AndroidUtil.FileToUri(file).toString();\n if (mBrowser != null && mBrowser.get() != null)\n mBrowser.get().sendTextInfo(file.getName(), count,\n mediaToScan.size());\n count++;\n if (existingMedias.containsKey(fileURI)) {\n /**\n * only add file if it is not already in the list. eg. if\n * user select an subfolder as well\n */\n if (!addedLocations.contains(fileURI)) {\n mItemListLock.writeLock().lock();\n // get existing media item from database\n mItemList.add(existingMedias.get(fileURI));\n mItemListLock.writeLock().unlock();\n addedLocations.add(fileURI);\n }\n } else {\n mItemListLock.writeLock().lock();\n // create new media item\n final Media media = new Media(libVlcInstance, Uri.parse(fileURI));\n media.parse();\n /* skip files with .mod extension and no duration */\n if ((media.getDuration() == 0 || (media.getTrackCount() != 0 && TextUtils.isEmpty(media.getTrack(0).codec))) &&\n fileURI.endsWith(\".mod\")) {\n mItemListLock.writeLock().unlock();\n media.release();\n continue;\n }\n MediaWrapper mw = new MediaWrapper(media);\n media.release();\n mw.setLastModified(file.lastModified());\n mItemList.add(mw);\n // Add this item to database\n mediaDatabase.addMedia(mw);\n mItemListLock.writeLock().unlock();\n }\n if (isStopping) {\n Log.d(TAG, \"Stopping scan\");\n return;\n }\n }\n } finally {\n // update the video and audio activities\n for (int i = 0; i < mUpdateHandler.size(); i++) {\n Handler h = mUpdateHandler.get(i);\n h.sendEmptyMessage(MEDIA_ITEMS_UPDATED);\n }\n\n // remove old files & folders from database if storage is mounted\n if (!isStopping && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {\n for (String fileURI : addedLocations) {\n existingMedias.remove(fileURI);\n }\n mediaDatabase.removeMediaWrappers(existingMedias.values());\n\n /*\n * In case of file matching path of a folder from another removable storage\n */\n for (File file : mediaDatabase.getMediaDirs())\n if (!file.isDirectory())\n mediaDatabase.removeDir(file.getAbsolutePath());\n }\n\n // hide progressbar in footer\n if (mBrowser != null && mBrowser.get() != null) {\n mBrowser.get().clearTextInfo();\n mBrowser.get().hideProgressBar();\n }\n\n Util.actionScanStop();\n\n if (mRestart) {\n Log.d(TAG, \"Restarting scan\");\n mRestart = false;\n restartHandler.sendEmptyMessageDelayed(1, 200);\n }\n }\n }\n }\n\n private Handler restartHandler = new RestartHandler(this);\n\n private static class RestartHandler extends WeakHandler<MediaLibrary> {\n public RestartHandler(MediaLibrary owner) {\n super(owner);\n }\n\n @Override\n public void handleMessage(Message msg) {\n MediaLibrary owner = getOwner();\n if(owner == null) return;\n owner.loadMediaItems();\n }\n }\n\n /**\n * Filters all irrelevant files\n */\n private static class MediaItemFilter implements FileFilter {\n\n @Override\n public boolean accept(File f) {\n boolean accepted = false;\n if (!f.isHidden()) {\n if (f.isDirectory() && !FOLDER_BLACKLIST.contains(f.getPath().toLowerCase(Locale.ENGLISH))) {\n accepted = true;\n } else {\n String fileName = f.getName().toLowerCase(Locale.ENGLISH);\n int dotIndex = fileName.lastIndexOf(\".\");\n if (dotIndex != -1) {\n String fileExt = fileName.substring(dotIndex);\n accepted = Extensions.AUDIO.contains(fileExt) ||\n Extensions.VIDEO.contains(fileExt) ||\n Extensions.PLAYLIST.contains(fileExt);\n }\n }\n }\n return accepted;\n }\n }\n\n public void setBrowser(IBrowser browser) {\n if (browser != null)\n mBrowser = new WeakReference<IBrowser>(browser);\n else\n mBrowser.clear();\n }\n}", "public class MediaWrapper implements Parcelable {\n public final static String TAG = \"VLC/MediaWrapper\";\n\n public final static int TYPE_ALL = -1;\n public final static int TYPE_VIDEO = 0;\n public final static int TYPE_AUDIO = 1;\n public final static int TYPE_GROUP = 2;\n public final static int TYPE_DIR = 3;\n public final static int TYPE_SUBTITLE = 4;\n public final static int TYPE_PLAYLIST = 5;\n\n public final static int MEDIA_VIDEO = 0x01;\n public final static int MEDIA_NO_HWACCEL = 0x02;\n public final static int MEDIA_PAUSED = 0x4;\n public final static int MEDIA_FORCE_AUDIO = 0x8;\n\n protected String mTitle;\n private String mArtist;\n private String mGenre;\n private String mCopyright;\n private String mAlbum;\n private int mTrackNumber;\n private int mDiscNumber;\n private String mAlbumArtist;\n private String mDescription;\n private String mRating;\n private String mDate;\n private String mSettings;\n private String mNowPlaying;\n private String mPublisher;\n private String mEncodedBy;\n private String mTrackID;\n private String mArtworkURL;\n\n private final Uri mUri;\n private String mFilename;\n private long mTime = 0;\n /* -1 is a valid track (Disabled) */\n private int mAudioTrack = -2;\n private int mSpuTrack = -2;\n private long mLength = 0;\n private int mType;\n private int mWidth = 0;\n private int mHeight = 0;\n private Bitmap mPicture;\n private boolean mIsPictureParsed;\n private int mFlags = 0;\n private long mLastModified = 0l;\n\n /**\n * Create a new MediaWrapper\n * @param uri Should not be null.\n */\n public MediaWrapper(Uri uri) {\n if (uri == null)\n throw new NullPointerException(\"uri was null\");\n\n mUri = uri;\n init(null);\n }\n\n /**\n * Create a new MediaWrapper\n * @param media should be parsed and not NULL\n */\n public MediaWrapper(Media media) {\n if (media == null)\n throw new NullPointerException(\"media was null\");\n\n mUri = media.getUri();\n init(media);\n }\n\n private void init(Media media) {\n mType = TYPE_ALL;\n\n if (media != null) {\n if (media.isParsed()) {\n mLength = media.getDuration();\n\n for (int i = 0; i < media.getTrackCount(); ++i) {\n final Media.Track track = media.getTrack(i);\n if (track == null)\n continue;\n if (track.type == Media.Track.Type.Video) {\n final Media.VideoTrack videoTrack = (VideoTrack) track;\n mType = TYPE_VIDEO;\n mWidth = videoTrack.width;\n mHeight = videoTrack.height;\n } else if (mType == TYPE_ALL && track.type == Media.Track.Type.Audio){\n mType = TYPE_AUDIO;\n }\n }\n }\n updateMeta(media);\n if (mType == TYPE_ALL && media.getType() == Media.Type.Directory)\n mType = TYPE_DIR;\n }\n\n if (mType == TYPE_ALL) {\n final String location = mUri.toString();\n int dotIndex = location.lastIndexOf(\".\");\n if (dotIndex != -1) {\n String fileExt = location.substring(dotIndex).toLowerCase(Locale.ENGLISH);\n if( Extensions.VIDEO.contains(fileExt) ) {\n mType = TYPE_VIDEO;\n } else if (Extensions.AUDIO.contains(fileExt)) {\n mType = TYPE_AUDIO;\n } else if (Extensions.SUBTITLES.contains(fileExt)) {\n mType = TYPE_SUBTITLE;\n } else if (Extensions.PLAYLIST.contains(fileExt)) {\n mType = TYPE_PLAYLIST;\n }\n }\n }\n }\n\n private void init(long time, long length, int type,\n Bitmap picture, String title, String artist, String genre, String album, String albumArtist,\n int width, int height, String artworkURL, int audio, int spu, int trackNumber, int discNumber, long lastModified) {\n mFilename = null;\n mTime = time;\n mAudioTrack = audio;\n mSpuTrack = spu;\n mLength = length;\n mType = type;\n mPicture = picture;\n mWidth = width;\n mHeight = height;\n\n mTitle = title;\n mArtist = artist;\n mGenre = genre;\n mAlbum = album;\n mAlbumArtist = albumArtist;\n mArtworkURL = artworkURL;\n mTrackNumber = trackNumber;\n mDiscNumber = discNumber;\n mLastModified = lastModified;\n }\n\n public MediaWrapper(Uri uri, long time, long length, int type,\n Bitmap picture, String title, String artist, String genre, String album, String albumArtist,\n int width, int height, String artworkURL, int audio, int spu, int trackNumber, int discNumber, long lastModified) {\n mUri = uri;\n init(time, length, type, picture, title, artist, genre, album, albumArtist,\n width, height, artworkURL, audio, spu, trackNumber, discNumber, lastModified);\n }\n\n public String getLocation() {\n return mUri.toString();\n }\n\n public Uri getUri() {\n return mUri;\n }\n\n private static String getMetaId(Media media, int id, boolean trim) {\n String meta = media.getMeta(id);\n return meta != null ? trim ? meta.trim() : meta : null;\n }\n\n public void updateMeta(Media media) {\n mTitle = getMetaId(media, Meta.Title, true);\n mArtist = getMetaId(media, Meta.Artist, true);\n mAlbum = getMetaId(media, Meta.Album, true);\n mGenre = getMetaId(media, Meta.Genre, true);\n mAlbumArtist = getMetaId(media, Meta.AlbumArtist, true);\n mArtworkURL = getMetaId(media, Meta.ArtworkURL, false);\n mNowPlaying = getMetaId(media, Meta.NowPlaying, false);\n final String trackNumber = getMetaId(media, Meta.TrackNumber, false);\n if (!TextUtils.isEmpty(trackNumber)) {\n try {\n mTrackNumber = Integer.parseInt(trackNumber);\n } catch (NumberFormatException ignored) {}\n }\n final String discNumber = getMetaId(media, Meta.DiscNumber, false);\n if (!TextUtils.isEmpty(discNumber)) {\n try {\n mDiscNumber = Integer.parseInt(discNumber);\n } catch (NumberFormatException ignored) {}\n }\n\n mTitle = tryUnicodeToGBK(mTitle);\n mArtist = tryUnicodeToGBK(mArtist);\n mGenre = tryUnicodeToGBK(mGenre);\n mAlbum = tryUnicodeToGBK(mAlbum);\n\n Log.d(TAG, \"Title \" + mTitle);\n Log.d(TAG, \"Artist \" + mArtist);\n Log.d(TAG, \"Genre \" + mGenre);\n Log.d(TAG, \"Album \" + mAlbum);\n }\n\n /**\n * [email protected] add\n * 添加将内容转换为UTF-8格式\n */\n\n /**\n * 尝试将转换字符乱码\n * http://blog.csdn.net/kuangren_01/article/details/10552227\n * @param oldString\n * @return\n */\n private String tryUnicodeToGBK(String oldString) {\n if (oldString == null)\n return oldString;\n\n String newString;\n try {\n newString = new String(oldString.getBytes(\"iso-8859-1\"), \"gbk\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n newString = oldString;\n }\n\n if (newString.indexOf(\"?\") == -1){\n return newString;\n } else {\n return oldString;\n }\n\n }\n // add end\n\n public void updateMeta(MediaPlayer mediaPlayer) {\n final Media media = mediaPlayer.getMedia();\n if (media == null)\n return;\n updateMeta(media);\n media.release();\n }\n\n public String getFileName() {\n if (mFilename == null) {\n mFilename = mUri.getLastPathSegment();\n }\n return mFilename;\n }\n\n public long getTime() {\n return mTime;\n }\n\n public void setTime(long time) {\n mTime = time;\n }\n\n public int getAudioTrack() {\n return mAudioTrack;\n }\n\n public void setAudioTrack(int track) {\n mAudioTrack = track;\n }\n\n public int getSpuTrack() {\n return mSpuTrack;\n }\n\n public void setSpuTrack(int track) {\n mSpuTrack = track;\n }\n\n public long getLength() {\n return mLength;\n }\n\n public int getType() {\n return mType;\n }\n\n public void setType(int type){\n mType = type;\n }\n\n public int getWidth() {\n return mWidth;\n }\n\n public int getHeight() {\n return mHeight;\n }\n\n /**\n * Returns the raw picture object. Likely to be NULL in VLC for Android\n * due to lazy-loading.\n *\n * Use {@link org.videolan.vlc.util.BitmapUtil#getPictureFromCache(MediaWrapper)} instead.\n *\n * @return The raw picture or NULL\n */\n public Bitmap getPicture() {\n return mPicture;\n }\n\n /**\n * Sets the raw picture object.\n *\n * In VLC for Android, use {@link org.videolan.vlc.MediaDatabase#setPicture(MediaWrapper, Bitmap)} instead.\n *\n * @param p\n */\n public void setPicture(Bitmap p) {\n mPicture = p;\n }\n\n public boolean isPictureParsed() {\n return mIsPictureParsed;\n }\n\n public void setPictureParsed(boolean isParsed) {\n mIsPictureParsed = isParsed;\n }\n\n public void setTitle(String title){\n mTitle = title;\n }\n\n public String getTitle() {\n if (!TextUtils.isEmpty(mTitle))\n return mTitle;\n else {\n String fileName = getFileName();\n if (fileName == null)\n return \"\";\n int end = fileName.lastIndexOf(\".\");\n if (end <= 0)\n return fileName;\n return fileName.substring(0, end);\n }\n }\n\n public String getReferenceArtist() {\n return mAlbumArtist == null ? mArtist : mAlbumArtist;\n }\n\n public String getArtist() {\n return mArtist;\n }\n\n public Boolean isArtistUnknown() {\n return mArtist == null;\n }\n\n public String getGenre() {\n if (mGenre == null)\n return null;\n else if (mGenre.length() > 1)/* Make genres case insensitive via normalisation */\n return Character.toUpperCase(mGenre.charAt(0)) + mGenre.substring(1).toLowerCase(Locale.getDefault());\n else\n return mGenre;\n }\n\n public String getCopyright() {\n return mCopyright;\n }\n\n public String getAlbum() {\n return mAlbum;\n }\n\n public String getAlbumArtist() {\n return mAlbumArtist;\n }\n\n public Boolean isAlbumUnknown() {\n return mAlbum == null;\n }\n\n public int getTrackNumber() {\n return mTrackNumber;\n }\n\n public int getDiscNumber() {\n return mDiscNumber;\n }\n\n public void setDescription(String description){\n mDescription = description;\n }\n\n public String getDescription() {\n return mDescription;\n }\n\n public String getRating() {\n return mRating;\n }\n\n public String getDate() {\n return mDate;\n }\n\n public String getSettings() {\n return mSettings;\n }\n\n public String getNowPlaying() {\n return mNowPlaying;\n }\n\n public String getPublisher() {\n return mPublisher;\n }\n\n public String getEncodedBy() {\n return mEncodedBy;\n }\n\n public String getTrackID() {\n return mTrackID;\n }\n\n public String getArtworkURL() {\n return mArtworkURL;\n }\n\n public long getLastModified() {\n return mLastModified;\n }\n\n public void setLastModified(long mLastModified) {\n this.mLastModified = mLastModified;\n }\n\n public void addFlags(int flags) {\n mFlags |= flags;\n }\n public void setFlags(int flags) {\n mFlags = flags;\n }\n public int getFlags() {\n return mFlags;\n }\n public void removeFlags(int flags) {\n mFlags &= ~flags;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public MediaWrapper(Parcel in) {\n mUri = in.readParcelable(Uri.class.getClassLoader());\n init(in.readLong(),\n in.readLong(),\n in.readInt(),\n (Bitmap) in.readParcelable(Bitmap.class.getClassLoader()),\n in.readString(),\n in.readString(),\n in.readString(),\n in.readString(),\n in.readString(),\n in.readInt(),\n in.readInt(),\n in.readString(),\n in.readInt(),\n in.readInt(),\n in.readInt(),\n in.readInt(),\n in.readLong());\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeParcelable(mUri, flags);\n dest.writeLong(getTime());\n dest.writeLong(getLength());\n dest.writeInt(getType());\n dest.writeParcelable(getPicture(), flags);\n dest.writeString(getTitle());\n dest.writeString(getArtist());\n dest.writeString(getGenre());\n dest.writeString(getAlbum());\n dest.writeString(getAlbumArtist());\n dest.writeInt(getWidth());\n dest.writeInt(getHeight());\n dest.writeString(getArtworkURL());\n dest.writeInt(getAudioTrack());\n dest.writeInt(getSpuTrack());\n dest.writeInt(getTrackNumber());\n dest.writeInt(getDiscNumber());\n dest.writeLong(getLastModified());\n }\n\n public static final Parcelable.Creator<MediaWrapper> CREATOR = new Parcelable.Creator<MediaWrapper>() {\n public MediaWrapper createFromParcel(Parcel in) {\n return new MediaWrapper(in);\n }\n public MediaWrapper[] newArray(int size) {\n return new MediaWrapper[size];\n }\n };\n}", "public class MainActivity extends AudioPlayerContainerActivity implements OnItemClickListener, SearchSuggestionsAdapter.SuggestionDisplay, FilterQueryProvider {\n public final static String TAG = \"VLC/MainActivity\";\n\n private static final String PREF_FIRST_RUN = \"first_run\";\n\n private static final int ACTIVITY_RESULT_PREFERENCES = 1;\n private static final int ACTIVITY_SHOW_INFOLAYOUT = 2;\n private static final int ACTIVITY_SHOW_PROGRESSBAR = 3;\n private static final int ACTIVITY_HIDE_PROGRESSBAR = 4;\n private static final int ACTIVITY_SHOW_TEXTINFO = 5;\n\n MediaLibrary mMediaLibrary;//媒体库\n\n private SidebarAdapter mSidebarAdapter;\n private HackyDrawerLayout mDrawerLayout;\n private ListView mListView;\n private ActionBarDrawerToggle mDrawerToggle;\n\n private View mInfoLayout;\n private ProgressBar mInfoProgress;\n private TextView mInfoText;\n private String mCurrentFragment;\n\n\n private int mVersionNumber = -1;\n private boolean mFirstRun = false;\n\n private Handler mHandler = new MainActivityHandler(this);\n private int mFocusedPrior = 0;\n private int mActionBarIconId = -1;\n Menu mMenu;\n private SearchView mSearchView;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (!VLCInstance.testCompatibleCPU(this)) {\n finish();\n return;\n }\n /* Enable the indeterminate progress feature */\n supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);\n\n /* Get the current version from package */\n mVersionNumber = BuildConfig.VERSION_CODE;\n\n /* Check if it's the first run */\n mFirstRun = mSettings.getInt(PREF_FIRST_RUN, -1) != mVersionNumber;\n if (mFirstRun) {\n Editor editor = mSettings.edit();\n editor.putInt(PREF_FIRST_RUN, mVersionNumber);\n Util.commitPreferences(editor);\n }\n\n mMediaLibrary = MediaLibrary.getInstance();\n if (savedInstanceState == null) { // means first creation, savedInstanceState is not null after rotation\n /* Load media items from database and storage */\n /* 媒体库加载 */\n mMediaLibrary.loadMediaItems();\n }\n\n /*** Start initializing the UI ***/\n\n setContentView(R.layout.main);\n\n mDrawerLayout = (HackyDrawerLayout) findViewById(R.id.root_container);\n mListView = (ListView)findViewById(R.id.sidelist);\n mListView.setFooterDividersEnabled(true);\n mSidebarAdapter = new SidebarAdapter(this);\n mListView.setAdapter(mSidebarAdapter);\n\n initAudioPlayerContainerActivity();\n\n if (savedInstanceState != null){\n mCurrentFragment = savedInstanceState.getString(\"current\");\n if (mCurrentFragment != null)\n mSidebarAdapter.setCurrentFragment(mCurrentFragment);\n }\n\n\n /* Initialize UI variables */\n mInfoLayout = findViewById(R.id.info_layout);\n mInfoProgress = (ProgressBar) findViewById(R.id.info_progress);\n mInfoText = (TextView) findViewById(R.id.info_text);\n\n /* Set up the action bar */\n prepareActionBar();\n\n /* Set up the sidebar click listener\n * no need to invalidate menu for now */\n mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close){\n @Override\n public void onDrawerClosed(View drawerView) {\n super.onDrawerClosed(drawerView);\n if (getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder) instanceof MediaBrowserFragment)\n ((MediaBrowserFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder)).setReadyToDisplay(true);\n }\n };\n\n // Set the drawer toggle as the DrawerListener\n mDrawerLayout.setDrawerListener(mDrawerToggle);\n // set a custom shadow that overlays the main content when the drawer opens\n mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);\n\n mListView.setOnItemClickListener(this);\n\n if (mFirstRun) {\n /*\n * The sliding menu is automatically opened when the user closes\n * the info dialog. If (for any reason) the dialog is not shown,\n * open the menu after a short delay.\n */\n mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n mDrawerLayout.openDrawer(mListView);\n }\n }, 500);\n }\n\n /* Reload the latest preferences */\n reloadPreferences();\n }\n\n @Override\n protected void onPostCreate(Bundle savedInstanceState) {\n super.onPostCreate(savedInstanceState);\n // Sync the toggle state after onRestoreInstanceState has occurred.\n mDrawerToggle.syncState();\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void prepareActionBar() {\n mActionBar.setDisplayHomeAsUpEnabled(true);\n mActionBar.setHomeButtonEnabled(true);\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n\n /* FIXME: this is used to avoid having MainActivity twice in the backstack */\n if (getIntent() != null && getIntent().hasExtra(PlaybackService.START_FROM_NOTIFICATION))\n getIntent().removeExtra(PlaybackService.START_FROM_NOTIFICATION);\n\n if (mSlidingPane.getState() == mSlidingPane.STATE_CLOSED)\n mActionBar.hide();\n }\n\n @Override\n protected void onResumeFragments() {\n super.onResumeFragments();\n\n // Figure out if currently-loaded fragment is a top-level fragment.\n Fragment current = getSupportFragmentManager()\n .findFragmentById(R.id.fragment_placeholder);\n boolean found = (current == null) || SidebarAdapter.sidebarFragments.contains(current.getTag());\n\n /**\n * Restore the last view.\n *\n * Replace:\n * - null fragments (freshly opened Activity)\n * - Wrong fragment open AND currently displayed fragment is a top-level fragment\n *\n * Do not replace:\n * - Non-sidebar fragments.\n * It will try to remove() the currently displayed fragment\n * (i.e. tracks) and replace it with a blank screen. (stuck menu bug)\n */\n if (current == null || (!current.getTag().equals(mCurrentFragment) && found)) {\n Log.d(TAG, \"Reloading displayed fragment\");\n if (mCurrentFragment == null)\n mCurrentFragment = \"video\";\n if (!SidebarAdapter.sidebarFragments.contains(mCurrentFragment)) {\n Log.d(TAG, \"Unknown fragment \\\"\" + mCurrentFragment + \"\\\", resetting to video\");\n mCurrentFragment = \"video\";\n }\n Fragment ff = getFragment(mCurrentFragment);\n FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n ft.replace(R.id.fragment_placeholder, ff, mCurrentFragment);\n ft.commit();\n }\n }\n\n /**\n * Stop audio player and save opened tab\n */\n @Override\n protected void onPause() {\n super.onPause();\n /* Stop scanning for files */\n mMediaLibrary.stop();\n /* Save the tab status in pref */\n SharedPreferences.Editor editor = mSettings.edit();\n editor.putString(\"fragment\", mCurrentFragment);\n Util.commitPreferences(editor);\n\n mFocusedPrior = 0;\n }\n\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putString(\"current\", mCurrentFragment);\n }\n\n @Override\n protected void onRestart() {\n super.onRestart();\n /* Reload the latest preferences */\n reloadPreferences();\n }\n\n @Override\n public void onBackPressed() {\n /* Close the menu first */\n if(mDrawerLayout.isDrawerOpen(mListView)) {\n if (mFocusedPrior != 0)\n requestFocusOnSearch();\n mDrawerLayout.closeDrawer(mListView);\n return;\n }\n\n // Slide down the audio player if it is shown entirely.\n if (slideDownAudioPlayer())\n return;\n\n if (mCurrentFragment!= null) {\n // If it's the directory view, a \"backpressed\" action shows a parent.\n if (mCurrentFragment.equals(SidebarEntry.ID_NETWORK) || mCurrentFragment.equals(SidebarEntry.ID_DIRECTORIES)){\n BaseBrowserFragment browserFragment = (BaseBrowserFragment) getSupportFragmentManager()\n .findFragmentById(R.id.fragment_placeholder);\n if (browserFragment != null) {\n browserFragment.goBack();\n return;\n }\n }\n }\n finish();\n }\n\n private Fragment getFragment(String id)\n {\n Fragment frag = getSupportFragmentManager().findFragmentByTag(id);\n if (frag != null)\n return frag;\n return mSidebarAdapter.fetchFragment(id);\n }\n\n private static void ShowFragment(FragmentActivity activity, String tag, Fragment fragment, String previous) {\n if (fragment == null) {\n Log.e(TAG, \"Cannot show a null fragment, ShowFragment(\"+tag+\") aborted.\");\n return;\n }\n\n FragmentManager fm = activity.getSupportFragmentManager();\n\n //abort if fragment is already the current one\n Fragment current = fm.findFragmentById(R.id.fragment_placeholder);\n if(current != null && current.getTag().equals(tag))\n return;\n\n //try to pop back if the fragment is already on the backstack\n if (fm.popBackStackImmediate(tag, 0))\n return;\n\n //fragment is not there yet, spawn a new one\n FragmentTransaction ft = fm.beginTransaction();\n ft.setCustomAnimations(R.anim.anim_enter_right, R.anim.anim_leave_left, R.anim.anim_enter_left, R.anim.anim_leave_right);\n ft.replace(R.id.fragment_placeholder, fragment, tag);\n ft.addToBackStack(previous);\n ft.commit();\n }\n\n /**\n * Show a secondary fragment.\n */\n public void showSecondaryFragment(String fragmentTag) {\n showSecondaryFragment(fragmentTag, null);\n }\n\n public void showSecondaryFragment(String fragmentTag, String param) {\n Intent i = new Intent(this, SecondaryActivity.class);\n i.putExtra(\"fragment\", fragmentTag);\n if (param != null)\n i.putExtra(\"param\", param);\n startActivity(i);\n // Slide down the audio player if needed.\n slideDownAudioPlayer();\n }\n\n /** Create menu from XML\n */\n @TargetApi(Build.VERSION_CODES.FROYO)\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n mMenu = menu;\n /* Note: on Android 3.0+ with an action bar this method\n * is called while the view is created. This can happen\n * any time after onCreate.\n */\n MenuInflater inflater = getMenuInflater();\n inflater.inflate(R.menu.media_library, menu);\n\n if (AndroidUtil.isFroyoOrLater()) {\n SearchManager searchManager =\n (SearchManager) VLCApplication.getAppContext().getSystemService(Context.SEARCH_SERVICE);\n mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.ml_menu_search));\n mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));\n mSearchView.setQueryHint(getString(R.string.search_hint));\n SearchSuggestionsAdapter searchSuggestionsAdapter = new SearchSuggestionsAdapter(this, null);\n searchSuggestionsAdapter.setFilterQueryProvider(this);\n mSearchView.setSuggestionsAdapter(searchSuggestionsAdapter);\n } else\n menu.findItem(R.id.ml_menu_search).setVisible(false);\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override\n public boolean onPrepareOptionsMenu (Menu menu) {\n super.onPrepareOptionsMenu(menu);\n if (menu == null)\n return false;\n Fragment current = getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder);\n MenuItem item;\n // Disable the sort option if we can't use it on the current fragment.\n if (current == null || !(current instanceof ISortable)) {\n item = menu.findItem(R.id.ml_menu_sortby);\n if (item == null)\n return false;\n item.setEnabled(false);\n item.setVisible(false);\n } else {\n ISortable sortable = (ISortable) current;\n item = menu.findItem(R.id.ml_menu_sortby);\n if (item == null)\n return false;\n item.setEnabled(true);\n item.setVisible(true);\n item = menu.findItem(R.id.ml_menu_sortby_name);\n if (sortable.sortDirection(VideoListAdapter.SORT_BY_TITLE) == 1)\n item.setTitle(R.string.sortby_name_desc);\n else\n item.setTitle(R.string.sortby_name);\n item = menu.findItem(R.id.ml_menu_sortby_length);\n if (sortable.sortDirection(VideoListAdapter.SORT_BY_LENGTH) == 1)\n item.setTitle(R.string.sortby_length_desc);\n else\n item.setTitle(R.string.sortby_length);\n item = menu.findItem(R.id.ml_menu_sortby_date);\n if (sortable.sortDirection(VideoListAdapter.SORT_BY_DATE) == 1)\n item.setTitle(R.string.sortby_date_desc);\n else\n item.setTitle(R.string.sortby_date);\n }\n\n boolean networkSave = current instanceof NetworkBrowserFragment && !((NetworkBrowserFragment)current).isRootDirectory();\n if (networkSave) {\n item = menu.findItem(R.id.ml_menu_save);\n item.setVisible(true);\n String mrl = ((BaseBrowserFragment)current).mMrl;\n item.setIcon(MediaDatabase.getInstance().networkFavExists(Uri.parse(mrl)) ?\n R.drawable.ic_menu_bookmark_w :\n R.drawable.ic_menu_bookmark_outline_w);\n } else\n menu.findItem(R.id.ml_menu_save).setVisible(false);\n if (current instanceof MRLPanelFragment)\n menu.findItem(R.id.ml_menu_clean).setVisible(!((MRLPanelFragment) current).isEmpty());\n boolean showLast = current instanceof AudioBrowserFragment || (current instanceof VideoGridFragment && mSettings.getString(PreferencesActivity.VIDEO_LAST, null) != null);\n menu.findItem(R.id.ml_menu_last_playlist).setVisible(showLast);\n return true;\n }\n\n /**\n * Handle onClick form menu buttons\n */\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n\n // Current fragment loaded\n Fragment current = getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder);\n\n // Handle item selection\n switch (item.getItemId()) {\n case R.id.ml_menu_sortby_name:\n case R.id.ml_menu_sortby_length:\n case R.id.ml_menu_sortby_date:\n if (current == null)\n break;\n if (current instanceof ISortable) {\n int sortBy = VideoListAdapter.SORT_BY_TITLE;\n if (item.getItemId() == R.id.ml_menu_sortby_length)\n sortBy = VideoListAdapter.SORT_BY_LENGTH;\n else if(item.getItemId() == R.id.ml_menu_sortby_date)\n sortBy = VideoListAdapter.SORT_BY_DATE;\n ((ISortable) current).sortBy(sortBy);\n supportInvalidateOptionsMenu();\n }\n break;\n case R.id.ml_menu_equalizer:\n showSecondaryFragment(SecondaryActivity.EQUALIZER);\n break;\n // Refresh\n case R.id.ml_menu_refresh:\n if (!mMediaLibrary.isWorking()) {\n if(current != null && current instanceof IRefreshable)\n ((IRefreshable) current).refresh();\n else\n mMediaLibrary.loadMediaItems(true);\n }\n break;\n // Restore last playlist\n case R.id.ml_menu_last_playlist:\n if (current instanceof AudioBrowserFragment) {\n Intent i = new Intent(PlaybackService.ACTION_REMOTE_LAST_PLAYLIST);\n sendBroadcast(i);\n } else if (current instanceof VideoGridFragment) {\n final Uri uri = Uri.parse(mSettings.getString(PreferencesActivity.VIDEO_LAST, null));\n if (uri != null)\n VideoPlayerActivity.start(this, uri);\n }\n break;\n case android.R.id.home:\n // Slide down the audio player.\n if (slideDownAudioPlayer())\n break;\n /* Toggle the sidebar */\n if (mDrawerToggle.onOptionsItemSelected(item)) {\n return true;\n }\n break;\n case R.id.ml_menu_clean:\n if (getFragment(mCurrentFragment) instanceof MRLPanelFragment)\n ((MRLPanelFragment)getFragment(mCurrentFragment)).clearHistory();\n break;\n case R.id.ml_menu_save:\n if (current == null)\n break;\n ((NetworkBrowserFragment)current).toggleFavorite();\n item.setIcon(R.drawable.ic_menu_bookmark_w);\n break;\n }\n mDrawerLayout.closeDrawer(mListView);\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == ACTIVITY_RESULT_PREFERENCES) {\n if (resultCode == PreferencesActivity.RESULT_RESCAN)\n mMediaLibrary.loadMediaItems(true);\n else if (resultCode == PreferencesActivity.RESULT_RESTART) {\n Intent intent = getIntent();\n finish();\n startActivity(intent);\n }\n }\n }\n\n public void setMenuFocusDown(boolean idIsEmpty, int id) {\n if (mMenu == null)\n return;\n //Save menu items ids for focus control\n final int[] menu_controls = new int[mMenu.size()+1];\n for (int i = 0 ; i < mMenu.size() ; i++){\n menu_controls[i] = mMenu.getItem(i).getItemId();\n }\n menu_controls[mMenu.size()] = mActionBarIconId;\n /*menu_controls = new int[]{R.id.ml_menu_search,\n R.id.ml_menu_open_mrl, R.id.ml_menu_sortby,\n R.id.ml_menu_last_playlist, R.id.ml_menu_refresh,\n mActionBarIconId};*/\n int pane = mSlidingPane.getState();\n for(int r : menu_controls) {\n View v = findViewById(r);\n if (v != null) {\n if (!idIsEmpty)\n v.setNextFocusDownId(id);\n else {\n if (pane == mSlidingPane.STATE_CLOSED) {\n v.setNextFocusDownId(R.id.play_pause);\n } else if (pane == mSlidingPane.STATE_OPENED) {\n v.setNextFocusDownId(R.id.header_play_pause);\n } else if (pane ==\n mSlidingPane.STATE_OPENED_ENTIRELY) {\n v.setNextFocusDownId(r);\n }\n }\n }\n }\n }\n\n public void setSearchAsFocusDown(boolean idIsEmpty, View parentView, int id) {\n View playPause = findViewById(R.id.header_play_pause);\n\n if (!idIsEmpty) {\n View list;\n int pane = mSlidingPane.getState();\n\n if (parentView == null)\n list = findViewById(id);\n else\n list = parentView.findViewById(id);\n\n if (list != null) {\n if (pane == mSlidingPane.STATE_OPENED_ENTIRELY) {\n list.setNextFocusDownId(id);\n } else if (pane == mSlidingPane.STATE_OPENED) {\n list.setNextFocusDownId(R.id.header_play_pause);\n playPause.setNextFocusUpId(id);\n }\n }\n } else {\n playPause.setNextFocusUpId(R.id.ml_menu_search);\n }\n }\n\n // Note. onKeyDown will not occur while moving within a list\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n //Filter for LG devices, see https://code.google.com/p/android/issues/detail?id=78154\n if ((keyCode == KeyEvent.KEYCODE_MENU) &&\n (Build.VERSION.SDK_INT <= 16) &&\n (Build.MANUFACTURER.compareTo(\"LGE\") == 0)) {\n return true;\n }\n if (mFocusedPrior == 0)\n setMenuFocusDown(true, 0);\n if (getCurrentFocus() != null)\n mFocusedPrior = getCurrentFocus().getId();\n return super.onKeyDown(keyCode, event);\n }\n\n // Note. onKeyDown will not occur while moving within a list\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n @Override\n public boolean onKeyUp(int keyCode, KeyEvent event) {\n //Filter for LG devices, see https://code.google.com/p/android/issues/detail?id=78154\n if ((keyCode == KeyEvent.KEYCODE_MENU) &&\n (Build.VERSION.SDK_INT <= 16) &&\n (Build.MANUFACTURER.compareTo(\"LGE\") == 0)) {\n openOptionsMenu();\n return true;\n }\n View v = getCurrentFocus();\n if (v == null)\n return super.onKeyUp(keyCode, event);\n if ((mActionBarIconId == -1) &&\n (v.getId() == -1) &&\n (v.getNextFocusDownId() == -1) &&\n (v.getNextFocusUpId() == -1) &&\n (v.getNextFocusLeftId() == -1) &&\n (v.getNextFocusRightId() == -1)) {\n mActionBarIconId = Util.generateViewId();\n v.setId(mActionBarIconId);\n v.setNextFocusUpId(mActionBarIconId);\n v.setNextFocusDownId(mActionBarIconId);\n v.setNextFocusLeftId(mActionBarIconId);\n v.setNextFocusRightId(R.id.ml_menu_search);\n if (AndroidUtil.isHoneycombOrLater())\n v.setNextFocusForwardId(mActionBarIconId);\n if (findViewById(R.id.ml_menu_search) != null)\n findViewById(R.id.ml_menu_search).setNextFocusLeftId(mActionBarIconId);\n }\n return super.onKeyUp(keyCode, event);\n }\n\n private void reloadPreferences() {\n mCurrentFragment = mSettings.getString(\"fragment\", \"video\");\n }\n\n @Override\n public Cursor runQuery(CharSequence constraint) {\n return MediaDatabase.getInstance().queryMedia(constraint.toString());\n }\n\n private static class MainActivityHandler extends WeakHandler<MainActivity> {\n public MainActivityHandler(MainActivity owner) {\n super(owner);\n }\n\n @Override\n public void handleMessage(Message msg) {\n MainActivity ma = getOwner();\n if(ma == null) return;\n\n switch (msg.what) {\n case ACTIVITY_SHOW_INFOLAYOUT:\n ma.mInfoLayout.setVisibility(View.VISIBLE);\n break;\n case ACTIVITY_SHOW_PROGRESSBAR:\n ma.setSupportProgressBarIndeterminateVisibility(true);\n ma.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n break;\n case ACTIVITY_HIDE_PROGRESSBAR:\n ma.setSupportProgressBarIndeterminateVisibility(false);\n ma.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n break;\n case ACTIVITY_SHOW_TEXTINFO:\n String info = (String) msg.obj;\n int max = msg.arg1;\n int progress = msg.arg2;\n ma.mInfoText.setText(info);\n ma.mInfoProgress.setMax(max);\n ma.mInfoProgress.setProgress(progress);\n\n if (info == null) {\n /* Cancel any upcoming visibility change */\n removeMessages(ACTIVITY_SHOW_INFOLAYOUT);\n ma.mInfoLayout.setVisibility(View.GONE);\n }\n else {\n /* Slightly delay the appearance of the progress bar to avoid unnecessary flickering */\n if (!hasMessages(ACTIVITY_SHOW_INFOLAYOUT)) {\n Message m = new Message();\n m.what = ACTIVITY_SHOW_INFOLAYOUT;\n sendMessageDelayed(m, 300);\n }\n }\n break;\n }\n }\n }\n\n public void hideKeyboard(){\n ((InputMethodManager) VLCApplication.getAppContext().getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(\n getWindow().getDecorView().getRootView().getWindowToken(), 0);\n }\n\n public void showProgressBar() {\n mHandler.obtainMessage(ACTIVITY_SHOW_PROGRESSBAR).sendToTarget();\n }\n\n public void hideProgressBar() {\n mHandler.obtainMessage(ACTIVITY_HIDE_PROGRESSBAR).sendToTarget();\n }\n\n public void sendTextInfo(String info, int progress, int max) {\n mHandler.obtainMessage(ACTIVITY_SHOW_TEXTINFO, max, progress, info).sendToTarget();\n }\n\n public void clearTextInfo() {\n mHandler.obtainMessage(ACTIVITY_SHOW_TEXTINFO, 0, 100, null).sendToTarget();\n }\n\n protected void onPanelClosedUiSet() {\n mDrawerLayout.setDrawerLockMode(HackyDrawerLayout.LOCK_MODE_LOCKED_CLOSED);\n }\n\n protected void onPanelOpenedEntirelyUiSet() {\n mDrawerLayout.setDrawerLockMode(HackyDrawerLayout.LOCK_MODE_UNLOCKED);\n }\n\n protected void onPanelOpenedUiSet() {\n mDrawerLayout.setDrawerLockMode(HackyDrawerLayout.LOCK_MODE_UNLOCKED);\n removeTipViewIfDisplayed();\n }\n\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n SidebarAdapter.SidebarEntry entry = (SidebarEntry) mListView.getItemAtPosition(position);\n Fragment current = getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder);\n\n if(current == null || (entry != null && current.getTag().equals(entry.id))) { /* Already selected */\n if (mFocusedPrior != 0)\n requestFocusOnSearch();\n mDrawerLayout.closeDrawer(mListView);\n return;\n }\n\n // This should not happen\n if(entry == null || entry.id == null)\n return;\n\n if (entry.type == SidebarEntry.TYPE_FRAGMENT) {\n\n /* Slide down the audio player */\n slideDownAudioPlayer();\n\n /* Switch the fragment */\n Fragment fragment = getFragment(entry.id);\n if (fragment instanceof MediaBrowserFragment)\n ((MediaBrowserFragment)fragment).setReadyToDisplay(false);\n FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n ft.replace(R.id.fragment_placeholder, fragment, entry.id);\n ft.addToBackStack(mCurrentFragment);\n ft.commit();\n mCurrentFragment = entry.id;\n mSidebarAdapter.setCurrentFragment(mCurrentFragment);\n\n if (mFocusedPrior != 0)\n requestFocusOnSearch();\n } else if (entry.type == SidebarEntry.TYPE_SECONDARY_FRAGMENT)\n showSecondaryFragment(SecondaryActivity.ABOUT);\n else if (entry.attributeID == R.attr.ic_menu_preferences)\n startActivityForResult(new Intent(this, PreferencesActivity.class), ACTIVITY_RESULT_PREFERENCES);\n mDrawerLayout.closeDrawer(mListView);\n }\n\n private void requestFocusOnSearch() {\n View search = findViewById(R.id.ml_menu_search);\n if (search != null)\n search.requestFocus();\n }\n}", "public abstract class MediaBrowserFragment extends PlaybackServiceFragment {\n\n protected SwipeRefreshLayout mSwipeRefreshLayout;\n protected volatile boolean mReadyToDisplay = true;\n\n public void setReadyToDisplay(boolean ready) {\n if (ready && !mReadyToDisplay)\n display();\n else\n mReadyToDisplay = ready;\n }\n\n protected abstract void display();\n\n protected abstract String getTitle();\n public abstract void clear();\n public void onStart(){\n super.onStart();\n final AppCompatActivity activity = (AppCompatActivity)getActivity();\n if (activity != null && activity.getSupportActionBar() != null) {\n activity.getSupportActionBar().setTitle(getTitle());\n getActivity().supportInvalidateOptionsMenu();\n }\n }\n}" ]
import android.annotation.TargetApi; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentActivity; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.TextView; import org.videolan.libvlc.Media; import org.videolan.libvlc.util.AndroidUtil; import org.videolan.vlc.MediaDatabase; import org.videolan.vlc.MediaGroup; import org.videolan.vlc.MediaLibrary; import org.videolan.vlc.MediaWrapper; import org.videolan.vlc.R; import org.videolan.vlc.Thumbnailer; import org.videolan.vlc.VLCApplication; import org.videolan.vlc.gui.MainActivity; import org.videolan.vlc.gui.SecondaryActivity; import org.videolan.vlc.gui.browser.MediaBrowserFragment; import org.videolan.vlc.interfaces.ISortable; import org.videolan.vlc.interfaces.IVideoBrowser; import org.videolan.vlc.util.AndroidDevices; import org.videolan.vlc.util.Util; import org.videolan.vlc.util.VLCInstance; import org.videolan.vlc.util.WeakHandler; import org.videolan.vlc.widget.SwipeRefreshLayout; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier;
/***************************************************************************** * VideoListActivity.java ***************************************************************************** * Copyright © 2011-2012 VLC authors and VideoLAN * * 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. *****************************************************************************/ package org.videolan.vlc.gui.video; public class VideoGridFragment extends MediaBrowserFragment implements ISortable, IVideoBrowser, SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener { public final static String TAG = "VLC/VideoListFragment"; public final static String KEY_GROUP = "key_group"; private static final int DELETE_MEDIA = 0; private static final int DELETE_DURATION = 3000; protected static final String ACTION_SCAN_START = "org.videolan.vlc.gui.ScanStart"; protected static final String ACTION_SCAN_STOP = "org.videolan.vlc.gui.ScanStop"; protected static final int UPDATE_ITEM = 0; /* Constants used to switch from Grid to List and vice versa */ //FIXME If you know a way to do this in pure XML please do it! private static final int GRID_STRETCH_MODE = GridView.STRETCH_COLUMN_WIDTH; private static final int LIST_STRETCH_MODE = GridView.STRETCH_COLUMN_WIDTH; protected LinearLayout mLayoutFlipperLoading; protected GridView mGridView; protected TextView mTextViewNomedia; protected View mViewNomedia; protected MediaWrapper mItemToUpdate; protected String mGroup; protected final CyclicBarrier mBarrier = new CyclicBarrier(2); private VideoListAdapter mVideoAdapter; private MediaLibrary mMediaLibrary; private Thumbnailer mThumbnailer; private VideoGridAnimator mAnimator;
private MainActivity mMainActivity;
3
abstractj/kalium
src/main/java/org/abstractj/kalium/crypto/Box.java
[ "public class NaCl {\n\n public static Sodium sodium() {\n Sodium sodium = SingletonHolder.SODIUM_INSTANCE;\n checkVersion(sodium);\n return sodium;\n }\n\n private static final String LIBRARY_NAME = libraryName();\n\n private static String libraryName() {\n switch (Platform.getNativePlatform().getOS()) {\n case WINDOWS:\n return \"libsodium\";\n default:\n return \"sodium\";\n }\n }\n\n private static final class SingletonHolder {\n public static final Sodium SODIUM_INSTANCE =\n LibraryLoader.create(Sodium.class)\n .search(\"/usr/local/lib\")\n .search(\"/opt/local/lib\")\n .search(\"lib\")\n .load(LIBRARY_NAME);\n\n }\n\n public static final Integer[] MIN_SUPPORTED_VERSION =\n new Integer[] { 1, 0, 3 };\n\n private static boolean versionSupported = false;\n\n private static final void checkVersion(Sodium lib) {\n if (!versionSupported) {\n String[] version = lib.sodium_version_string().split(\"\\\\.\");\n versionSupported = version.length >= 3 &&\n MIN_SUPPORTED_VERSION[0] <= new Integer(version[0]) &&\n MIN_SUPPORTED_VERSION[1] <= new Integer(version[1]) &&\n MIN_SUPPORTED_VERSION[2] <= new Integer(version[2]);\n }\n if (!versionSupported) {\n String message = String.format(\"Unsupported libsodium version: %s. Please update\",\n lib.sodium_version_string());\n throw new UnsupportedOperationException(message);\n }\n }\n\n private NaCl() {\n }\n\n public interface Sodium {\n\n /**\n * This function isn't thread safe. Be sure to call it once, and before\n * performing other operations.\n *\n * Check libsodium's documentation for more info.\n */\n int sodium_init();\n\n String sodium_version_string();\n\n // ---------------------------------------------------------------------\n // Generating Random Data\n\n void randombytes(@Out byte[] buffer, @In @u_int64_t int size);\n\n // ---------------------------------------------------------------------\n // Secret-key cryptography: Authenticated encryption\n\n /**\n * @deprecated use CRYPTO_SECRETBOX_XSALSA20POLY1305_KEYBYTES\n */\n @Deprecated\n int XSALSA20_POLY1305_SECRETBOX_KEYBYTES = 32;\n\n /**\n * @deprecated use CRYPTO_SECRETBOX_XSALSA20POLY1305_NONCEBYTES\n */\n @Deprecated\n int XSALSA20_POLY1305_SECRETBOX_NONCEBYTES = 24;\n\n int CRYPTO_SECRETBOX_XSALSA20POLY1305_KEYBYTES = 32;\n\n int CRYPTO_SECRETBOX_XSALSA20POLY1305_NONCEBYTES = 24;\n\n int crypto_secretbox_xsalsa20poly1305(\n @Out byte[] ct, @In byte[] msg, @In @u_int64_t int length,\n @In byte[] nonce, @In byte[] key);\n\n int crypto_secretbox_xsalsa20poly1305_open(\n @Out byte[] message, @In byte[] ct, @In @u_int64_t int length,\n @In byte[] nonce, @In byte[] key);\n\n // ---------------------------------------------------------------------\n // Secret-key cryptography: Authentication\n\n /**\n * @deprecated use CRYPTO_AUTH_HMACSHA512256_BYTESS\n */\n @Deprecated\n int HMACSHA512256_BYTES = 32;\n\n /**\n * @deprecated use CRYPTO_AUTH_HMACSHA512256_KEYBYTESS\n */\n @Deprecated\n int HMACSHA512256_KEYBYTES = 32;\n\n int CRYPTO_AUTH_HMACSHA512256_BYTES = 32;\n\n int CRYPTO_AUTH_HMACSHA512256_KEYBYTES = 32;\n\n int crypto_auth_hmacsha512256(\n @Out byte[] mac, @In byte[] message, @In @u_int64_t int sizeof,\n @In byte[] key);\n\n int crypto_auth_hmacsha512256_verify(\n @In byte[] mac, @In byte[] message, @In @u_int64_t int sizeof,\n @In byte[] key);\n\n // ---------------------------------------------------------------------\n // Secret-key cryptography: AEAD\n\n int CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = 32;\n\n int CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = 8;\n\n int CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = 16;\n\n int crypto_aead_chacha20poly1305_encrypt(\n @Out byte[] ct, @Out LongLongByReference ctLength,\n @In byte[] message, @In @u_int64_t int messageLength,\n @In byte[] additionalData, @In @u_int64_t int adLength,\n @In byte[] nsec, @In byte[] npub, @In byte[] key);\n\n int crypto_aead_chacha20poly1305_decrypt(\n @Out byte[] message, @Out LongLongByReference messageLength,\n @In byte[] nsec, @In byte[] ct, @In @u_int64_t int ctLength,\n @In byte[] additionalData, @In @u_int64_t int adLength,\n @In byte[] npub, @In byte[] key);\n\n // ---------------------------------------------------------------------\n // Public-key cryptography: Authenticated encryption\n\n /**\n * @deprecated use CRYPTO_BOX_CURVE25519XSALSA20POLY1305_PUBLICKEYBYTES\n */\n @Deprecated\n int PUBLICKEY_BYTES = 32;\n\n /**\n * @deprecated use CRYPTO_BOX_CURVE25519XSALSA20POLY1305_SECRETKEYBYTESS\n */\n @Deprecated\n int SECRETKEY_BYTES = 32;\n\n /**\n * @deprecated use CRYPTO_BOX_CURVE25519XSALSA20POLY1305_NONCEBYTES\n */\n @Deprecated\n int NONCE_BYTES = 24;\n\n /**\n * @deprecated use CRYPTO_BOX_CURVE25519XSALSA20POLY1305_ZEROBYTESS\n */\n @Deprecated\n int ZERO_BYTES = 32;\n\n /**\n * @deprecated use CRYPTO_BOX_CURVE25519XSALSA20POLY1305_BOXZEROBYTES\n */\n @Deprecated\n int BOXZERO_BYTES = 16;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_PUBLICKEYBYTES = 32;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_SECRETKEYBYTES = 32;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_ZEROBYTES = 32;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_BOXZEROBYTES = 16;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_MACBYTES =\n CRYPTO_BOX_CURVE25519XSALSA20POLY1305_ZEROBYTES -\n CRYPTO_BOX_CURVE25519XSALSA20POLY1305_BOXZEROBYTES;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_NONCEBYTES = 24;\n\n int CRYPTO_BOX_CURVE25519XSALSA20POLY1305_BEFORENMBYTES = 32;\n\n int crypto_scalarmult_base(\n @Out byte[] publicKey, @In byte[] secretKey);\n\n int crypto_box_curve25519xsalsa20poly1305_keypair(\n @Out byte[] publicKey, @Out byte[] secretKey);\n\n int crypto_box_curve25519xsalsa20poly1305_beforenm(\n @Out byte[] sharedkey, @In byte[] publicKey,\n @In byte[] privateKey);\n\n int crypto_box_curve25519xsalsa20poly1305(\n @Out byte[] ct, @In byte[] msg, @In @u_int64_t int length,\n @In byte[] nonce, @In byte[] publicKey, @In byte[] privateKey);\n\n int crypto_box_curve25519xsalsa20poly1305_afternm(\n @Out byte[] ct, @In byte[] msg, @In @u_int64_t int length,\n @In byte[] nonce, @In byte[] shared);\n\n int crypto_box_curve25519xsalsa20poly1305_open(\n @Out byte[] message, @In byte[] ct, @In @u_int64_t int length,\n @In byte[] nonce, @In byte[] publicKey, @In byte[] privateKey);\n\n int crypto_box_curve25519xsalsa20poly1305_open_afternm(\n @Out byte[] message, @In byte[] ct, @In @u_int64_t int length,\n @In byte[] nonce, @In byte[] shared);\n\n // ---------------------------------------------------------------------\n // Public-key cryptography: Public-key signatures\n\n /**\n * @deprecated use the documented CRYPTO_SIGN_ED25519_BYTES.\n */\n @Deprecated\n int SIGNATURE_BYTES = 64;\n\n int CRYPTO_SIGN_ED25519_PUBLICKEYBYTES = 32;\n\n int CRYPTO_SIGN_ED25519_SECRETKEYBYTES = 64;\n\n int CRYPTO_SIGN_ED25519_BYTES = 64;\n\n int crypto_sign_ed25519_seed_keypair(\n @Out byte[] publicKey, @Out byte[] secretKey, @In byte[] seed);\n\n int crypto_sign_ed25519(\n @Out byte[] buffer, @Out LongLongByReference bufferLen,\n @In byte[] message, @In @u_int64_t int length,\n @In byte[] secretKey);\n\n int crypto_sign_ed25519_open(\n @Out byte[] buffer, @Out LongLongByReference bufferLen,\n @In byte[] sigAndMsg, @In @u_int64_t int length,\n @In byte[] key);\n\n int crypto_sign_ed25519_detached(@Out byte[] sig, @Out LongLongByReference sigLen,\n @In byte[] message, @In @u_int64_t int length,\n @In byte[] secretKey);\n\n int crypto_sign_ed25519_verify_detached(@In byte[] sig,\n @In byte[] message, @In @u_int64_t int length,\n @In byte[] key);\n\n // ---------------------------------------------------------------------\n // Public-key cryptography: Sealed boxes\n\n int CRYPTO_BOX_SEALBYTES =\n CRYPTO_BOX_CURVE25519XSALSA20POLY1305_PUBLICKEYBYTES +\n CRYPTO_BOX_CURVE25519XSALSA20POLY1305_MACBYTES;\n\n int crypto_box_seal(\n @Out byte[] ct, @In byte[] message, @In @u_int64_t int length,\n @In byte[] publicKey);\n\n int crypto_box_seal_open(\n @Out byte[] message, @In byte[] c, @In @u_int64_t int length,\n @In byte[] publicKey, @In byte[] privateKey);\n\n // ---------------------------------------------------------------------\n // Hashing: Generic hashing\n\n /**\n * @deprecated use CRYPTO_GENERICHASH_BLAKE2B_BYTES_MAX. Note that\n * the Libsodium standard value is '32' and not '64' as defined here.\n */\n @Deprecated\n int BLAKE2B_OUTBYTES = 64;\n\n int CRYPTO_GENERICHASH_BLAKE2B_BYTES = 32;\n\n int CRYPTO_GENERICHASH_BLAKE2B_BYTES_MIN = 16;\n\n int CRYPTO_GENERICHASH_BLAKE2B_BYTES_MAX = 64;\n\n int CRYPTO_GENERICHASH_BLAKE2B_KEYBYTES = 32;\n\n int CRYPTO_GENERICHASH_BLAKE2B_KEYBYTES_MIN = 16;\n\n int CRYPTO_GENERICHASH_BLAKE2B_KEYBYTES_MAX = 64;\n\n int crypto_generichash_blake2b(\n @Out byte[] buffer, @In @u_int64_t int outLen,\n @In byte[] message, @u_int64_t int messageLen, @In byte[] key,\n @In @u_int64_t int keyLen);\n\n int crypto_generichash_blake2b_salt_personal(\n @Out byte[] buffer, @In @u_int64_t int outLen,\n @In byte[] message, @u_int64_t int messageLen, @In byte[] key,\n @In @u_int64_t int keyLen, @In byte[] salt,\n @In byte[] personal);\n\n // ---------------------------------------------------------------------\n // Hashing: Short-input hashing\n\n int CRYPTO_SHORTHASH_SIPHASH24_BYTES = 8;\n\n int CRYPTO_SHORTHASH_SIPHASH24_KEYBYTES = 16;\n\n int crypto_shorthash_siphash24(@Out byte[] out, @In byte[] in, @u_int64_t int inLen, @In byte[] key);\n\n // ---------------------------------------------------------------------\n // Password hashing\n\n /**\n * @deprecated use CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRBYTES\n */\n @Deprecated\n int PWHASH_SCRYPTSALSA208SHA256_STRBYTES = 102;\n\n /**\n * @deprecated use CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OUTBYTES\n */\n @Deprecated\n int PWHASH_SCRYPTSALSA208SHA256_OUTBYTES = 64;\n\n /**\n * @deprecated use CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE\n */\n @Deprecated\n int PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 524288;\n\n /**\n * @deprecated use CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE\n */\n @Deprecated\n int PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE = 16777216;\n\n\n int CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRBYTES = 102;\n\n int CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OUTBYTES = 64;\n\n int CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 524288;\n\n int CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE = 16777216;\n\n int crypto_pwhash_scryptsalsa208sha256(\n @Out byte[] buffer, @In @u_int64_t int outlen,\n @In byte[] passwd,\n @In @u_int64_t int passwdlen, @In byte[] salt,\n @In @u_int64_t long opslimit, @In @u_int64_t long memlimit);\n\n int crypto_pwhash_scryptsalsa208sha256_str(\n @Out byte[] buffer, @In byte[] passwd,\n @In @u_int64_t int passwdlen, @In @u_int64_t long opslimit,\n @In @u_int64_t long memlimit);\n\n int crypto_pwhash_scryptsalsa208sha256_str_verify(\n @In byte[] buffer, @In byte[] passwd,\n @In @u_int64_t int passwdlen);\n\n // ---------------------------------------------------------------------\n // Advanced: AES256-GCM\n\n int CRYPTO_AEAD_AES256GCM_KEYBYTES = 32;\n\n int CRYPTO_AEAD_AES256GCM_NPUBBYTES = 12;\n\n int CRYPTO_AEAD_AES256GCM_ABYTES = 16;\n\n /**\n * @return 1 if the current CPU supports the AES256-GCM implementation,\n * and 0 if it doesn't.\n */\n int crypto_aead_aes256gcm_is_available();\n\n int crypto_aead_aes256gcm_encrypt(\n @Out byte[] ct, @Out LongLongByReference ctLen, @In byte[] msg,\n @In @u_int64_t int msgLen, @In byte[] ad,\n @In @u_int64_t int adLen, @In byte[] nsec, @In byte[] npub,\n @In byte[] key);\n\n int crypto_aead_aes256gcm_decrypt(\n @Out byte[] msg, @Out LongLongByReference msgLen, @In byte[] nsec,\n @In byte[] ct, @In @u_int64_t int ctLen, @In byte[] ad,\n @In @u_int64_t int adLen, @In byte[] npub, @In byte[] key);\n\n int crypto_aead_aes256gcm_statebytes();\n\n int crypto_aead_aes256gcm_beforenm(\n @Out byte[] state, @In byte[] key);\n\n int crypto_aead_aes256gcm_encrypt_afternm(\n @Out byte[] ct, @Out LongLongByReference ctLen, @In byte[] msg,\n @In @u_int64_t int msgLen, @In byte[] ad,\n @In @u_int64_t int adLen, @In byte[] nsec, @In byte[] npub,\n @In @Out byte[] state);\n\n int crypto_aead_aes256gcm_decrypt_afternm(\n @Out byte[] ct, @Out LongLongByReference ctLen, @In byte[] msg,\n @In @u_int64_t int msgLen, @In byte[] ad,\n @In @u_int64_t int adLen, @In byte[] nsec, @In byte[] npub,\n @In @Out byte[] state);\n\n // ---------------------------------------------------------------------\n // Advanced: SHA-2\n\n /**\n * @deprecated use CRYPTO_HASH_SHA256_BYTES\n */\n int SHA256BYTES = 32;\n\n /**\n * @deprecated use CRYPTO_HASH_SHA512_BYTES\n */\n int SHA512BYTES = 64;\n\n int CRYPTO_HASH_SHA256_BYTES = 32;\n\n int crypto_hash_sha256(\n @Out byte[] buffer, @In byte[] message,\n @In @u_int64_t int sizeof);\n\n int CRYPTO_HASH_SHA512_BYTES = 64;\n\n int crypto_hash_sha512(\n @Out byte[] buffer, @In byte[] message,\n @In @u_int64_t int sizeof);\n\n // ---------------------------------------------------------------------\n // Advanced: HMAC-SHA-2\n\n // TODO\n\n // ---------------------------------------------------------------------\n // Advanced: One-time authentication\n\n // TODO\n\n // ---------------------------------------------------------------------\n // Advanced: Diffie-Hellman\n\n int CRYPTO_SCALARMULT_CURVE25519_SCALARBYTES = 32;\n\n int CRYPTO_SCALARMULT_CURVE25519_BYTES = 32;\n\n int crypto_scalarmult_curve25519(\n @Out byte[] result, @In byte[] intValue, @In byte[] point);\n\n // ---------------------------------------------------------------------\n // Advanced: Stream ciphers: ChaCha20\n\n // TODO\n\n // ---------------------------------------------------------------------\n // Advanced: Stream ciphers: Salsa20\n\n int CRYPTO_STREAM_KEYBYTES = 32;\n\n int CRYPTO_STREAM_NONCEBYTES = 24;\n\n int crypto_stream_xor(\n @Out byte[] result, @In byte[] message,\n @In @u_int64_t int mlen,\n @In byte[] nonce, @In byte[] key);\n\n // ---------------------------------------------------------------------\n // Advanced: Stream ciphers: XSalsa20\n\n // TODO\n\n // ---------------------------------------------------------------------\n // Advanced: Ed25519 to Curve25519\n\n }\n\n /**\n * This is a Java synchronized wrapper around libsodium's init function.\n * LibSodium's init function is not thread-safe.\n *\n * Check libsodium's documentation for more info.\n */\n public static synchronized int init() {\n return sodium().sodium_init();\n }\n}", "public interface Encoder {\n\n public static final Charset CHARSET = Charset.forName(\"US-ASCII\");\n\n public static final Hex HEX = new Hex();\n public static final Raw RAW = new Raw();\n\n public byte[] decode(String data);\n\n public String encode(final byte[] data);\n}", "public class PrivateKey implements Key {\n\n private final byte[] secretKey;\n\n public PrivateKey(byte[] secretKey) {\n this.secretKey = secretKey;\n checkLength(secretKey, CRYPTO_BOX_CURVE25519XSALSA20POLY1305_SECRETKEYBYTES);\n }\n\n public PrivateKey(String secretKey) {\n this.secretKey = HEX.decode(secretKey);\n checkLength(this.secretKey, CRYPTO_BOX_CURVE25519XSALSA20POLY1305_SECRETKEYBYTES);\n }\n\n @Override\n public byte[] toBytes() {\n return secretKey;\n }\n\n @Override\n public String toString() {\n return HEX.encode(secretKey);\n }\n}", "public class PublicKey implements Key {\n\n private final byte[] publicKey;\n\n public PublicKey(byte[] publicKey) {\n this.publicKey = publicKey;\n checkLength(publicKey, CRYPTO_BOX_CURVE25519XSALSA20POLY1305_PUBLICKEYBYTES);\n }\n\n public PublicKey(String publicKey) {\n this.publicKey = HEX.decode(publicKey);\n }\n\n public byte[] toBytes() {\n return publicKey;\n }\n\n @Override\n public String toString() {\n return HEX.encode(publicKey);\n }\n}", "public static Sodium sodium() {\n Sodium sodium = SingletonHolder.SODIUM_INSTANCE;\n checkVersion(sodium);\n return sodium;\n}", "public static void checkLength(byte[] data, int size) {\n if (data == null || data.length != size)\n throw new RuntimeException(\"Invalid size\");\n}", "public static boolean isValid(int status, String message) {\n if (status != 0)\n throw new RuntimeException(message);\n return true;\n}", "public static byte[] prependZeros(int n, byte[] message) {\n byte[] result = new byte[n + message.length];\n System.arraycopy(message, 0, result, n, message.length);\n return result;\n}", "public static byte[] removeZeros(int n, byte[] message) {\n return Arrays.copyOfRange(message, n, message.length);\n}" ]
import static org.abstractj.kalium.crypto.Util.removeZeros; import org.abstractj.kalium.NaCl; import org.abstractj.kalium.encoders.Encoder; import org.abstractj.kalium.keys.PrivateKey; import org.abstractj.kalium.keys.PublicKey; import static org.abstractj.kalium.NaCl.Sodium.CRYPTO_BOX_CURVE25519XSALSA20POLY1305_BOXZEROBYTES; import static org.abstractj.kalium.NaCl.Sodium.CRYPTO_BOX_CURVE25519XSALSA20POLY1305_NONCEBYTES; import static org.abstractj.kalium.NaCl.Sodium.CRYPTO_BOX_CURVE25519XSALSA20POLY1305_PUBLICKEYBYTES; import static org.abstractj.kalium.NaCl.Sodium.CRYPTO_BOX_CURVE25519XSALSA20POLY1305_SECRETKEYBYTES; import static org.abstractj.kalium.NaCl.Sodium.CRYPTO_BOX_CURVE25519XSALSA20POLY1305_ZEROBYTES; import static org.abstractj.kalium.NaCl.sodium; import static org.abstractj.kalium.crypto.Util.checkLength; import static org.abstractj.kalium.crypto.Util.isValid; import static org.abstractj.kalium.crypto.Util.prependZeros;
/** * Copyright 2013 Bruno Oliveira, and individual contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.abstractj.kalium.crypto; /** * Based on Curve25519XSalsa20Poly1305 and Box classes from rbnacl */ public class Box { private final byte[] sharedKey; public Box(byte[] publicKey, byte[] privateKey) { checkLength(publicKey, CRYPTO_BOX_CURVE25519XSALSA20POLY1305_PUBLICKEYBYTES); checkLength(privateKey, CRYPTO_BOX_CURVE25519XSALSA20POLY1305_SECRETKEYBYTES); sharedKey = new byte[NaCl.Sodium.CRYPTO_BOX_CURVE25519XSALSA20POLY1305_BEFORENMBYTES]; isValid(sodium().crypto_box_curve25519xsalsa20poly1305_beforenm( sharedKey, publicKey, privateKey), "Key agreement failed"); } public Box(PublicKey publicKey, PrivateKey privateKey) { this(publicKey.toBytes(), privateKey.toBytes()); }
public Box(String publicKey, String privateKey, Encoder encoder) {
1
mars3142/toaster
app/src/main/java/org/mars3142/android/toaster/ui/activity/MainActivity.java
[ "public class PackageHelper {\r\n\r\n private static PackageHelper mInstance;\r\n\r\n private Context mContext;\r\n private HashMap<String, String> mAppNames;\r\n private BitmapLruCache mBitmapCache;\r\n\r\n private PackageHelper(Context context) {\r\n mContext = context;\r\n mAppNames = new HashMap<>();\r\n mBitmapCache = new BitmapLruCache();\r\n }\r\n\r\n public synchronized static PackageHelper with(Context context) {\r\n if (mInstance == null) {\r\n mInstance = new PackageHelper(context.getApplicationContext());\r\n }\r\n return mInstance;\r\n }\r\n\r\n public String getAppName(String packageName) {\r\n if (mAppNames.containsKey(packageName)) {\r\n return mAppNames.get(packageName);\r\n } else {\r\n try {\r\n PackageManager pm = mContext.getPackageManager();\r\n PackageInfo pi = pm.getPackageInfo(packageName, 0);\r\n String appName = pi.applicationInfo.loadLabel(mContext.getPackageManager()).toString();\r\n mAppNames.put(packageName, appName);\r\n return appName;\r\n } catch (Exception e) {\r\n // Nothing\r\n }\r\n }\r\n return packageName;\r\n }\r\n\r\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\r\n public Drawable getIconFromPackageName(String packageName) {\r\n Bitmap bitmap = mBitmapCache.get(packageName);\r\n if (bitmap != null) {\r\n return new BitmapDrawable(mContext.getResources(), bitmap);\r\n }\r\n\r\n PackageManager pm = mContext.getPackageManager();\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {\r\n try {\r\n PackageInfo pi = pm.getPackageInfo(packageName, 0);\r\n Context otherAppCtx = mContext.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);\r\n\r\n int displayMetrics[] = {DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_HIGH, DisplayMetrics.DENSITY_TV,\r\n DisplayMetrics.DENSITY_MEDIUM, DisplayMetrics.DENSITY_LOW};\r\n\r\n for (int displayMetric : displayMetrics) {\r\n try {\r\n Drawable drawable;\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\r\n drawable = otherAppCtx.getResources().getDrawableForDensity(pi.applicationInfo.icon, displayMetric, null);\r\n } else {\r\n drawable = otherAppCtx.getResources().getDrawableForDensity(pi.applicationInfo.icon, displayMetric);\r\n }\r\n if (drawable != null) {\r\n mBitmapCache.put(packageName, drawableToBitmap(drawable));\r\n return drawable;\r\n }\r\n } catch (Resources.NotFoundException e) {\r\n continue;\r\n }\r\n }\r\n } catch (Exception e) {\r\n // Handle Error here\r\n }\r\n }\r\n\r\n ApplicationInfo appInfo;\r\n try {\r\n appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);\r\n return appInfo.loadIcon(pm);\r\n } catch (PackageManager.NameNotFoundException e) {\r\n // Nothing\r\n }\r\n return null;\r\n }\r\n\r\n public static Bitmap drawableToBitmap(Drawable drawable) {\r\n if (drawable == null) {\r\n return null;\r\n }\r\n if (drawable instanceof BitmapDrawable) {\r\n return ((BitmapDrawable) drawable).getBitmap();\r\n }\r\n\r\n Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);\r\n Canvas canvas = new Canvas(bitmap);\r\n drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\r\n drawable.draw(canvas);\r\n\r\n return bitmap;\r\n }\r\n}\r", "public class AccessibilityServiceListener\r\n implements DialogInterface.OnClickListener {\r\n\r\n private final Context mContext;\r\n\r\n public AccessibilityServiceListener(Context context) {\r\n this.mContext = context;\r\n }\r\n\r\n @Override\r\n public void onClick(DialogInterface dialog, int which) {\r\n Timber.e(\"Starting accessibility settings activity...\");\r\n\r\n mContext.startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));\r\n }\r\n}\r", "public class DeleteListener\r\n implements DialogInterface.OnClickListener {\r\n\r\n private static final String TAG = DeleteListener.class.getSimpleName();\r\n\r\n private final Context mContext;\r\n private final Uri mUri;\r\n private final String mWhere;\r\n private final String[] mSelectionArgs;\r\n\r\n public DeleteListener(Context context, Uri uri) {\r\n this(context, uri, null, null);\r\n }\r\n\r\n public DeleteListener(Context context, Uri uri, String where, String[] selectionArgs) {\r\n mContext = context;\r\n mUri = uri;\r\n mWhere = where;\r\n mSelectionArgs = selectionArgs;\r\n }\r\n\r\n @Override\r\n public void onClick(DialogInterface dialog, int which) {\r\n if (mUri != null) {\r\n AsyncDelete task = new AsyncDelete(mContext, mUri, mWhere, mSelectionArgs);\r\n task.execute();\r\n }\r\n }\r\n}\r", "public class ToasterService extends AccessibilityService {\r\n\r\n @Override\r\n public void onAccessibilityEvent(AccessibilityEvent event) {\r\n Timber.d(\"Event: %s\", event);\r\n\r\n if (event.getEventType() != AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {\r\n Timber.d(\"Unexpected event type - ignoring\");\r\n return; // event is not a notification\r\n }\r\n\r\n long timestamp = Calendar.getInstance().getTimeInMillis();\r\n String sourcePackageName = (String) event.getPackageName();\r\n String message = \"\";\r\n for (CharSequence text : event.getText()) {\r\n message += text + \"\\n\";\r\n }\r\n if (message.length() > 0) {\r\n message = message.substring(0, message.length() - 1);\r\n }\r\n\r\n Parcelable parcelable = event.getParcelableData();\r\n if (!(parcelable instanceof Notification)) {\r\n ContentValues cv = new ContentValues();\r\n cv.put(ToasterTable.PACKAGE, sourcePackageName);\r\n cv.put(ToasterTable.MESSAGE, message);\r\n cv.put(ToasterTable.TIMESTAMP, timestamp);\r\n new AsyncInsert(this, ToasterTable.TOASTER_URI, cv).execute();\r\n\r\n Intent intent = new Intent(BuildConfig.APPLICATION_ID + \".APPWIDGET_UPDATE\");\r\n sendBroadcast(intent);\r\n }\r\n }\r\n\r\n @Override\r\n public void onInterrupt() {\r\n // Nothing\r\n }\r\n}\r", "public class ToasterTable\r\n implements BaseColumns {\r\n\r\n private static final String TAG = ToasterTable.class.getSimpleName();\r\n \r\n public static final String TABLE_NAME = \"toaster\";\r\n public static final String TIMESTAMP = \"timestamp\";\r\n public static final String PACKAGE = \"package\";\r\n public static final String MESSAGE = \"message\";\r\n public static final String VERSION_CODE = \"version_code\";\r\n public static final String VERSION_NAME = \"version_name\";\r\n public static final Uri TOASTER_URI = Uri.parse(\"content://\" + ToasterProvider.AUTHORITY + \"/toaster\");\r\n public static final Uri PACKAGE_URI = Uri.parse(\"content://\" + ToasterProvider.AUTHORITY + \"/packages\");\r\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + \"/vnd.mars3142.content.toaster\";\r\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + \"/vnd.mars3142.content.toaster\";\r\n\r\n public static void onCreate(SQLiteDatabase db) {\r\n db.execSQL(\"CREATE TABLE \" + TABLE_NAME +\r\n \" (\" +\r\n _ID + \" INTEGER PRIMARY KEY AUTOINCREMENT, \" +\r\n TIMESTAMP + \" LONG, \" +\r\n PACKAGE + \" TEXT, \" +\r\n MESSAGE + \" TEXT, \" +\r\n VERSION_CODE + \" INTEGER, \" +\r\n VERSION_NAME + \" TEXT \" +\r\n \");\");\r\n }\r\n\r\n public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n if (newVersion > oldVersion) {\r\n switch (oldVersion) {\r\n case 1:\r\n try {\r\n db.execSQL(\"ALTER TABLE \" + TABLE_NAME + \" ADD COLUMN \" + VERSION_CODE + \" INTEGER;\");\r\n db.execSQL(\"ALTER TABLE \" + TABLE_NAME + \" ADD COLUMN \" + VERSION_NAME + \" TEXT;\");\r\n } catch (SQLException ex) {\r\n // upgrade already done\r\n }\r\n break;\r\n\r\n default:\r\n db.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME);\r\n onCreate(db);\r\n }\r\n }\r\n }\r\n\r\n public static void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n // nothing\r\n }\r\n}\r", "public class PackagesFragment extends Fragment\r\n implements LoaderManager.LoaderCallbacks<Cursor>, View.OnClickListener, NavDrawerRecyclerViewHolder.OnItemClickListener {\r\n\r\n private static final String STATE_SELECTED_PACKAGE_NAME = \"selected_package_name\";\r\n private static final int DATA_LOADER = 0;\r\n\r\n private PackagesCallbacks mCallbacks;\r\n private ActionBarDrawerToggle mDrawerToggle;\r\n private DrawerLayout mDrawerLayout;\r\n private View mFragmentContainerView;\r\n private RecyclerView mDrawerRecyclerView;\r\n private String mCurrentSelectedPackageName = null;\r\n\r\n public PackagesFragment() {\r\n }\r\n\r\n @Override\r\n public void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n\r\n if (savedInstanceState != null) {\r\n mCurrentSelectedPackageName = savedInstanceState.getString(STATE_SELECTED_PACKAGE_NAME);\r\n }\r\n }\r\n\r\n @Override\r\n public void onActivityCreated(Bundle savedInstanceState) {\r\n super.onActivityCreated(savedInstanceState);\r\n\r\n setHasOptionsMenu(true);\r\n }\r\n\r\n @Override\r\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\r\n RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.packages, container, false);\r\n\r\n RelativeLayout settings = (RelativeLayout) layout.findViewById(R.id.setting);\r\n settings.setOnClickListener(this);\r\n\r\n LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());\r\n layoutManager.setOrientation(LinearLayoutManager.VERTICAL);\r\n mDrawerRecyclerView = (RecyclerView) layout.findViewById(R.id.recycler_view);\r\n if (mDrawerRecyclerView != null) {\r\n mDrawerRecyclerView.setLayoutManager(layoutManager);\r\n }\r\n\r\n getLoaderManager().restartLoader(DATA_LOADER, null, this);\r\n\r\n return layout;\r\n }\r\n\r\n @Override\r\n public void onViewCreated(View view, Bundle savedInstanceState) {\r\n super.onViewCreated(view, savedInstanceState);\r\n\r\n onItemClick(mCurrentSelectedPackageName);\r\n }\r\n\r\n @Override\r\n public void onAttach(Activity activity) {\r\n super.onAttach(activity);\r\n\r\n try {\r\n mCallbacks = (PackagesCallbacks) activity;\r\n } catch (ClassCastException e) {\r\n throw new ClassCastException(\"Activity must implement PackagesCallbacks.\");\r\n }\r\n }\r\n\r\n @Override\r\n public void onDetach() {\r\n super.onDetach();\r\n\r\n mCallbacks = null;\r\n }\r\n\r\n @Override\r\n public void onSaveInstanceState(Bundle outState) {\r\n super.onSaveInstanceState(outState);\r\n\r\n outState.putString(STATE_SELECTED_PACKAGE_NAME, mCurrentSelectedPackageName);\r\n }\r\n\r\n @Override\r\n public void onConfigurationChanged(Configuration newConfig) {\r\n super.onConfigurationChanged(newConfig);\r\n\r\n mDrawerToggle.onConfigurationChanged(newConfig);\r\n }\r\n\r\n @Override\r\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\r\n if (mDrawerLayout != null && isDrawerOpen()) {\r\n showGlobalContextActionBar();\r\n }\r\n\r\n super.onCreateOptionsMenu(menu, inflater);\r\n }\r\n\r\n @Override\r\n public boolean onOptionsItemSelected(MenuItem item) {\r\n return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);\r\n }\r\n\r\n @Override\r\n public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {\r\n switch (loaderId) {\r\n case DATA_LOADER:\r\n return new CursorLoader(getActivity(), ToasterTable.PACKAGE_URI, null, null, null, null);\r\n\r\n default:\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n\r\n @Override\r\n public void onLoadFinished(Loader<Cursor> loader, Cursor data) {\r\n switch (loader.getId()) {\r\n case DATA_LOADER:\r\n ArrayList<ToastCard> packageList = new ArrayList<>();\r\n\r\n if (data.moveToFirst()) {\r\n do {\r\n String packageName = data.getString(data.getColumnIndex(ToasterTable.PACKAGE));\r\n ToastCard packageCard = new ToastCard(getActionBar().getThemedContext(), packageName);\r\n if (packageCard.packageName != null) {\r\n packageList.add(packageCard);\r\n }\r\n } while (data.moveToNext());\r\n }\r\n Collections.sort(packageList, new ToastCardComparator());\r\n mDrawerRecyclerView.setAdapter(new NavDrawerRecyclerAdapter(getActivity(), packageList, this));\r\n\r\n break;\r\n\r\n default:\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n\r\n @Override\r\n public void onLoaderReset(Loader<Cursor> loader) {\r\n switch (loader.getId()) {\r\n case DATA_LOADER:\r\n mDrawerRecyclerView.setAdapter(null);\r\n break;\r\n\r\n default:\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n\r\n private void showGlobalContextActionBar() {\r\n ActionBar actionBar = getActionBar();\r\n actionBar.setDisplayShowTitleEnabled(true);\r\n }\r\n\r\n private ActionBar getActionBar() {\r\n return ((AppCompatActivity) getActivity()).getSupportActionBar();\r\n }\r\n\r\n public boolean isDrawerOpen() {\r\n return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);\r\n }\r\n\r\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\r\n public void setUp(int fragmentId, DrawerLayout drawerLayout) {\r\n mFragmentContainerView = getActivity().findViewById(fragmentId);\r\n mDrawerLayout = drawerLayout;\r\n\r\n ActionBar actionBar = getActionBar();\r\n if (actionBar != null) {\r\n actionBar.setDisplayHomeAsUpEnabled(true);\r\n actionBar.setHomeButtonEnabled(true);\r\n }\r\n\r\n mDrawerToggle = new ActionBarDrawerToggle(\r\n getActivity(),\r\n mDrawerLayout,\r\n (Toolbar) getActivity().findViewById(R.id.toolbar),\r\n R.string.navigation_drawer_open,\r\n R.string.navigation_drawer_close\r\n ) {\r\n @Override\r\n public void onDrawerClosed(View drawerView) {\r\n super.onDrawerClosed(drawerView);\r\n if (!isAdded()) {\r\n return;\r\n }\r\n\r\n getLoaderManager().restartLoader(DATA_LOADER, null, PackagesFragment.this);\r\n getActivity().invalidateOptionsMenu();\r\n }\r\n\r\n @Override\r\n public void onDrawerOpened(View drawerView) {\r\n super.onDrawerOpened(drawerView);\r\n if (!isAdded()) {\r\n return;\r\n }\r\n\r\n getLoaderManager().restartLoader(DATA_LOADER, null, PackagesFragment.this);\r\n getActivity().invalidateOptionsMenu();\r\n }\r\n };\r\n\r\n mDrawerLayout.post(new Runnable() {\r\n @Override\r\n public void run() {\r\n mDrawerToggle.syncState();\r\n }\r\n });\r\n mDrawerLayout.setDrawerListener(mDrawerToggle);\r\n }\r\n\r\n @Override\r\n public void onItemClick(String packageName) {\r\n if (mDrawerLayout != null) {\r\n mDrawerLayout.closeDrawer(mFragmentContainerView);\r\n }\r\n\r\n if (mCallbacks != null && !((\"\" + packageName).equals(\"\" + mCurrentSelectedPackageName))) {\r\n mCallbacks.onPackagesItemSelected(packageName);\r\n }\r\n\r\n mCurrentSelectedPackageName = packageName;\r\n }\r\n\r\n @Override\r\n public void onClick(View view) {\r\n switch (view.getId()) {\r\n case R.id.setting:\r\n Intent intent = new Intent(getActivity(), SettingsActivity.class);\r\n getActivity().startActivity(intent);\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n public interface PackagesCallbacks {\r\n void onPackagesItemSelected(String packageName);\r\n }\r\n}\r", "public class ToasterFragment extends Fragment\r\n implements LoaderManager.LoaderCallbacks<Cursor>, AbsListView.OnScrollListener {\r\n\r\n private static final String TAG = ToasterFragment.class.getSimpleName();\r\n private static final String PACKAGE_FILTER = \"packageFilter\";\r\n private static final int DATA_LOADER_ALL = 0;\r\n private static final int DATA_LOADER_FILTERED = 1;\r\n\r\n private ToastCardAdapter mAdapter;\r\n\r\n public ToasterFragment() {\r\n }\r\n\r\n public static ToasterFragment newInstance(String packageFilter) {\r\n ToasterFragment fragment = new ToasterFragment();\r\n Bundle args = new Bundle();\r\n args.putString(PACKAGE_FILTER, packageFilter);\r\n fragment.setArguments(args);\r\n return fragment;\r\n }\r\n\r\n @Override\r\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\r\n return inflater.inflate(R.layout.toaster, container, false);\r\n }\r\n\r\n @Override\r\n public void onViewCreated(View view, Bundle savedInstanceState) {\r\n super.onViewCreated(view, savedInstanceState);\r\n\r\n mAdapter = new ToastCardAdapter(getActivity());\r\n CardListView mListView = (CardListView) getActivity().findViewById(R.id.toast_card_list);\r\n if (mListView != null) {\r\n mListView.setAdapter(mAdapter);\r\n mListView.setOnScrollListener(this);\r\n }\r\n\r\n String packageFilter = null;\r\n if (getArguments() != null) {\r\n packageFilter = getArguments().getString(PACKAGE_FILTER);\r\n }\r\n if (TextUtils.isEmpty(packageFilter)) {\r\n getLoaderManager().restartLoader(DATA_LOADER_ALL, null, this);\r\n } else {\r\n getLoaderManager().restartLoader(DATA_LOADER_FILTERED, null, this);\r\n }\r\n }\r\n\r\n @Override\r\n public Loader<Cursor> onCreateLoader(int id, Bundle args) {\r\n switch (id) {\r\n case DATA_LOADER_ALL:\r\n return new CursorLoader(getActivity(), ToasterTable.TOASTER_URI, null, null, null, null);\r\n\r\n case DATA_LOADER_FILTERED:\r\n return new CursorLoader(getActivity(), ToasterTable.TOASTER_URI, null, ToasterTable.PACKAGE + \" = ?\", new String[]{getArguments().getString(PACKAGE_FILTER)}, null);\r\n\r\n default:\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n\r\n @Override\r\n public void onLoadFinished(Loader<Cursor> loader, Cursor data) {\r\n if (getActivity() == null) {\r\n return;\r\n }\r\n\r\n switch (loader.getId()) {\r\n case DATA_LOADER_ALL:\r\n case DATA_LOADER_FILTERED:\r\n mAdapter.swapCursor(data);\r\n break;\r\n\r\n default:\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n\r\n @Override\r\n public void onLoaderReset(Loader<Cursor> loader) {\r\n switch (loader.getId()) {\r\n case DATA_LOADER_ALL:\r\n case DATA_LOADER_FILTERED:\r\n mAdapter.swapCursor(null);\r\n break;\r\n\r\n default:\r\n throw new IllegalArgumentException();\r\n }\r\n }\r\n\r\n @Override\r\n public void onAttach(Activity activity) {\r\n super.onAttach(activity);\r\n\r\n try {\r\n String packageFilter = null;\r\n if (getArguments() != null) {\r\n packageFilter = getArguments().getString(PACKAGE_FILTER);\r\n }\r\n if (TextUtils.isEmpty(packageFilter)) {\r\n packageFilter = \"\";\r\n }\r\n ((MainActivity) activity).onSectionAttached(packageFilter);\r\n } catch (NullPointerException ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n @Override\r\n public void onScrollStateChanged(AbsListView view, int scrollState) {\r\n MainActivity activity = (MainActivity) getActivity();\r\n if (activity != null) {\r\n // activity.toggleToolbarVisibility();\r\n }\r\n }\r\n\r\n @Override\r\n public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {\r\n if (view.getChildCount() > 0) {\r\n //\r\n }\r\n }\r\n}\r", "public class NavDrawerRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n private OnItemClickListener mOnItemClickListener;\n public ImageView mPackageIcon;\n public TextView mAppName;\n public String mPackageName;\n\n public NavDrawerRecyclerViewHolder(View itemView, OnItemClickListener onItemClickListener) {\n super(itemView);\n\n mOnItemClickListener = onItemClickListener;\n mAppName = (TextView) itemView.findViewById(R.id.app_name);\n mPackageIcon = (ImageView) itemView.findViewById(R.id.package_icon);\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n if (mOnItemClickListener != null) {\n mOnItemClickListener.onItemClick(mPackageName);\n }\n }\n\n public interface OnItemClickListener {\n void onItemClick(String packageName);\n }\n}" ]
import android.animation.Animator; import android.animation.ObjectAnimator; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.animation.BounceInterpolator; import android.view.animation.LinearInterpolator; import org.mars3142.android.toaster.BuildConfig; import org.mars3142.android.toaster.R; import org.mars3142.android.toaster.helper.PackageHelper; import org.mars3142.android.toaster.listener.AccessibilityServiceListener; import org.mars3142.android.toaster.listener.DeleteListener; import org.mars3142.android.toaster.service.ToasterService; import org.mars3142.android.toaster.table.ToasterTable; import org.mars3142.android.toaster.ui.fragment.PackagesFragment; import org.mars3142.android.toaster.ui.fragment.ToasterFragment; import org.mars3142.android.toaster.viewholder.NavDrawerRecyclerViewHolder; import timber.log.Timber;
/* * This file is part of Toaster * * Copyright (c) 2014, 2017 Peter Siegmund * * 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.mars3142.android.toaster.ui.activity; /** * MainActivity of Toaster * <p/> * It's the main entry point for the app * * @author mars3142 */ public class MainActivity extends AppCompatActivity implements PackagesFragment.PackagesCallbacks, NavDrawerRecyclerViewHolder.OnItemClickListener { private static final String PACKAGE_NAME = "packageName"; private PackagesFragment mPackagesFragment; private CharSequence mTitle; private String mPackageName; private Toolbar mToolbar; private Boolean mToobarVisible = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitle = getTitle(); mToolbar = findViewById(R.id.toolbar); if (mToolbar != null) { setSupportActionBar(mToolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setHomeButtonEnabled(false); getSupportActionBar().setElevation(getResources().getDimension(R.dimen.elevation_toolbar)); } } DrawerLayout drawerLayout = findViewById(R.id.drawer_layout); if (drawerLayout != null) { mPackagesFragment = (PackagesFragment) getFragmentManager().findFragmentById(R.id.packages); mPackagesFragment.setUp(R.id.packages, drawerLayout); } if (savedInstanceState != null) { mPackageName = savedInstanceState.getString(PACKAGE_NAME); } onPackagesItemSelected(mPackageName); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(PACKAGE_NAME, mPackageName); } @Override public boolean onCreateOptionsMenu(Menu menu) { int menuRes = R.menu.main_options; if (mPackagesFragment != null) { if (!mPackagesFragment.isDrawerOpen()) { menuRes = R.menu.main_options; } } getMenuInflater().inflate(menuRes, menu); restoreActionBar(); return true; } @Override public void onPackagesItemSelected(String packageFilter) { getFragmentManager().beginTransaction().replace(R.id.container, ToasterFragment.newInstance(packageFilter)).commit(); } @Override public void onItemClick(String packageName) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.container, ToasterFragment.newInstance(packageName)); transaction.commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.action_blacklist: intent = new Intent(this, BlacklistActivity.class); startActivity(intent); return true; case R.id.action_delete: DeleteListener deleteListener; if (TextUtils.isEmpty(mPackageName)) {
deleteListener = new DeleteListener(this, ToasterTable.TOASTER_URI);
4
mouton5000/DSTAlgoEvaluation
src/graphTheory/generators/steinLib/STPUndirectedGenerator.java
[ "public class Arc implements Cloneable {\n\n\tprivate Integer input;\n\tprivate Integer output;\n\tprivate boolean isDirected;\n\n\tpublic Arc(Integer input, Integer output, boolean isDirected) {\n\t\tthis.input = input;\n\t\tthis.output = output;\n\t\tthis.isDirected = isDirected;\n\t}\n\n\tpublic Integer getInput() {\n\t\treturn input;\n\t}\n\n\tpublic Integer getOutput() {\n\t\treturn output;\n\t}\n\n\tpublic boolean isDirected() {\n\t\treturn isDirected;\n\t}\n\n\tpublic boolean equals(Object o) {\n\t\tif (o == null)\n\t\t\treturn false;\n\t\tif (o instanceof Arc) {\n\t\t\tArc a = (Arc) o;\n\n\t\t\treturn isDirected == a.isDirected\n\t\t\t\t\t&& ((((input == null && a.input == null) || (input != null && input\n\t\t\t\t\t\t\t.equals(a.input))) && ((output == null && a.output == null) || (output != null && output\n\t\t\t\t\t\t\t.equals(a.output)))) || (!isDirected && ((input == null && a.output == null) || (input != null && input\n\t\t\t\t\t\t\t.equals(a.output))))\n\t\t\t\t\t\t\t&& ((output == null && a.input == null) || (output != null && (output\n\t\t\t\t\t\t\t\t\t.equals(a.input)))));\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic String toString() {\n\t\treturn (new StringBuilder()).append(input).append(\" ---\")\n\t\t\t\t.append(isDirected ? \">\" : \"-\").append(\" \").append(output)\n\t\t\t\t.toString();\n\t}\n\n\tpublic int hashCode() {\n\n\t\tint i1 = input;\n\t\tint i2 = output;\n\t\tif (isDirected)\n\t\t\treturn i1 ^ (i2 * 31);\n\t\telse\n\t\t\treturn i1 ^ i2;\n\t}\n\n\tpublic static Arc valueOf(String s) {\n\t\tPattern p = Pattern.compile(\"(\\\\d+) ---(>|-) (\\\\d+)\");\n\t\tMatcher m = p.matcher(s);\n\t\tif (m.find())\n\t\t\treturn new Arc(Integer.valueOf(m.group(1)), Integer.valueOf(m\n\t\t\t\t\t.group(3)), m.group(2).equals(\">\"));\n\t\telse\n\t\t\treturn null;\n\n\t}\n\n\tpublic Object clone() {\n\t\tArc a;\n\t\ttry {\n\t\t\ta = (Arc) super.clone();\n\t\t\ta.input = input;\n\t\t\ta.output = output;\n\t\t\treturn a;\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n}", "public class SteinerUndirectedInstance extends SteinerInstance {\n\n\tpublic SteinerUndirectedInstance(UndirectedGraph g) {\n\t\tsuper(g);\n\t}\n\n\tpublic UndirectedGraph getGraph() {\n\t\treturn (UndirectedGraph) graph;\n\t}\n\n\t@Override\n\tpublic boolean hasSolution() {\n\t\tInteger u, v;\n\t\tint k = getNumberOfRequiredVertices();\n\t\tif (k == 0)\n\t\t\treturn true;\n\n\t\tu = getRequiredVertice(0);\n\t\tfor (int j = 1; j < k; j++) {\n\t\t\tv = getRequiredVertice(j);\n\t\t\tif (!graph.areConnectedByUndirectedEdges(u, v))\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n}", "public class STPTranslationException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate STPTranslationExceptionEnum errorValue;\n\tprivate String filePath;\n\tprivate int lineNumber;\n\tprivate String lineValue;\n\n\tpublic STPTranslationException(STPTranslationExceptionEnum errorValue,\n\t\t\tString filePath, int lineNumber, String lineValue) {\n\t\tsuper();\n\t\tthis.errorValue = errorValue;\n\t\tthis.filePath = filePath;\n\t\tthis.lineNumber = lineNumber;\n\t\tthis.lineValue = lineValue;\n\n\t}\n\n\t@Override\n\tpublic String getMessage() {\n\t\tString s = \"While parsing \" + filePath + \"\\n\" + \"At line \" + lineNumber\n\t\t\t\t+ \" : \" + lineValue + \"\\n\" + \"Error : \" + errorValue.toString();\n\n\t\treturn s;\n\t}\n\n}", "public class STPTranslator {\n\n\t/**\n\t * Return the {@link SteinerDirectedInstance} or the\n\t * {@link SteinerUndirectedInstance} conresponding to the .stp file in\n\t * input. If the file describes a graph containing directed arcs and\n\t * undirected edges, then this method returns null.\n\t * \n\t * @param nomFic\n\t * path of the file describing the instance we want to build.\n\t * @return\n\t * @throws STPTranslationException\n\t */\n\tpublic static SteinerInstance translateFile(String nomFic)\n\t\t\tthrows STPTranslationException {\n\t\tFileManager f = new FileManager();\n\t\tf.openRead(nomFic);\n\t\tString s;\n\t\tint lineNumber = 0;\n\t\ts = f.readLine();\n\t\tlineNumber++;\n\t\tif (s == null) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.EMPTY_FILE, nomFic, lineNumber,\n\t\t\t\t\tnull);\n\t\t}\n\n\t\ts = s.toLowerCase();\n\n\t\t// On vérifie que le fichier est au bon format\n\n\t\tif (!s.contains(\"33d32945\")) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.BAD_FORMAT_CODE, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\n\t\t// On saute l'espace réservé aux commentaires.\n\t\twhile (!s.contains(\"section graph\")) {\n\t\t\ts = f.readLine();\n\t\t\tlineNumber++;\n\t\t\tif (s == null) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.NO_SECTION_GRAPH, nomFic,\n\t\t\t\t\t\tlineNumber, s);\n\t\t\t}\n\t\t\ts = s.toLowerCase();\n\t\t}\n\n\t\t// On récupère le nombre de noeuds.\n\t\ts = f.readLine();\n\t\tlineNumber++;\n\n\t\tif (s == null) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.EMPTY_SECTION_GRAPH, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\t\ts = s.toLowerCase();\n\t\ts = s.trim();\n\t\tPattern p = Pattern.compile(\"nodes +(\\\\d+)\");\n\t\tMatcher m = p.matcher(s);\n\t\tint nov;\n\t\tif (!m.matches())\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.NODE_NUMBER_BAD_FORMAT, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\tnov = Integer.valueOf(m.group(1));\n\t\t// On récupère le nombre d'arcs\n\t\ts = f.readLine();\n\t\tlineNumber++;\n\t\tif (s == null) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.EDGE_NUMBER_BAD_FORMAT, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\t\ts = s.toLowerCase();\n\t\ts = s.trim();\n\t\tp = Pattern.compile(\"(edges|arcs) +(\\\\d+)\");\n\t\tm = p.matcher(s);\n\t\tboolean isDirected;\n\t\tint noe;\n\t\tchar letter;\n\t\tSteinerInstance g;\n\t\tif (m.matches()) {\n\t\t\tisDirected = m.group(1).equals(\"arcs\");\n\t\t\tif (isDirected) {\n\t\t\t\tDirectedGraph dg = new DirectedGraph();\n\t\t\t\tg = new SteinerDirectedInstance(dg);\n\t\t\t\tletter = 'a';\n\t\t\t} else {\n\t\t\t\tUndirectedGraph ug = new UndirectedGraph();\n\t\t\t\tg = new SteinerUndirectedInstance(ug);\n\t\t\t\tletter = 'e';\n\t\t\t}\n\t\t\tnoe = Integer.valueOf(m.group(2));\n\t\t} else {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.EDGE_NUMBER_BAD_FORMAT, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\n\t\ts = f.readLine();\n\t\tlineNumber++;\n\t\tif (s == null) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.NO_SECTION_GRAPH_CONTENT,\n\t\t\t\t\tnomFic, lineNumber, s);\n\t\t}\n\t\ts = s.toLowerCase();\n\t\ts = s.trim();\n\t\twhile (s.equals(\"\")) {\n\t\t\ts = f.readLine();\n\t\t\tlineNumber++;\n\n\t\t\tif (s == null) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.NO_SECTION_GRAPH_CONTENT,\n\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t}\n\t\t\ts = s.toLowerCase();\n\t\t\ts = s.trim();\n\t\t}\n\t\tp = Pattern.compile(letter + \" +(\\\\d+) +(\\\\d+) +(\\\\d+)\");\n\t\tint cost;\n\t\tInteger n1, n2;\n\t\twhile (!s.equals(\"end\")) {\n\t\t\tm = p.matcher(s);\n\t\t\tif (m.matches()) {\n\t\t\t\tn1 = Integer.valueOf(m.group(1));\n\t\t\t\tn2 = Integer.valueOf(m.group(2));\n\t\t\t\tcost = Integer.valueOf(m.group(3));\n\t\t\t\tif (!g.getGraph().contains(n1)) {\n\t\t\t\t\tg.getGraph().addVertice(n1);\n\t\t\t\t\tnov--;\n\t\t\t\t}\n\t\t\t\tif (!g.getGraph().contains(n2)) {\n\t\t\t\t\tg.getGraph().addVertice(n2);\n\t\t\t\t\tnov--;\n\t\t\t\t}\n\n\t\t\t\tArc a;\n\t\t\t\tif (isDirected)\n\t\t\t\t\ta = g.getGraph().addDirectedEdge(n1, n2);\n\t\t\t\telse\n\t\t\t\t\ta = g.getGraph().addUndirectedEdge(n1, n2);\n\t\t\t\tg.setCost(a, cost);\n\t\t\t} else {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.EDGE_DESCRIPTION_BAD_FORMAT,\n\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t}\n\n\t\t\ts = f.readLine();\n\t\t\tlineNumber++;\n\t\t\tif (s == null) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.FILE_ENDED_BEFORE_EOF_SG,\n\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t}\n\t\t\ts = s.toLowerCase();\n\t\t\ts = s.trim();\n\t\t\tnoe--;\n\t\t}\n\n\t\tif (nov != 0) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.INCOHERENT_NB_NODES, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\t\tif (noe != 0) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.INCOHERENT_NB_EDGES, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\n\t\t// On saute jusqu'aux terminaux\n\t\twhile (!s.contains(\"section terminals\")) {\n\t\t\ts = f.readLine();\n\t\t\tlineNumber++;\n\t\t\tif (s == null) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.NO_SECTION_TERM, nomFic,\n\t\t\t\t\t\tlineNumber, s);\n\t\t\t}\n\t\t\ts = s.toLowerCase();\n\t\t}\n\n\t\ts = f.readLine();\n\t\tlineNumber++;\n\t\tif (s == null) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.EMPTY_SECTION_TERM, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\t\ts = s.toLowerCase();\n\t\tp = Pattern.compile(\"terminals +(\\\\d+)\");\n\t\tm = p.matcher(s);\n\t\tint not;\n\t\tint size = g.getGraph().getNumberOfVertices();\n\t\tif (m.matches()) {\n\t\t\tnot = Integer.valueOf(m.group(1));\n\t\t\tif (not > size || not <= 0) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.STRANGE_NB_TERM, nomFic,\n\t\t\t\t\t\tlineNumber, s);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.TERMINALS_NUMBER_BAD_FORMAT,\n\t\t\t\t\tnomFic, lineNumber, s);\n\t\t}\n\n\t\tboolean rootSet = false;\n\t\ts = f.readLine();\n\t\tlineNumber++;\n\t\tif (s == null) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.NO_SECTION_TERM_CONTENT,\n\t\t\t\t\tnomFic, lineNumber, s);\n\t\t}\n\t\ts = s.toLowerCase();\n\t\ts = s.trim();\n\t\tp = Pattern.compile(\"(t +(\\\\d+))|(root +(\\\\d+))\");\n\t\twhile (!s.equals(\"end\")) {\n\t\t\tm = p.matcher(s);\n\t\t\tif (m.matches()) {\n\t\t\t\tif (m.group(3) != null) {\n\t\t\t\t\tif (rootSet || !isDirected) {\n\t\t\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\t\t\tSTPTranslationExceptionEnum.TOO_MUCH_ROOT_SET,\n\t\t\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t\t\t} else {\n\t\t\t\t\t\trootSet = true;\n\t\t\t\t\t\t((SteinerDirectedInstance) g).setRoot(Integer.valueOf(m\n\t\t\t\t\t\t\t\t.group(4)));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tn1 = Integer.valueOf(m.group(2));\n\t\t\t\t\tg.setRequired(n1, true);\n\t\t\t\t\tnot--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.TERMINALS_DESC_BAD_FORMAT,\n\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t}\n\t\t\ts = f.readLine();\n\t\t\tlineNumber++;\n\t\t\tif (s == null) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.FILE_ENDED_BEFORE_EOF_ST,\n\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t}\n\t\t\ts = s.toLowerCase();\n\n\t\t}\n\t\tif (not != 0) {\n\t\t\tthrow new STPTranslationException(\n\t\t\t\t\tSTPTranslationExceptionEnum.INCOHERENT_NB_TERMS, nomFic,\n\t\t\t\t\tlineNumber, s);\n\t\t}\n\n\t\t// On saute l'espace reservé aux coordonnées\n\t\twhile (!s.contains(\"eof\")) {\n\t\t\ts = f.readLine();\n\t\t\tlineNumber++;\n\t\t\tif (s == null) {\n\t\t\t\tthrow new STPTranslationException(\n\t\t\t\t\t\tSTPTranslationExceptionEnum.FILE_ENDED_BEFORE_EOF,\n\t\t\t\t\t\tnomFic, lineNumber, s);\n\t\t\t}\n\t\t\ts = s.toLowerCase();\n\t\t}\n\t\treturn g;\n\t}\n\n\t/**\n\t * \n\t * Return the {@link SteinerDirectedInstance} conresponding to the .stp file\n\t * in input. If the file describes a graph containing undirected edges, then\n\t * this method returns null.\n\t * \n\t * @param nomFic\n\t * path of the file describing the instance we want to build.\n\t * @return\n\t * @throws STPTranslationException\n\t */\n\tpublic static SteinerDirectedInstance translateDirectedFile(String nomFic)\n\t\t\tthrows STPTranslationException {\n\t\tSteinerInstance g = translateFile(nomFic);\n\t\tif (g == null || g instanceof SteinerUndirectedInstance)\n\t\t\treturn null;\n\t\telse\n\t\t\treturn (SteinerDirectedInstance) g;\n\t}\n\n\t/**\n\t * \n\t * Return the {@link SteinerUndirectedInstance} conresponding to the .stp\n\t * file in input. If the file describes a graph containing directed arcs,\n\t * then this method returns null.\n\t * \n\t * @param nomFic\n\t * path of the file describing the instance we want to build.\n\t * @return\n\t * @throws STPTranslationException\n\t */\n\tpublic static SteinerUndirectedInstance translateUndirectedFile(\n\t\t\tString nomFic) throws STPTranslationException {\n\t\tSteinerInstance g = translateFile(nomFic);\n\t\tif (g == null || g instanceof SteinerDirectedInstance)\n\t\t\treturn null;\n\t\telse\n\t\t\treturn (SteinerUndirectedInstance) g;\n\t}\n\n\t/**\n\t * Translate the Steiner instance g into a .stp file, which path is nomFic.\n\t * \n\t * @param g\n\t * @param nomFic\n\t */\n\tpublic static void translateSteinerGraph(SteinerInstance g, String nomFic) {\n\t\ttranslateSteinerGraph(g, nomFic, \"\");\n\t}\n\n\t/**\n\t * Translate the Steiner instance g into a .stp file, which path is nomFic.\n\t * Associate the instance to the name given in parameter in the file.\n\t * \n\t * @param g\n\t * @param nomFic\n\t */\n\tpublic static void translateSteinerGraph(SteinerInstance g, String nomFic,\n\t\t\tString name) {\n\t\tboolean isDirected = g instanceof SteinerDirectedInstance;\n\t\tFileManager f = new FileManager();\n\t\tf.openErase(nomFic);\n\n\t\tf.writeln(\"33d32945 STP File, STP Format Version 1.0\");\n\t\tf.writeln();\n\t\tf.writeln(\"SECTION Comment\");\n\t\tf.writeln(\"Name \\\"\" + name + \"\\\"\");\n\t\tf.writeln(\"Creator \\\"Dimitri Watel\\\"\");\n\t\tf.writeln(\"Remark \\\"\\\"\");\n\t\tf.writeln(\"END\");\n\t\tf.writeln();\n\t\tf.writeln(\"SECTION Graph\");\n\t\tf.writeln(\"Nodes \" + g.getGraph().getNumberOfVertices());\n\t\tf.writeln((isDirected ? \"Arcs\" : \"Edges\") + \" \"\n\t\t\t\t+ g.getGraph().getNumberOfEdges());\n\t\tIterator<Arc> it = g.getGraph().getEdgesIterator();\n\t\tArc a;\n\t\twhile (it.hasNext()) {\n\t\t\ta = it.next();\n\t\t\tf.writeln((isDirected ? 'A' : 'E') + \" \" + a.getInput() + \" \"\n\t\t\t\t\t+ a.getOutput() + \" \" + g.getIntCost(a));\n\t\t}\n\t\tf.writeln(\"END\");\n\t\tf.writeln();\n\t\tf.writeln(\"SECTION Terminals\");\n\t\tf.writeln(\"Terminals \" + g.getNumberOfRequiredVertices());\n\t\tif (isDirected) {\n\t\t\tf.writeln(\"Root \" + ((SteinerDirectedInstance) g).getRoot());\n\t\t}\n\t\tIterator<Integer> it2 = g.getRequiredVerticesIterator();\n\t\tInteger n;\n\t\twhile (it2.hasNext()) {\n\t\t\tn = it2.next();\n\t\t\tf.writeln(\"T \" + n);\n\t\t}\n\t\tf.writeln(\"END\");\n\t\tf.writeln();\n\t\tf.writeln(\"EOF\");\n\n\t\tf.closeWrite();\n\t}\n}", "public class FileManager {\n\n\tprivate FileWriter fw;\n\tprivate BufferedReader br;\n\n\t/**\n\t * Create a new FileManager. It can be associated with any file in order to\n\t * read it, erase it or write in it.\n\t * \n\t * @see #openErase(String)\n\t * @see #openRead(String)\n\t * @see #openWrite(String)\n\t */\n\tpublic FileManager() {\n\t}\n\n\t/**\n\t * Open the file which path is path in order to read it. One can then use\n\t * the {@link #readLine()} method to read the file line by line. The file\n\t * should be closed when the reading is finished.\n\t * \n\t * @param path\n\t * @see #readLine()\n\t * @see #closeRead()\n\t */\n\tpublic void openRead(String path) {\n\t\ttry {\n\t\t\tbr = new BufferedReader(new FileReader(path));\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * @return the next line of a file, previously opened with method\n\t * {@link #openRead(String)}. Returns null if no file was opened or\n\t * if every lines of the file were read.\n\t * @see #openRead(String)\n\t */\n\tpublic String readLine() {\n\t\ttry {\n\t\t\treturn br.readLine();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Open the file which path is path in order to write in it. One can then\n\t * use the {@link #write(String)}, {@link #writeln()} or\n\t * {@link #writeln(String)} methods to insert text at the end of the file.\n\t * The previous content of the file is not erased. The file should be closed\n\t * with {@link #closeWrite()} when writing is finished. Notice that while\n\t * the file is not closed, its content is not modified. <br/>\n\t * One can flush the FileManager using {@link #flush()} method in order to\n\t * put the new content into the file before closing it. <br/>\n\t * In order to erase the content, use {@link #openErase(String)} method.\n\t * \n\t * @param path\n\t * @see #write(String)\n\t * @see #writeln()\n\t * @see #writeln(String)\n\t * @see #openErase(String)\n\t * @see #closeWrite()\n\t * @see #flush()\n\t */\n\tpublic void openWrite(String path) {\n\t\ttry {\n\t\t\tfw = new FileWriter(path, true);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Open the file which path is path in order to erase it and replace its\n\t * content. One can then use the {@link #write(String)}, {@link #writeln()}\n\t * or {@link #writeln(String)} methods to insert text at the end of the\n\t * file. The file should be closed when writing is finished. Notice that\n\t * when the FileManager opens the file with this method, the content is\n\t * immediately erased. But while the file is not closed, no new content is\n\t * added. <br/>\n\t * One can flush the FileManager using {@link #flush()} method in order to\n\t * put the new content into the file before closing it. <br/>\n\t * In order to write into the file without erasing the content, use\n\t * {@link #openWrite(String)} method.\n\t * \n\t * @param path\n\t * @see #write(String)\n\t * @see #writeln()\n\t * @see #writeln(String)\n\t * @see #openWrite(String)\n\t * @see #closeWrite()\n\t * @see #flush()\n\t */\n\tpublic void openErase(String path) {\n\t\ttry {\n\n\t\t\tfw = new FileWriter(path, false);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Write at the end of a file, previously opened with\n\t * {@link #openErase(String)} or {@link #openWrite(String)}, the String\n\t * text. Notice that while the file is not closed with {@link #closeWrite()}\n\t * or flush with {@link #flush()}, its content is not modified.\n\t * \n\t * @param text\n\t */\n\tpublic void write(String text) {\n\t\ttry {\n\t\t\tif (fw != null)\n\t\t\t\tfw.write(text);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Write at the end of a file, previously opened with\n\t * {@link #openErase(String)} or {@link #openWrite(String)}, the String text\n\t * and a new line. Notice that while the file is not closed with\n\t * {@link #closeWrite()} or flush with {@link #flush()}, its content is not\n\t * modified.\n\t * \n\t * @param text\n\t */\n\tpublic void writeln(String text) {\n\t\ttry {\n\t\t\tif (fw != null)\n\t\t\t\tfw.write(text + \"\\n\");\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Write at the end of a file, previously opened with\n\t * {@link #openErase(String)} or {@link #openWrite(String)}, a new line.\n\t * Notice that while the file is not closed with {@link #closeWrite()} or\n\t * flush with {@link #flush()}, its content is not modified.\n\t */\n\tpublic void writeln() {\n\t\ttry {\n\t\t\tif (fw != null)\n\t\t\t\tfw.write(\"\\n\");\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Flush the content added to a file, previously opened with\n\t * {@link #openErase(String)} or {@link #openWrite(String)}.\n\t */\n\tpublic void flush() {\n\t\ttry {\n\t\t\tfw.flush();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Close a file, previously opened with {@link #openRead(String)}.\n\t */\n\tpublic void closeRead() {\n\t\ttry {\n\t\t\tif (br != null)\n\t\t\t\tbr.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Close a file, previously opened with {@link #openWrite(String)} or\n\t * {@link #openErase(String)}. This content added with\n\t * {@link #write(String)} {@link #writeln()} or {@link #writeln(String)} is\n\t * flushed into the file.\n\t */\n\tpublic void closeWrite() {\n\t\ttry {\n\t\t\tif (fw != null)\n\t\t\t\tfw.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}" ]
import graphTheory.graph.Arc; import graphTheory.instances.steiner.classic.SteinerUndirectedInstance; import graphTheory.steinLib.STPTranslationException; import graphTheory.steinLib.STPTranslator; import graphTheory.utils.FileManager; import java.io.File; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern;
package graphTheory.generators.steinLib; /** * * This generator generated Undirected Steiner Instances from an STP file. * The format is described at http://steinlib.zib.de/ * * @author Watel Dimitri * */ public class STPUndirectedGenerator extends STPGenerator<SteinerUndirectedInstance> { public STPUndirectedGenerator() { this(null, null); } public STPUndirectedGenerator(String instancesDirectoryName, String resultsFileName) { super(instancesDirectoryName, resultsFileName); } @Override public SteinerUndirectedInstance generate() { File f = instanceFiles[index]; Pattern p = Pattern.compile("((\\w|-)+)\\.stp"); Matcher m = p.matcher(f.getName()); Integer optValue = null; String opt = null; if (m.matches()) { String name = m.group(1); if (resultsFileName != null) { FileManager fm = new FileManager(); fm.openRead(resultsFileName); String ligne; optValue = 0; for (int i = 0; i <= index; i++) { ligne = fm.readLine(); p = Pattern.compile("((\\w|-)+) (\\d+)(.*)"); m = p.matcher(ligne); if (m.matches()) { if (m.group(1).equals(name)) { optValue = Integer.valueOf(m.group(3)); opt = m.group(4).trim(); break; } } else return null; } } SteinerUndirectedInstance sug = null; try { sug = STPTranslator.translateUndirectedFile(f.getPath()); sug.getGraph().defineParam(OUTPUT_NAME_PARAM_NAME, name); if (optValue == null) optValue = -1; sug.getGraph().defineParam(OUTPUT_OPTIMUM_VALUE_PARAM_NAME, optValue); HashSet<Arc> arborescence = null; if (opt != null && !opt.equals("")) { opt = opt.trim(); opt = opt.substring(1, opt.length() - 1); String[] arcs = opt.split(", "); arborescence = new HashSet<Arc>(); for (String arc : arcs) arborescence.add(Arc.valueOf(arc)); } sug.getGraph().defineParam(OUTPUT_OPTIMUM_PARAM_NAME, arborescence); incrIndex();
} catch (STPTranslationException e) {
2
ccjeng/News
app/src/main/java/com/ccjeng/news/view/NewsCategory.java
[ "public class Analytics {\n\n\n public static void trackerPage(Activity activity) {\n Tracker t = ((BaseApplication) activity.getApplication()).getTracker(\n BaseApplication.TrackerName.APP_TRACKER);\n t.setScreenName(activity.getClass().getSimpleName());\n t.send(new HitBuilders.AppViewBuilder().build());\n }\n\n public static void trackEvent(Activity activity\n , String category, String action, String label, long value) {\n Tracker t = ((BaseApplication) activity.getApplication()).getTracker(\n BaseApplication.TrackerName.APP_TRACKER);\n t.send(new HitBuilders.EventBuilder()\n .setCategory(category)\n .setAction(action)\n .setLabel(label)\n .setValue(value)\n .build());\n }\n\n\n}", "public class Category {\n\n private Context context;\n\n public Category(Context context) {\n this.context = context;\n }\n\n public String[] getCategory(String tab, int position) {\n String[] category = null;\n\n if (tab.equals(\"TW\")) {\n switch (position) {\n case 0:\n category = context.getResources().getStringArray(R.array.newscatsCNA);\n break;\n case 1:\n category = context.getResources().getStringArray(R.array.newscatsYahoo);\n break;\n case 2:\n category = context.getResources().getStringArray(R.array.newscatsUDN);\n break;\n case 3:\n category = context.getResources().getStringArray(R.array.newscatsUDNFN);\n break;\n case 4:\n category = context.getResources().getStringArray(R.array.newscatsChinaTimes);\n break;\n case 5:\n category = context.getResources().getStringArray(R.array.newscatsCommercial);\n break;\n case 6:\n category = context.getResources().getStringArray(R.array.newscatsWant);\n break;\n case 7:\n category = context.getResources().getStringArray(R.array.newscatsStorm);\n break;\n case 8:\n category = context.getResources().getStringArray(R.array.newscatsEttoday);\n break;\n case 9:\n category = context.getResources().getStringArray(R.array.newscatsCNYes);\n break;\n case 10:\n category = context.getResources().getStringArray(R.array.newscatsNewsTalk);\n break;\n case 11:\n category = context.getResources().getStringArray(R.array.newscatsLibertyTimes);\n break;\n case 12:\n category = context.getResources().getStringArray(R.array.newscatsAppDaily);\n break;\n case 13:\n category = context.getResources().getStringArray(R.array.newscatsAppDailyRT);\n break;\n case 14:\n category = context.getResources().getStringArray(R.array.newsCatsTheNewsLens);\n break;\n }\n } else if (tab.equals(\"HK\")) {\n switch (position) {\n case 0:\n category = context.getResources().getStringArray(R.array.newscatsHKAppleDaily);\n break;\n case 1:\n category = context.getResources().getStringArray(R.array.newscatsHKAppleDailyRT);\n break;\n case 2:\n category = context.getResources().getStringArray(R.array.newscatsHKOrientalDaily);\n break;\n case 3:\n //category = context.getResources().getStringArray(R.array.newscatsHKYahoo);\n //break;\n //case 4:\n category = context.getResources().getStringArray(R.array.newscatsHKEJ);\n break;\n case 4:\n category = context.getResources().getStringArray(R.array.newscatsHKMetro);\n break;\n case 5:\n category = context.getResources().getStringArray(R.array.newscatsHKam730);\n break;\n case 6:\n category = context.getResources().getStringArray(R.array.newscatsHKheadline);\n break;\n case 7:\n category = context.getResources().getStringArray(R.array.newscatsETNet);\n break;\n case 8:\n category = context.getResources().getStringArray(R.array.newscatsTheStandNews);\n break;\n case 9:\n category = context.getResources().getStringArray(R.array.newscatsInMediaHK);\n break;\n }\n } else if (tab.equals(\"SG\")) {\n switch (position) {\n case 0:\n category = context.getResources().getStringArray(R.array.newscatsZaobao);\n break;\n case 1:\n category = context.getResources().getStringArray(R.array.newscatsDaliulian);\n break;\n case 2:\n category = context.getResources().getStringArray(R.array.newscatsKwongwah);\n break;\n case 3:\n category = context.getResources().getStringArray(R.array.newscatsGuangming);\n break;\n }\n }\n\n return category;\n }\n\n public String[] getFeedURL(String tab, int position) {\n String[] feedURL = null;\n\n if (tab.equals(\"TW\")) {\n switch (position) {\n case 0:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsCNA);\n break;\n case 1:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsYahoo);\n break;\n case 2:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsUDN);\n break;\n case 3:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsUDNFN);\n break;\n case 4:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsChinaTimes);\n break;\n case 5:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsCommercial);\n break;\n case 6:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsWant);\n break;\n case 7:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsStorm);\n break;\n case 8:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsEttoday);\n break;\n case 9:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsCNYes);\n break;\n case 10:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsNewsTalk);\n break;\n case 11:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsLibertyTimes);\n break;\n case 12:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsAppDaily);\n break;\n case 13:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsAppDailyRT);\n break;\n case 14:\n feedURL = context.getResources().getStringArray(R.array.newsFeedsTheNewsLens);\n break;\n }\n } else if (tab.equals(\"HK\")) {\n switch (position) {\n case 0:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKAppleDaily);\n break;\n case 1:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKAppleDailyRT);\n break;\n case 2:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKOrientalDaily);\n break;\n case 3:\n //feedURL = context.getResources().getStringArray(R.array.newsfeedsHKYahoo);\n //break;\n //case 4:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKEJ);\n break;\n case 4:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKMetro);\n break;\n case 5:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKam730);\n break;\n case 6:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsHKheadline);\n break;\n case 7:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsETNet);\n break;\n case 8:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsTheStandNews);\n break;\n case 9:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsInMediaHK);\n break;\n }\n } else if (tab.equals(\"SG\")) {\n switch (position) {\n case 0:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsZaobao);\n break;\n case 1:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsDaliulian);\n break;\n case 2:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsKwongwah);\n break;\n case 3:\n feedURL = context.getResources().getStringArray(R.array.newsfeedsGuangming);\n break;\n }\n }\n\n return feedURL;\n }\n\n public AbstractNews getNewsParser(String tab, int position) {\n AbstractNews parser = null;\n\n if (tab.equals(\"TW\")) {\n switch (position) {\n case 0:\n parser = new CNA();\n break;\n case 1:\n parser = new Yahoo();\n break;\n case 2:\n case 3:\n parser = new UDN();\n break;\n case 4:\n case 5:\n case 6:\n parser = new ChinaTimes();\n break;\n case 7:\n parser = new Storm();\n break;\n case 8:\n parser = new ETToday();\n break;\n case 9:\n parser = new CNYes();\n break;\n case 10:\n parser = new NewTalk();\n break;\n case 11:\n parser = new LibertyTimes();\n break;\n case 12:\n case 13:\n parser = new AppleDaily();\n break;\n case 14:\n parser = new TheNewsLens();\n break;\n }\n } else if (tab.equals(\"HK\")) {\n switch (position) {\n case 0:\n case 1:\n parser = new HKAppleDaily();\n break;\n case 2:\n parser = new OrientalDaily();\n break;\n case 3:\n // parser = new HKYahoo();\n // break;\n //case 4:\n parser = new HKEJ();\n break;\n case 4:\n parser = new RTHK();\n break;\n case 5:\n parser = new AM730();\n break;\n case 6:\n parser = new HKHeadline();\n break;\n case 7:\n parser = new ETNet();\n break;\n case 8:\n parser = new TheStandNews();\n break;\n case 9:\n parser = new InMediaHK();\n break;\n }\n } else if (tab.equals(\"SG\")) {\n switch (position) {\n case 0:\n parser = new Zaobao();\n break;\n case 1:\n parser = new Daliulian();\n break;\n case 2:\n parser = new Kwongwah();\n break;\n case 3:\n parser = new Guangming();\n break;\n }\n }\n\n return parser;\n }\n\n public static String getEncoding(String tab, int position) {\n String encoding = \"utf-8\";\n\n if (tab.equals(\"HK\")) {\n\n /*\n switch (position) {\n case 6: //HKHeadline\n encoding = \"big-5\";\n break;\n }*/\n }\n\n return encoding;\n }\n\n public static boolean customRSSFeed(String url) {\n\n if (url.contains(\"appledaily\") || // include TW and HK\n url.contains(\"am730.com.hk\") ||\n url.contains(\"twgreatdaily\")) {\n return true;\n } else {\n return false;\n }\n\n }\n}", "public class NewsCategoryAdapter extends RecyclerView.Adapter<NewsCategoryAdapter.CustomViewHolder>{\n\n private String[] mArrayString;\n private Context mContext;\n\n public NewsCategoryAdapter(Context context) {\n this.mContext = context;\n }\n\n public void setData(String[] arrayString) {\n this.mArrayString = arrayString;\n notifyDataSetChanged();\n }\n\n @Override\n public CustomViewHolder onCreateViewHolder(ViewGroup parent, int i) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_item, parent, false);\n\n CustomViewHolder viewHolder = new CustomViewHolder(view);\n\n return viewHolder;\n }\n\n @Override\n public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {\n //Setting text view title\n customViewHolder.textView.setText(mArrayString[i]);\n }\n\n @Override\n public int getItemCount() {\n return (null != mArrayString ? mArrayString.length : 0);\n }\n\n public class CustomViewHolder extends RecyclerView.ViewHolder {\n //protected ImageView imageView;\n protected TextView textView;\n\n public CustomViewHolder(View view) {\n super(view);\n //this.imageView = (ImageView) view.findViewById(R.id.icon);\n this.textView = (TextView) view.findViewById(R.id.row);\n }\n\n }\n}", "public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {\n private OnItemClickListener mListener;\n\n public interface OnItemClickListener {\n public void onItemClick(View view, int position);\n }\n\n GestureDetector mGestureDetector;\n\n public RecyclerItemClickListener(Context context, OnItemClickListener listener) {\n mListener = listener;\n mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {\n @Override\n public boolean onSingleTapUp(MotionEvent e) {\n return true;\n }\n });\n }\n\n @Override\n public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {\n View childView = view.findChildViewUnder(e.getX(), e.getY());\n if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {\n mListener.onItemClick(childView, view.getChildAdapterPosition(childView));\n }\n return false;\n }\n\n @Override\n public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {\n }\n\n @Override\n public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {\n\n }\n}", "public class BaseActivity extends SwipeBackActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getSwipeBackLayout().setEdgeOrientation(SwipeBackLayout.EDGE_LEFT);\n\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n GoogleAnalytics.getInstance(this).reportActivityStart(this);\n }\n\n @Override\n public void onStop() {\n super.onStop();\n GoogleAnalytics.getInstance(this).reportActivityStop(this);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n finish();\n break;\n }\n\n return super.onOptionsItemSelected(item);\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import com.ccjeng.news.R; import com.ccjeng.news.utils.Analytics; import com.ccjeng.news.utils.Category; import com.ccjeng.news.view.adapter.NewsCategoryAdapter; import com.ccjeng.news.view.adapter.RecyclerItemClickListener; import com.ccjeng.news.view.base.BaseActivity; import butterknife.BindView; import butterknife.ButterKnife;
package com.ccjeng.news.view; public class NewsCategory extends BaseActivity { private static final String TAG = NewsCategory.class.getName(); private Analytics ga; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.recyclerView) RecyclerView recyclerView; //private MoPubView moPubView; private int sourceNumber; private String tabName; private String categoryName; private String[] category; private NewsCategoryAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_category); ButterKnife.bind(this); ga = new Analytics(); ga.trackerPage(this); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } LinearLayoutManager llm = new LinearLayoutManager(this); recyclerView.setLayoutManager(llm); recyclerView.setHasFixedSize(true); adapter = new NewsCategoryAdapter(this); recyclerView.setAdapter(adapter); //get intent values Bundle bunde = this.getIntent().getExtras(); sourceNumber = Integer.parseInt(bunde.getString("SourceNum")); categoryName = bunde.getString("SourceName"); tabName = bunde.getString("SourceTab"); //set toolbar title getSupportActionBar().setTitle(categoryName); showResult(tabName, sourceNumber); //moPubView = (MoPubView) findViewById(R.id.adview); //Network.AdView(moPubView, Constant.Ad_MoPub_Category); ga.trackEvent(this, "Click", "News", categoryName, 0); } @Override protected void onDestroy() { //if (moPubView != null) { // moPubView.destroy(); //} super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } private void showResult(String tabName, int sourceNumber) { Category cat = new Category(this); category = cat.getCategory(tabName, sourceNumber); if (category != null) { adapter.setData(category); recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
3
Archarithms/bigio
core/src/main/java/io/bigio/core/member/MeMember.java
[ "public enum Parameters {\n INSTANCE;\n \n private final Logger LOG;\n private final int MAX_DEPTH;\n private final Properties properties;\n private final FileSystem fileSystem;\n private final Path configDir;\n\n private static OperatingSystem os;\n\n /**\n * Protected constructor.\n */\n Parameters() {\n LOG = LoggerFactory.getLogger(Parameters.class);\n MAX_DEPTH = 10;\n properties = new Properties();\n fileSystem = FileSystems.getDefault();\n configDir = fileSystem.getPath(\"config\");\n \n init();\n }\n\n /**\n * Get a property.\n * \n * @param name the name of the property.\n * @return the property value, or null if the property does not exist.\n */\n public String getProperty(String name) {\n return properties.getProperty(name);\n }\n \n /**\n * Get a property. If the property doesn't exist, the default value will\n * be returned.\n * \n * @param name the name of the property.\n * @param defaultValue the default value of the property.\n * @return the value should the property exist, or the default property \n * if it does not.\n */\n public String getProperty(String name, String defaultValue) {\n return properties.getProperty(name, defaultValue);\n }\n\n /**\n * Set a property.\n * \n * @param name the name of the property.\n * @param value the value of the property.\n */\n public void setProperty(String name, String value) {\n properties.setProperty(name, value);\n }\n\n /**\n * Get the operating system.\n * \n * @return the operating system.\n */\n public OperatingSystem currentOS() {\n return os;\n }\n\n /**\n * Load the configuration.\n */\n private void init() {\n String osName = System.getProperty(\"os.name\");\n String osArch = System.getProperty(\"os.arch\");\n\n if(osName.contains(\"Windows\")) {\n if(osArch.contains(\"amd64\")) {\n os = OperatingSystem.WIN_64;\n } else {\n os = OperatingSystem.WIN_32;\n }\n } else if(osName.contains(\"Linux\")) {\n if(osArch.contains(\"amd64\")) {\n os = OperatingSystem.LINUX_64;\n } else {\n os = OperatingSystem.LINUX_32;\n }\n } else {\n if(osArch.contains(\"amd64\")) {\n os = OperatingSystem.MAC_64;\n } else {\n os = OperatingSystem.MAC_32;\n }\n }\n \n Set<FileVisitOption> options = new TreeSet<>();\n options.add(FileVisitOption.FOLLOW_LINKS);\n\n try {\n if(Files.isDirectory(configDir)) {\n Files.walkFileTree(configDir, options, MAX_DEPTH, new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if(file.getFileName().toString().endsWith(\"properties\")) {\n LOG.debug(\"Loading configuration file '\" + file.toString() + \"'\");\n\n try (BufferedReader in = Files.newBufferedReader(file, Charset.defaultCharset())) {\n properties.load(in);\n }\n }\n\n return FileVisitResult.CONTINUE;\n }\n });\n } else {\n LOG.info(\"Cannot find default configuration directory. Using default configuration values.\");\n }\n } catch(IOException ex) {\n LOG.error(\"Error while loading configuration.\", ex);\n }\n\n properties.entrySet().stream().forEach((entry) -> {\n System.getProperties().setProperty(entry.getKey().toString(), entry.getValue().toString());\n });\n\n System.getProperties().entrySet().stream().forEach((entry) -> {\n properties.setProperty(entry.getKey().toString(), entry.getValue().toString());\n });\n }\n}", "public class Envelope<T> {\n \n private String senderKey;\n private int executeTime;\n private int millisecondsSinceMidnight;\n private String topic;\n private String partition;\n private String className;\n private byte[] payload;\n\n private byte[] key;\n private boolean decoded = false;\n private boolean encrypted = false;\n private T message;\n\n /**\n * @return the senderKey\n */\n public String getSenderKey() {\n return senderKey;\n }\n\n /**\n * @param senderKey the senderKey to set\n */\n public void setSenderKey(String senderKey) {\n this.senderKey = senderKey;\n }\n\n /**\n * @return the executeTime\n */\n public int getExecuteTime() {\n return executeTime;\n }\n\n /**\n * @param executeTime the executeTime to set\n */\n public void setExecuteTime(int executeTime) {\n this.executeTime = executeTime;\n }\n\n /**\n * @return the topic\n */\n public String getTopic() {\n return topic;\n }\n\n /**\n * @param topic the topic to set\n */\n public void setTopic(String topic) {\n this.topic = topic;\n }\n\n /**\n * @return the payload\n */\n public byte[] getPayload() {\n return payload;\n }\n\n /**\n * @param payload the payload to set\n */\n public void setPayload(byte[] payload) {\n this.payload = payload;\n }\n\n /**\n * @return the decoded\n */\n public boolean isDecoded() {\n return decoded;\n }\n\n /**\n * @param decoded the decoded to set\n */\n public void setDecoded(boolean decoded) {\n this.decoded = decoded;\n }\n\n /**\n * @return the message\n */\n public T getMessage() {\n return message;\n }\n\n /**\n * @param message the message to set\n */\n public void setMessage(T message) {\n this.message = message;\n }\n\n /**\n * @return the millisecondsSinceMidnight\n */\n public int getMillisecondsSinceMidnight() {\n return millisecondsSinceMidnight;\n }\n\n /**\n * @param millisecondsSinceMidnight the millisecondsSinceMidnight to set\n */\n public void setMillisecondsSinceMidnight(int millisecondsSinceMidnight) {\n this.millisecondsSinceMidnight = millisecondsSinceMidnight;\n }\n\n /**\n * @return the className\n */\n public String getClassName() {\n return className;\n }\n\n /**\n * @param className the className to set\n */\n public void setClassName(String className) {\n this.className = className;\n }\n\n /**\n * @return the partition\n */\n public String getPartition() {\n return partition;\n }\n\n /**\n * @param partition the partition to set\n */\n public void setPartition(String partition) {\n this.partition = partition;\n }\n\n /**\n * @return the encrypted\n */\n public boolean isEncrypted() {\n return encrypted;\n }\n\n /**\n * @param encrypted the encrypted to set\n */\n public void setEncrypted(boolean encrypted) {\n this.encrypted = encrypted;\n }\n\n /**\n * @return the key\n */\n public byte[] getKey() {\n return key;\n }\n\n /**\n * @param key the key to set\n */\n public void setKey(byte[] key) {\n this.key = key;\n }\n}", "public interface GossipListener {\n\n /**\n * Receive a gossip message.\n * \n * @param message a gossip message.\n */\n public void accept(GossipMessage message);\n}", "public class GossipMessage {\n\n private String ip;\n private int gossipPort;\n private int dataPort;\n private int millisecondsSinceMidnight;\n private byte[] publicKey = null;\n private final Map<String, String> tags = new HashMap<>();\n private final List<String> members = new ArrayList<>();\n private final List<Integer> clock = new ArrayList<>();\n private final Map<String, List<String>> listeners = new HashMap<>();\n\n /**\n * Default constructor.\n */\n public GossipMessage() {\n \n }\n\n /**\n * Constructor with sender's information.\n * \n * @param ip the IP address of the sender.\n * @param gossipPort the gossip port of the sender.\n * @param dataPort the data port of the sender.\n */\n public GossipMessage(String ip, int gossipPort, int dataPort) {\n this.ip = ip;\n this.gossipPort = gossipPort;\n this.dataPort = dataPort;\n }\n\n /**\n * Produce a nice textual representation of the message.\n * \n * @return the message as a string.\n */\n @Override\n public String toString() {\n StringBuilder buff = new StringBuilder();\n buff.append(\"GossipMessage: \").append(\"\\n\")\n .append(\"Address: \").append(getIp()).append(\"\\n\")\n .append(\"GossipPort: \").append(getGossipPort()).append(\"\\n\")\n .append(\"DataPort: \").append(getDataPort()).append(\"\\n\")\n .append(\"Time: \").append(getMillisecondsSinceMidnight()).append(\"\\n\")\n .append(\"Tags: \").append(\"\\n\");\n getTags().keySet().stream().forEach((key) -> {\n buff.append(\" \").append(key).append(\" -> \").append(getTags().get(key)).append(\"\\n\");\n });\n buff.append(\"Members: \").append(\"\\n\");\n for(int i = 0; i < getMembers().size(); ++i) {\n buff.append(\" \").append(getMembers().get(i)).append(\" -- \").append(getClock().get(i)).append(\"\\n\");\n }\n buff.append(\"Listeners: \").append(\"\\n\");\n getListeners().keySet().stream().map((key) -> {\n buff.append(\" \").append(key).append(\"\\n\");\n return key;\n }).forEach((key) -> {\n getListeners().get(key).stream().forEach((topic) -> {\n buff.append(\" \").append(topic).append(\"\\n\");\n });\n });\n return buff.toString();\n }\n\n /**\n * @return the ip\n */\n public String getIp() {\n return ip;\n }\n\n /**\n * @param ip the ip to set\n */\n public void setIp(String ip) {\n this.ip = ip;\n }\n\n /**\n * @return the gossipPort\n */\n public int getGossipPort() {\n return gossipPort;\n }\n\n /**\n * @param gossipPort the gossipPort to set\n */\n public void setGossipPort(int gossipPort) {\n this.gossipPort = gossipPort;\n }\n\n /**\n * @return the tags\n */\n public Map<String, String> getTags() {\n return tags;\n }\n\n /**\n * @return the dataPort\n */\n public int getDataPort() {\n return dataPort;\n }\n\n /**\n * @param dataPort the dataPort to set\n */\n public void setDataPort(int dataPort) {\n this.dataPort = dataPort;\n }\n\n /**\n * @return the members\n */\n public List<String> getMembers() {\n return members;\n }\n\n /**\n * @return the listeners\n */\n public Map<String, List<String>> getListeners() {\n return listeners;\n }\n\n /**\n * @return the millisecondsSinceMidnight\n */\n public int getMillisecondsSinceMidnight() {\n return millisecondsSinceMidnight;\n }\n\n /**\n * @return the clock\n */\n public List<Integer> getClock() {\n return clock;\n }\n\n /**\n * @param millisecondsSinceMidnight the millisecondsSinceMidnight to set\n */\n public void setMillisecondsSinceMidnight(int millisecondsSinceMidnight) {\n this.millisecondsSinceMidnight = millisecondsSinceMidnight;\n }\n\n /**\n * @return the publicKey\n */\n public byte[] getPublicKey() {\n return publicKey;\n }\n\n /**\n * @param publicKey the publicKey to set\n */\n public void setPublicKey(byte[] publicKey) {\n this.publicKey = publicKey;\n }\n}", "@Component\npublic class ListenerRegistry {\n\n private static final int THREAD_POOL_SIZE = 8;\n\n private static final Logger LOG = LoggerFactory.getLogger(ListenerRegistry.class);\n \n private final Environment environment = new Environment();\n private final Reactor reactor;\n\n private final ScheduledExecutorService futureExecutor = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);\n\n private Member me;\n\n private final Map<Member, Map<String, List<Registration>>> map = new ConcurrentHashMap<>();\n\n private final Map<String, List<Interceptor>> interceptors = new ConcurrentHashMap<>();\n\n /**\n * Constructor.\n */\n public ListenerRegistry() {\n reactor = Reactors.reactor()\n .env(environment)\n .dispatcher(Environment.RING_BUFFER)\n .get();\n }\n\n /**\n * Add a topic interceptor.\n * \n * @param topic a topic.\n * @param interceptor an interceptor.\n */\n public void addInterceptor(String topic, Interceptor interceptor) {\n if(interceptors.get(topic) == null) {\n interceptors.put(topic, new ArrayList<>());\n }\n interceptors.get(topic).add(interceptor);\n }\n\n /**\n * Set the current member.\n * \n * @param me the current member.\n */\n public void setMe(Member me) {\n this.me = me;\n }\n\n /**\n * Get the current member.\n * @return the current member.\n */\n public Member getMe() {\n return me;\n }\n\n /**\n * Add a listener that is located in the same VM as the current member.\n * \n * @param <T> a message type.\n * @param topic a topic.\n * @param partition a partition.\n * @param listener a listener.\n */\n public <T> void addLocalListener(final String topic, final String partition, final MessageListener<T> listener) {\n Consumer<Event<Envelope>> consumer = (Event<Envelope> m) -> {\n try {\n listener.receive((T)m.getData().getMessage());\n } catch(ClassCastException ex) {\n LOG.error(\"Topic '\" + topic + \"' received incorrect message type : \" + m.getData().getMessage().getClass().getName(), ex);\n } catch(Exception ex) {\n LOG.error(\"Exception in Reactor.\", ex);\n }\n };\n\n reactor.on(Selectors.regex(TopicUtils.getTopicString(topic, partition)), consumer);\n }\n\n /**\n * Remove all local listeners on a given topic.\n * \n * @param topic a topic.\n * @param partition\n */\n public void removeAllLocalListeners(String topic, String partition) {\n Map<String, List<Registration>> allRegs = map.get(me);\n \n if(allRegs != null) {\n List<Registration> regs = allRegs.get(topic);\n\n if(regs != null) {\n LOG.trace(\"Removing \" + regs.size() + \" registration\");\n reactor.getConsumerRegistry().unregister(Selectors.regex(TopicUtils.getTopicString(topic, partition)));\n regs.clear();\n } else {\n LOG.trace(\"No listeners registered for topic \" + topic);\n }\n }\n }\n\n /**\n * Remove topic/partition registrations. \n * \n * @param regs a set of registrations.\n */\n public void removeRegistrations(List<Registration> regs) {\n map.values().stream().filter((allRegs) -> (allRegs != null)).forEach((allRegs) -> {\n allRegs.keySet().stream().forEach((key) -> {\n allRegs.get(key).removeAll(regs);\n });\n });\n }\n\n /**\n * Get all topic/partition registrations. \n * \n * @return the list of all registrations.\n */\n public List<Registration> getAllRegistrations() {\n List<Registration> ret = new ArrayList<>();\n \n map.values().stream().filter((allRegs) -> (allRegs != null)).forEach((allRegs) -> {\n allRegs.keySet().stream().forEach((key) -> {\n ret.addAll(allRegs.get(key));\n });\n });\n\n return ret;\n }\n\n /**\n * Get all members that have at least one listener registered for a given \n * topic.\n * \n * @param topic a topic.\n * @return all members that have at least one registered listener.\n */\n public List<Member> getRegisteredMembers(String topic) {\n List<Member> ret = new ArrayList<>();\n\n map.keySet().stream().forEach((member) -> {\n Map<String, List<Registration>> allRegs = map.get(member);\n if (allRegs != null) {\n allRegs.keySet().stream().filter((key) -> (key.equals(topic))).forEach((_item) -> {\n ret.add(member);\n });\n }\n });\n\n return ret;\n }\n\n /**\n * Register a member for a topic-partition.\n * \n * @param topic a topic.\n * @param partition a partition.\n * @param member a member.\n */\n protected synchronized void registerMemberForTopic(String topic, String partition, Member member) {\n\n if(map.get(member) == null) {\n map.put(member, new ConcurrentHashMap<>());\n }\n\n if(map.get(member).get(topic) == null) {\n map.get(member).put(topic, new ArrayList<>());\n }\n\n boolean found = false;\n for(Registration reg : map.get(member).get(topic)) {\n if(topic.equals(reg.getTopic()) && partition.equals(reg.getPartition()) && member.equals(reg.getMember())) {\n found = true;\n break;\n }\n }\n\n if(!found) {\n Registration reg = new Registration(member, topic, partition);\n map.get(member).get(topic).add(reg);\n\n if(LOG.isTraceEnabled()) {\n LOG.trace(new StringBuilder()\n .append(MemberKey.getKey(me))\n .append(\": Registering member '\")\n .append(MemberKey.getKey(member))\n .append(\"' for topic '\")\n .append(topic)\n .append(\"' on partition '\")\n .append(partition)\n .append(\"'\").toString());\n }\n }\n }\n\n /**\n * Send a message.\n * \n * @param envelope a message envelope.\n * @throws IOException in case of a sending error.\n */\n public void send(Envelope envelope) throws IOException {\n if(interceptors.containsKey(envelope.getTopic())) {\n for(Interceptor interceptor : interceptors.get(envelope.getTopic())) {\n envelope = interceptor.intercept(envelope);\n }\n }\n\n if(envelope.getExecuteTime() > 0) {\n final Envelope env = envelope;\n futureExecutor.schedule(() -> {\n reactor.notify(TopicUtils.getNotifyTopicString(env.getTopic(), env.getPartition()), Event.wrap(env));\n }, envelope.getExecuteTime(), TimeUnit.MILLISECONDS);\n } else if(envelope.getExecuteTime() >= 0) {\n reactor.notify(TopicUtils.getNotifyTopicString(envelope.getTopic(), envelope.getPartition()), Event.wrap(envelope));\n }\n }\n}", "public class EnvelopeCodec {\n \n private static final MessagePack msgPack = new MessagePack();\n\n private EnvelopeCodec() {\n\n }\n\n /**\n * Decode a message envelope.\n * \n * @param bytes the raw message.\n * @return the decoded message.\n * @throws IOException in case of a decode error.\n */\n public static Envelope decode(ByteBuf bytes) throws IOException {\n MessageUnpacker unpacker = msgPack.newUnpacker(new ByteBufInputStream(bytes));\n Envelope message = decode(unpacker);\n return message;\n }\n \n /**\n * Decode a message envelope.\n * \n * @param bytes the raw message.\n * @return the decoded message.\n * @throws IOException in case of a decode error.\n */\n public static Envelope decode(byte[] bytes) throws IOException {\n MessageUnpacker unpacker = msgPack.newUnpacker(bytes);\n Envelope message = decode(unpacker);\n return message;\n }\n\n /**\n * Decode a message envelope.\n * \n * @param unpacker a MsgPack object containing the raw message.\n * @return the decoded message.\n * @throws IOException in case of a decode error.\n */\n private static Envelope decode(MessageUnpacker unpacker) throws IOException {\n\n Envelope message = new Envelope();\n\n StringBuilder keyBuilder = new StringBuilder();\n keyBuilder\n .append(unpacker.unpackInt())\n .append(\".\")\n .append(unpacker.unpackInt())\n .append(\".\")\n .append(unpacker.unpackInt())\n .append(\".\")\n .append(unpacker.unpackInt())\n .append(\":\")\n .append(unpacker.unpackInt())\n .append(\":\")\n .append(unpacker.unpackInt());\n message.setSenderKey(keyBuilder.toString());\n message.setEncrypted(unpacker.unpackBoolean());\n if(message.isEncrypted()) {\n int length = unpacker.unpackArrayHeader();\n byte[] key = new byte[length];\n for(int i = 0; i < length; ++i) {\n key[i] = unpacker.unpackByte();\n }\n message.setKey(key);\n }\n message.setExecuteTime(unpacker.unpackInt());\n message.setMillisecondsSinceMidnight(unpacker.unpackInt());\n message.setTopic(unpacker.unpackString());\n message.setPartition(unpacker.unpackString());\n message.setClassName(unpacker.unpackString());\n\n if(unpacker.getNextFormat() == MessageFormat.BIN16 || \n unpacker.getNextFormat() == MessageFormat.BIN32 || \n unpacker.getNextFormat() == MessageFormat.BIN8) {\n int length = unpacker.unpackBinaryHeader();\n byte[] payload = new byte[length];\n unpacker.readPayload(payload);\n message.setPayload(payload);\n } else {\n int length = unpacker.unpackArrayHeader();\n byte[] payload = new byte[length];\n for(int i = 0; i < length; ++i) {\n payload[i] = unpacker.unpackByte();\n }\n message.setPayload(payload);\n }\n\n return message;\n }\n\n /**\n * Encode a message envelope.\n * \n * @param message a message to encode.\n * @return the encoded message.\n * @throws IOException in case of an encode error.\n */\n public static byte[] encode(Envelope message) throws IOException {\n ByteArrayOutputStream msgBuffer = new ByteArrayOutputStream();\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n \n MessagePacker packer = msgPack.newPacker(msgBuffer);\n\n String[] keys = message.getSenderKey().split(\":\");\n String[] ip = keys[0].split(\"\\\\.\");\n packer.packInt(Integer.parseInt(ip[0]));\n packer.packInt(Integer.parseInt(ip[1]));\n packer.packInt(Integer.parseInt(ip[2]));\n packer.packInt(Integer.parseInt(ip[3]));\n packer.packInt(Integer.parseInt(keys[1]));\n packer.packInt(Integer.parseInt(keys[2]));\n\n packer.packBoolean(message.isEncrypted());\n if(message.isEncrypted()) {\n packer.packArrayHeader(message.getKey().length);\n for(byte b : message.getKey()) {\n packer.packByte(b);\n }\n }\n packer.packInt(message.getExecuteTime());\n packer.packInt(message.getMillisecondsSinceMidnight());\n packer.packString(message.getTopic());\n packer.packString(message.getPartition());\n packer.packString(message.getClassName());\n packer.packArrayHeader(message.getPayload().length);\n for(byte b : message.getPayload()) {\n packer.packByte(b);\n }\n\n packer.close();\n\n out.write((short)msgBuffer.size() >>> 8);\n out.write((short)msgBuffer.size());\n msgBuffer.writeTo(out);\n\n return out.toByteArray();\n }\n}", "public class GenericCodec {\n\n private static final Logger LOG = LoggerFactory.getLogger(GenericCodec.class);\n\n private GenericCodec() {\n \n }\n\n /**\n * Decode a message payload.\n * \n * @param className the type of message.\n * @param bytes the raw message.\n * @return a decoded message.\n * @throws IOException in case of a decoding error.\n */\n public static Object decode(String className, byte[] bytes) throws IOException {\n\n try {\n Class clazz = Class.forName(className);\n\n if(clazz.getAnnotation(io.bigio.Message.class) != null) {\n try {\n Object obj = clazz.newInstance();\n ((BigIOMessage)obj).bigiodecode(bytes);\n return obj;\n } catch (IllegalAccessException ex) {\n LOG.error(\"Illegal method access.\", ex);\n } catch (InstantiationException ex) {\n LOG.error(\"Cannot create new message.\", ex);\n }\n }\n } catch(ClassNotFoundException ex) {\n LOG.error(\"Cannot find message type\", ex);\n }\n\n return null;\n }\n\n /**\n * Encode a message payload.\n * \n * @param message a message.\n * @return the encoded form of the message.\n * @throws IOException in case of an error in encoding.\n */\n public static byte[] encode(Object message) throws IOException {\n\n if(message.getClass().getAnnotation(io.bigio.Message.class) != null) {\n try {\n byte[] ret;\n ret = (byte[])((BigIOMessage)message).bigioencode();\n return ret;\n } catch (Exception ex) {\n LOG.error(\"Exception serializing.\", ex);\n }\n }\n\n return null;\n }\n}" ]
import io.bigio.Parameters; import io.bigio.core.Envelope; import io.bigio.core.GossipListener; import io.bigio.core.GossipMessage; import io.bigio.core.ListenerRegistry; import io.bigio.core.codec.EnvelopeCodec; import io.bigio.core.codec.GenericCodec; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.msgpack.core.MessageTypeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Environment; import reactor.core.Reactor; import reactor.core.spec.Reactors; import reactor.event.Event; import reactor.event.selector.Selectors;
/* * Copyright (c) 2015, Archarithms Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package io.bigio.core.member; /** * A representation of the current BigIO cluster member. * * @author Andy Trimble */ public abstract class MeMember extends AbstractMember { private static final Logger LOG = LoggerFactory.getLogger(MeMember.class); public static final String ENCRYPTION_PROPERTY = "io.bigio.encryption"; private static final String DEFAULT_ENCRYPTION = "false"; protected static final String GOSSIP_TOPIC = "__gossiper"; protected static final String DECODE_TOPIC = "__decoder"; private final Environment env = new Environment(); protected Reactor reactor; protected Reactor decoderReactor; protected ListenerRegistry registry; private Cipher symmetricCipher = null; private Cipher rsaCipher = null; private KeyPair keyPair = null; public MeMember(MemberHolder memberHolder, ListenerRegistry registry) { super(memberHolder); this.registry = registry; } public MeMember(String ip, int gossipPort, int dataPort, MemberHolder memberHolder, ListenerRegistry registry) { super(ip, gossipPort, dataPort, memberHolder); this.registry = registry; } protected abstract void initializeServers();
public void addGossipConsumer(final GossipListener consumer) {
2
hiBrianLee/AndroidMvvm
sample/src/main/java/com/hibrianlee/sample/mvvm/adapter/AndroidVersionsAdapter.java
[ "public abstract class RecyclerViewAdapter<ITEM_T, VIEW_MODEL_T extends ItemViewModel<ITEM_T>>\n extends RecyclerView.Adapter<RecyclerViewAdapter.ItemViewHolder<ITEM_T, VIEW_MODEL_T>> {\n\n protected final ArrayList<ITEM_T> items;\n\n private final ActivityComponent activityComponent;\n\n public RecyclerViewAdapter(@NonNull ActivityComponent activityComponent) {\n this.activityComponent = activityComponent;\n items = new ArrayList<>();\n }\n\n @Override\n public final void onBindViewHolder(ItemViewHolder<ITEM_T, VIEW_MODEL_T> holder, int position) {\n holder.setItem(items.get(position));\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n protected final ActivityComponent getActivityComponent() {\n return activityComponent;\n }\n\n public static class ItemViewHolder<T, VT extends ItemViewModel<T>>\n extends RecyclerView.ViewHolder {\n\n protected final VT viewModel;\n private final ViewDataBinding binding;\n\n public ItemViewHolder(View itemView, ViewDataBinding binding, VT viewModel) {\n super(itemView);\n this.binding = binding;\n this.viewModel = viewModel;\n }\n\n void setItem(T item) {\n viewModel.setItem(item);\n binding.executePendingBindings();\n }\n }\n}", "@PerActivity\n@Component(\n dependencies = AppComponent.class,\n modules = {ActivityModule.class})\npublic interface ActivityComponent {\n\n void inject(ViewModel viewModel);\n}", "public class AndroidVersion implements Parcelable {\n\n private final String codeName;\n private final String version;\n private boolean selected;\n\n public AndroidVersion(String codeName, String version) {\n this.codeName = codeName;\n this.version = version;\n }\n\n public AndroidVersion(Parcel in) {\n codeName = in.readString();\n version = in.readString();\n selected = in.readInt() == 1;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(codeName);\n dest.writeString(version);\n dest.writeInt(selected ? 1 : 0);\n }\n\n public String getCodeName() {\n return codeName;\n }\n\n public String getVersion() {\n return version;\n }\n\n public boolean isSelected() {\n return selected;\n }\n\n public void toggleSelected() {\n selected = !selected;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AndroidVersion that = (AndroidVersion) o;\n\n if (selected != that.selected) return false;\n if (codeName != null ? !codeName.equals(that.codeName) : that.codeName != null)\n return false;\n return !(version != null ? !version.equals(that.version) : that.version != null);\n\n }\n\n @Override\n public int hashCode() {\n int result = codeName != null ? codeName.hashCode() : 0;\n result = 31 * result + (version != null ? version.hashCode() : 0);\n result = 31 * result + (selected ? 1 : 0);\n return result;\n }\n\n public static Creator<AndroidVersion> CREATOR = new Creator<AndroidVersion>() {\n @Override\n public AndroidVersion createFromParcel(Parcel source) {\n return new AndroidVersion(source);\n }\n\n @Override\n public AndroidVersion[] newArray(int size) {\n return new AndroidVersion[size];\n }\n };\n}", "public class AndroidVersionItemViewModel extends ItemViewModel<AndroidVersion> {\n\n private AndroidVersion androidVersion;\n\n AndroidVersionItemViewModel(@NonNull ActivityComponent activityComponent) {\n super(activityComponent);\n }\n\n @Override\n public void setItem(AndroidVersion item) {\n androidVersion = item;\n notifyChange();\n }\n\n public void onClick() {\n androidVersion.toggleSelected();\n notifyPropertyChanged(BR.selected);\n }\n\n @Bindable\n public String getVersion() {\n return androidVersion.getVersion();\n }\n\n @Bindable\n public String getCodeName() {\n return androidVersion.getCodeName();\n }\n\n @Bindable\n public boolean getSelected() {\n return androidVersion.isSelected();\n }\n}", "public interface ViewModelFactory {\n\n @NonNull\n MainViewModel createMainViewModel(@NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n @NonNull\n ClickCountViewModel createClickCountViewModel(@NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n\n @NonNull\n AndroidVersionsViewModel createAndroidVersionsViewModel(\n @NonNull AndroidVersionsAdapter adapter,\n @NonNull ActivityComponent activityComponent,\n @Nullable ViewModel.State savedViewModelState);\n\n @NonNull\n AndroidVersionItemViewModel createAndroidVersionItemViewModel(\n @NonNull ActivityComponent activityComponent);\n}" ]
import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.OnClick; import android.databinding.ViewDataBinding; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hibrianlee.mvvmapp.adapter.RecyclerViewAdapter; import com.hibrianlee.mvvmapp.inject.ActivityComponent; import com.hibrianlee.sample.mvvm.R; import com.hibrianlee.sample.mvvm.databinding.ItemAndroidVersionBinding; import com.hibrianlee.sample.mvvm.model.AndroidVersion; import com.hibrianlee.sample.mvvm.viewmodel.AndroidVersionItemViewModel; import com.hibrianlee.sample.mvvm.viewmodel.ViewModelFactory;
/* * Copyright (C) 2015 Brian Lee (@hiBrianLee) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hibrianlee.sample.mvvm.adapter; public class AndroidVersionsAdapter extends RecyclerViewAdapter<AndroidVersion, AndroidVersionItemViewModel> { private final ViewModelFactory viewModelFactory; public AndroidVersionsAdapter(ViewModelFactory viewModelFactory,
@NonNull ActivityComponent activityComponent) {
1
idega/is.idega.idegaweb.egov.course
src/java/is/idega/idegaweb/egov/course/business/CourseAttendanceWriter.java
[ "public class CourseConstants {\n\n\tpublic static final String CASE_CODE_KEY = \"COURSEA\";\n\n\tpublic static final String IW_BUNDLE_IDENTIFIER = \"is.idega.idegaweb.egov.course\";\n\n\tpublic static final String ADMINISTRATOR_ROLE_KEY = \"afterSchoolCareAdministrator\";\n\tpublic static final String SUPER_ADMINISTRATOR_ROLE_KEY = \"superAfterSchoolCareAdministrator\";\n\tpublic static final String COURSE_ACCOUNTING_ROLE_KEY = \"courseAccounting\";\n\n\tpublic static final int DAY_CARE_NONE = 0;\n\tpublic static final int DAY_CARE_PRE = 1;\n\tpublic static final int DAY_CARE_POST = 2;\n\tpublic static final int DAY_CARE_PRE_AND_POST = 3;\n\n\tpublic static final String PROPERTY_REGISTRATION_EMAIL = \"egov.course.registration.email\";\n\tpublic static final String PROPERTY_BCC_EMAIL = \"egov.course.bcc.email\";\n\tpublic static final String PROPERTY_REFUND_EMAIL = \"egov.course.refund.email\";\n\tpublic static final String PROPERTY_HIDDEN_SCHOOL_TYPE = \"egov.course.hidden.type\";\n\tpublic static final String PROPERTY_MERCHANT_PK = \"egov.course.merchant.pk\";\n\tpublic static final String PROPERTY_MERCHANT_TYPE = \"egov.course.merchant.type\";\n\tpublic static final String PROPERTY_INVALIDATE_INTERVAL = \"egov.course.invalidate.interval\";\n\tpublic static final String PROPERTY_USE_DWR = \"egov.course.use.dwr\";\n\tpublic static final String PROPERTY_USE_FIXED_PRICES = \"egov.course.use.fixed.prices\";\n\tpublic static final String PROPERTY_USE_BIRTHYEARS = \"egov.course.use.birthyears\";\n\tpublic static final String PROPERTY_ACCOUNTING_TYPE_PK = \"egov.course.accounting.type\";\n\tpublic static final String PROPERTY_SHOW_ID_IN_NAME = \"egov.course.show.id.in.name\";\n\tpublic static final String PROPERTY_SHOW_PROVIDER = \"egov.course.show.provider\";\n\tpublic static final String PROPERTY_INCEPTION_YEAR = \"egov.course.inception.year\";\n\tpublic static final String PROPERTY_SHOW_ALL_COURSES = \"egov.course.show.all.courses\";\n\tpublic static final String PROPERTY_SHOW_CERTIFICATES = \"egov.course.show.certificates\";\n\tpublic static final String PROPERTY_SHOW_NO_PAYMENT = \"egov.course.show.no.payment\";\n\tpublic static final String PROPERTY_BACK_MONTHS = \"egov.course.back.months\";\n\tpublic static final String PROPERTY_USE_WAITING_LIST = \"egov.course.use.waiting.list\";\n\tpublic static final String PROPERTY_USE_DIRECT_PAYMENT = \"egov.course.use.direct.payment\";\n\tpublic static final String PROPERTY_SEND_REMINDERS = \"egov.course.send.reminders\";\n\tpublic static final String PROPERTY_PUBLIC_HOLIDAYS = \"egov.course.public.holidays\";\n\tpublic static final String PROPERTY_MANUALLY_OPEN_COURSES = \"egov.course.manually.open\";\n\tpublic static final String PROPERTY_ACCEPT_URL = \"egov.course.accept.url\";\n\tpublic static final String PROPERTY_SHOW_CARE_OPTIONS = \"egov.course.show.care.options\";\n\tpublic static final String PROPERTY_SHOW_PROVIDER_INFORMATION = \"egov.course.show.provider.info\";\n\tpublic static final String PROPERTY_SHOW_PERSON_INFORMATION = \"egov.course.show.person.info\";\n\n\tpublic static final String PROPERTY_TIMEOUT_DAY_OF_WEEK = \"egov.course.timeout.day\";\n\tpublic static final String PROPERTY_TIMEOUT_HOUR = \"egov.course.timeout.hour\";\n\n\tpublic static final String APPLICATION_PROPERTY_COURSE_MAP = \"egov.course.map\";\n\n\tpublic static final String CARD_TYPE_EUROCARD = \"eurocard\";\n\tpublic static final String CARD_TYPE_VISA = \"visa\";\n\n\tpublic static final String PAYMENT_TYPE_CARD = \"credit_card\";\n\tpublic static final String PAYMENT_TYPE_GIRO = \"giro\";\n\tpublic static final String PAYMENT_TYPE_BANK_TRANSFER = \"bank_transfer\";\n\n\tpublic static final String PRODUCT_CODE_CARE = \"CARE\";\n\tpublic static final String PRODUCT_CODE_COURSE = \"COURSE\";\n\n\tpublic static final String DISCOUNT_SIBLING = \"sibling\";\n\tpublic static final String DISCOUNT_QUANTITY = \"quantity\";\n\tpublic static final String DISCOUNT_SPOUSE = \"spouse\";\n\n\tpublic static final String COURSE_PREFIX = \"course_\";\n\t\n\tpublic static final String DEFAULT_COURSE_CERTIFICATE_FEE = \"defaultCourseCertificateFee\";\n\n\tpublic static final String PROPERTY_TIMER_HOUR = \"egov.course.timer.hour\";\n\tpublic static final String PROPERTY_TIMER_DAYOFWEEK = \"egov.course.timer.dayofweek\";\n\tpublic static final String PROPERTY_TIMER_MINUTE = \"egov.course.timer.minute\";\n\n}", "public interface Course extends IDOEntity {\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getName\n\t */\n\tpublic String getName();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getUser\n\t */\n\tpublic String getUser();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getDescription\n\t */\n\tpublic String getDescription();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getProvider\n\t */\n\tpublic School getProvider();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCourseType\n\t */\n\tpublic CourseType getCourseType();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getPrice\n\t */\n\tpublic CoursePrice getPrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCoursePrice\n\t */\n\tpublic float getCoursePrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCourseCost\n\t */\n\tpublic float getCourseCost();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getAccountingKey\n\t */\n\tpublic String getAccountingKey();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getStartDate\n\t */\n\tpublic Timestamp getStartDate();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getEndDate\n\t */\n\tpublic Timestamp getEndDate();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getRegistrationEnd\n\t */\n\tpublic Timestamp getRegistrationEnd();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getBirthyearFrom\n\t */\n\tpublic int getBirthyearFrom();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getBirthyearTo\n\t */\n\tpublic int getBirthyearTo();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getMax\n\t */\n\tpublic int getMax();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getFreePlaces\n\t */\n\tpublic int getFreePlaces();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getFreePlaces\n\t */\n\tpublic int getFreePlaces(boolean countOffers);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCourseNumber\n\t */\n\tpublic int getCourseNumber();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#isOpenForRegistration\n\t */\n\tpublic boolean isOpenForRegistration();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#hasPreCare\n\t */\n\tpublic boolean hasPreCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#hasPostCare\n\t */\n\tpublic boolean hasPostCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#hasPreAndPostCarehasPreAndPostCare\n\t */\n\tpublic boolean hasPreAndPostCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setName\n\t */\n\tpublic void setName(String name);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setUser\n\t */\n\tpublic void setUser(String user);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setDescription\n\t */\n\tpublic void setDescription(String description);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setProvider\n\t */\n\tpublic void setProvider(School provider);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCourseType\n\t */\n\tpublic void setCourseType(CourseType courseType);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setPrice\n\t */\n\tpublic void setPrice(CoursePrice price);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCoursePrice\n\t */\n\tpublic void setCoursePrice(float price);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCourseCost\n\t */\n\tpublic void setCourseCost(float cost);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setAccountingKey\n\t */\n\tpublic void setAccountingKey(String key);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setStartDate\n\t */\n\tpublic void setStartDate(Timestamp startDate);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setEndDate\n\t */\n\tpublic void setEndDate(Timestamp endDate);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setRegistrationEnd\n\t */\n\tpublic void setRegistrationEnd(Timestamp registrationEnd);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setBirthyearFrom\n\t */\n\tpublic void setBirthyearFrom(int from);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setBirthyearTo\n\t */\n\tpublic void setBirthyearTo(int to);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setMax\n\t */\n\tpublic void setMax(int max);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCourseNumber\n\t */\n\tpublic void setCourseNumber(int number);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setOpenForRegistration\n\t */\n\tpublic void setOpenForRegistration(boolean openForRegistration);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setHasPreCare\n\t */\n\tpublic void setHasPreCare(boolean hasPreCare);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setHasPostCare\n\t */\n\tpublic void setHasPostCare(boolean hasPostCare);\n\n\tpublic void setRentableItems(Collection<? extends RentableItem> items) throws IDOAddRelationshipException;\n\tpublic Collection<? extends RentableItem> getRentableItems(Class<? extends RentableItem> itemClass);\n\tpublic void addRentableItem(RentableItem item) throws IDOAddRelationshipException;\n\tpublic void removeRentableItem(RentableItem item) throws IDORemoveRelationshipException;\n\tpublic void removeAllRentableItems(Class<? extends RentableItem> itemClass) throws IDORemoveRelationshipException;\n\n\tpublic void addPrice(CoursePrice price) throws IDOAddRelationshipException;\n\tpublic Collection<CoursePrice> getAllPrices();\n\tpublic void removePrice(CoursePrice price) throws IDORemoveRelationshipException;\n\tpublic void removeAllPrices() throws IDORemoveRelationshipException;\n\n\tpublic void addSeason(SchoolSeason season) throws IDOAddRelationshipException;\n\tpublic Collection<SchoolSeason> getSeasons();\n\tpublic void removeSeason(SchoolSeason season) throws IDORemoveRelationshipException;\n\tpublic void removeAllSeasons() throws IDORemoveRelationshipException;\n\n}", "public interface CourseApplication extends IDOEntity, Case {\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCaseCodeDescription\n\t */\n\tpublic String getCaseCodeDescription();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCaseCodeKey\n\t */\n\tpublic String getCaseCodeKey();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCreditCardMerchantID\n\t */\n\tpublic int getCreditCardMerchantID();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCreditCardMerchantType\n\t */\n\tpublic String getCreditCardMerchantType();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getReferenceNumber\n\t */\n\tpublic String getReferenceNumber();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getPaymentType\n\t */\n\tpublic String getPaymentType();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#isPaid\n\t */\n\tpublic boolean isPaid();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getPaymentTimestamp\n\t */\n\tpublic Timestamp getPaymentTimestamp();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getPayerName\n\t */\n\tpublic String getPayerName();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getPayerPersonalID\n\t */\n\tpublic String getPayerPersonalID();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getPrefix\n\t */\n\tpublic String getPrefix();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getAmount\n\t */\n\tpublic float getAmount();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCompany\n\t */\n\tpublic Company getCompany();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCardType\n\t */\n\tpublic String getCardType();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCardNumber\n\t */\n\tpublic String getCardNumber();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCardValidMonth\n\t */\n\tpublic int getCardValidMonth();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#getCardValidYear\n\t */\n\tpublic int getCardValidYear();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCreditCardMerchantID\n\t */\n\tpublic void setCreditCardMerchantID(int merchantID);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCreditCardMerchantType\n\t */\n\tpublic void setCreditCardMerchantType(String merchantType);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setReferenceNumber\n\t */\n\tpublic void setReferenceNumber(String referenceNumber);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setPaymentType\n\t */\n\tpublic void setPaymentType(String paymentType);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setPaid\n\t */\n\tpublic void setPaid(boolean paid);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setPaymentTimestamp\n\t */\n\tpublic void setPaymentTimestamp(Timestamp timestamp);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setPayerName\n\t */\n\tpublic void setPayerName(String name);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setPayerPersonalID\n\t */\n\tpublic void setPayerPersonalID(String personalID);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setPrefix\n\t */\n\tpublic void setPrefix(String prefix);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setAmount\n\t */\n\tpublic void setAmount(float amount);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCompany\n\t */\n\tpublic void setCompany(Company company);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCardType\n\t */\n\tpublic void setCardType(String type);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCardNumber\n\t */\n\tpublic void setCardNumber(String number);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCardValidMonth\n\t */\n\tpublic void setCardValidMonth(int month);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseApplicationBMPBean#setCardValidYear\n\t */\n\tpublic void setCardValidYear(int year);\n}", "public interface CourseChoice extends IDOEntity {\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getApplication\n\t */\n\tpublic CourseApplication getApplication();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getCourse\n\t */\n\tpublic Course getCourse();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getUser\n\t */\n\tpublic User getUser();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getDayCare\n\t */\n\tpublic int getDayCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getPaymentTimestamp\n\t */\n\tpublic Timestamp getPaymentTimestamp();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isPickedUp\n\t */\n\tpublic boolean isPickedUp();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isValid\n\t */\n\tpublic boolean isValid();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#hasDyslexia\n\t */\n\tpublic boolean hasDyslexia();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isOnWaitingList\n\t */\n\tpublic boolean isOnWaitingList();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isNoPayment\n\t */\n\tpublic boolean isNoPayment();\n\t\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#hasReceivedReminder\n\t */\n\tpublic boolean hasReceivedReminder();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#hasCreateLogin\n\t */\n\tpublic boolean hasCreateLogin();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setApplication\n\t */\n\tpublic void setApplication(CourseApplication application);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setCourse\n\t */\n\tpublic void setCourse(Course course);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setUser\n\t */\n\tpublic void setUser(User user);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setPaymentTimestamp\n\t */\n\tpublic void setPaymentTimestamp(Timestamp timestamp);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setDayCare\n\t */\n\tpublic void setDayCare(int dayCare);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setPickedUp\n\t */\n\tpublic void setPickedUp(boolean pickedUp);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setValid\n\t */\n\tpublic void setValid(boolean valid);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setHasDyslexia\n\t */\n\tpublic void setHasDyslexia(boolean dyslexia);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setWaitingList\n\t */\n\tpublic void setWaitingList(boolean waitingList);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setNoPayment\n\t */\n\tpublic void setNoPayment(boolean noPayment);\n\t\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setReceivedReminder\n\t */\n\tpublic void setReceivedReminder(boolean hasReceivedReminder);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setHasCreateLogin\n\t */\n\tpublic void setHasCreateLogin(boolean createLogin);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setPassed\n\t */\n\tpublic void setPassed(boolean passed);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#hasPassed\n\t */\n\tpublic boolean hasPassed();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setCourseCertificateFee\n\t */\n\tpublic void setCourseCertificateFee(float fee);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getCourseCertificateFee\n\t */\n\tpublic float getCourseCertificateFee();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isCertificateOfProperty\n\t */\n\tpublic boolean isCertificateOfProperty();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isCriminalRecord\n\t */\n\tpublic boolean isCriminalRecord();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isDidNotShowUp\n\t */\n\tpublic boolean isDidNotShowUp();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isNeedVerificationFromGovermentOffice\n\t */\n\tpublic boolean isNeedVerificationFromGovermentOffice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isVerificationFromGovermentOffice\n\t */\n\tpublic boolean isVerificationFromGovermentOffice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isVerificationOfPayment\n\t */\n\tpublic boolean isVerificationOfPayment();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setCertificateOfProperty\n\t */\n\tpublic void setCertificateOfProperty(boolean certificateOfProperty);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setCriminalRecord\n\t */\n\tpublic void setCriminalRecord(boolean criminalRecord);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#isLimitedCertificate\n\t */\n\tpublic boolean isLimitedCertificate();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setDidNotShowUp\n\t */\n\tpublic void setDidNotShowUp(boolean didNotShowUp);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setNeedsVerificationFromGovermentOffice\n\t */\n\tpublic void setNeedsVerificationFromGovermentOffice(\n\t\t\tboolean needsVerificationFromOffice);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setVerificationFromGovermentOffice\n\t */\n\tpublic void setVerificationFromGovermentOffice(\n\t\t\tboolean verificationFromGovermentOffice);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setVerificationOfPayment\n\t */\n\tpublic void setVerificationOfPayment(boolean verificationOfPayment);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setLimitedCertificate\n\t */\n\tpublic void setLimitedCertificate(boolean limitedCertificate);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getBooleanValueFromColumn\n\t */\n\tpublic boolean getBooleanValueFromColumn(String columnName);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setBooleanValueForColumn\n\t */\n\tpublic void setBooleanValueForColumn(boolean value, String columnName);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getNotes\n\t */\n\tpublic String getNotes();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#getUniqueID\n\t */\n\tpublic String getUniqueID();\n\t\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setNotes\n\t */\n\tpublic void setNotes(String notes);\n\t\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseChoiceBMPBean#setUniqueID\n\t */\n\tpublic void setUniqueID(String uniqueID);\n}", "public abstract class CourseBlock extends Block implements IWPageEventListener {\n\n\tpublic static final String ACTION_PRINT = \"print\";\n\tpublic static final String ACTION_CONFIRM_PRINT = \"confirmPrint\";\n\tpublic static final String ACTION_REMOVE_CERTIFICATE = \"removeCertificate\";\n\n\tpublic static final String PARAMETER_ACTION = \"prm_action\";\n\tpublic static final String PARAMETER_PRINT_CERTIFICATE = \"prm_print_certificate\";\n\tpublic static final String PARAMETER_PROVIDER_PK = \"prm_provider_pk\";\n\tpublic static final String PARAMETER_COURSE_PK = \"prm_course_pk\";\n\tpublic static final String PARAMETER_CHOICE_PK = \"prm_choice_pk\";\n\tpublic static final String PARAMETER_COURSE_TYPE_PK = \"prm_course_type_pk\";\n\tpublic static final String PARAMETER_COURSE_PARTICIPANT_PK = \"prm_course_participant_pk\";\n\tpublic static final String PARAMETER_SCHOOL_TYPE_PK = \"prm_school_type_pk\";\n\tpublic static final String PARAMETER_FROM_DATE = \"prm_from_date\";\n\tpublic static final String PARAMETER_TO_DATE = \"prm_to_date\";\n\tpublic static final String PARAMETER_YEAR = \"prm_year\";\n\tpublic static final String PARAMETER_CERTIFICATE_PK = \"prm_certificate_pk\";\n\n\tprivate CourseBusiness business;\n\tprivate CourseSession session;\n\tprivate CitizenBusiness uBusiness;\n\n\tprivate IWResourceBundle iwrb;\n\tprivate IWBundle iwb;\n\n\tprivate ICPage iResponsePage;\n\tprivate ICPage iBackPage;\n\n\tprivate boolean iHasErrors = false;\n\tprivate Map<String, String> iErrors;\n\n\t@Override\n\tpublic boolean actionPerformed(IWContext iwc) {\n\t\tif (iwc.isParameterSet(PARAMETER_PROVIDER_PK)) {\n\t\t\ttry {\n\t\t\t\tgetSession(iwc).setProviderPK(new Integer(iwc.getParameter(PARAMETER_PROVIDER_PK)));\n\t\t\t}\n\t\t\tcatch (RemoteException re) {\n\t\t\t\tthrow new IBORuntimeException(re);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\ttry {\n\t\t\t\tgetSession(iwc).setProviderPK(null);\n\t\t\t}\n\t\t\tcatch (RemoteException re) {\n\t\t\t\tthrow new IBORuntimeException(re);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void main(IWContext iwc) throws Exception {\n\t\tsetBundle(getBundle(iwc));\n\t\tsetResourceBundle(getResourceBundle(iwc));\n\t\tthis.business = getBusiness(iwc);\n\t\tthis.session = getSession(iwc);\n\t\tthis.uBusiness = getUserBusiness(iwc);\n\t\tPresentationUtil.addStyleSheetToHeader(iwc, iwc.getIWMainApplication().getBundle(\"is.idega.idegaweb.egov.application\").getVirtualPathWithFileNameString(\"style/application.css\"));\n\t\tPresentationUtil.addStyleSheetToHeader(iwc, iwc.getIWMainApplication().getBundle(\"is.idega.idegaweb.egov.course\").getVirtualPathWithFileNameString(\"style/course.css\"));\n\n\t\tpresent(iwc);\n\t}\n\n\tprotected IWResourceBundle getResourceBundle() {\n\t\treturn this.iwrb;\n\t}\n\n\tprivate void setResourceBundle(IWResourceBundle iwrb) {\n\t\tthis.iwrb = iwrb;\n\t}\n\n\tprotected IWBundle getBundle() {\n\t\treturn this.iwb;\n\t}\n\n\tprivate void setBundle(IWBundle iwb) {\n\t\tthis.iwb = iwb;\n\t}\n\n\tprotected String localize(String key, String defaultValue) {\n\t\treturn getResourceBundle().getLocalizedString(key, defaultValue);\n\t}\n\n\tprotected CourseBusiness getBusiness() {\n\t\treturn this.business;\n\t}\n\n\tprotected CourseSession getSession() {\n\t\treturn this.session;\n\t}\n\n\tprotected CitizenBusiness getUserBusiness() {\n\t\treturn this.uBusiness;\n\t}\n\n\tprivate CourseBusiness getBusiness(IWApplicationContext iwac) {\n\t\ttry {\n\t\t\treturn IBOLookup.getServiceInstance(iwac, CourseBusiness.class);\n\t\t}\n\t\tcatch (IBOLookupException ile) {\n\t\t\tthrow new IBORuntimeException(ile);\n\t\t}\n\t}\n\n\tprotected CourseSession getSession(IWUserContext iwuc) {\n\t\ttry {\n\t\t\treturn IBOLookup.getSessionInstance(iwuc, CourseSession.class);\n\t\t}\n\t\tcatch (IBOLookupException ile) {\n\t\t\tthrow new IBORuntimeException(ile);\n\t\t}\n\t}\n\n\tprotected FamilyLogic getFamilyLogic(IWApplicationContext iwac) {\n\t\ttry {\n\t\t\treturn IBOLookup.getServiceInstance(iwac, FamilyLogic.class);\n\t\t}\n\t\tcatch (IBOLookupException ile) {\n\t\t\tthrow new IBORuntimeException(ile);\n\t\t}\n\t}\n\n\tprotected CitizenBusiness getUserBusiness(IWApplicationContext iwac) {\n\t\ttry {\n\t\t\treturn IBOLookup.getServiceInstance(iwac, CitizenBusiness.class);\n\t\t}\n\t\tcatch (IBOLookupException ile) {\n\t\t\tthrow new IBORuntimeException(ile);\n\t\t}\n\t}\n\n\tprotected SchoolBusiness getSchoolBusiness(IWApplicationContext iwac) {\n\t\ttry {\n\t\t\treturn IBOLookup.getServiceInstance(iwac, SchoolBusiness.class);\n\t\t}\n\t\tcatch (RemoteException e) {\n\t\t\tthrow new IBORuntimeException(e.getMessage());\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getBundleIdentifier() {\n\t\treturn CourseConstants.IW_BUNDLE_IDENTIFIER;\n\t}\n\n\tpublic abstract void present(IWContext iwc);\n\n\tprotected boolean isSchoolUser() {\n\t\ttry {\n\t\t\treturn getSession().isSchoolProvider();\n\t\t}\n\t\tcatch (RemoteException re) {\n\t\t\tthrow new IBORuntimeException(re);\n\t\t}\n\t}\n\n\tprotected boolean isSchoolAdministrator(IWContext iwc) {\n\t\treturn isSchoolSuperAdministrator(iwc) || isSchoolUser();\n\t}\n\n\tprotected boolean isSchoolSuperAdministrator(IWContext iwc) {\n\t\treturn iwc.getAccessController().hasRole(CourseConstants.SUPER_ADMINISTRATOR_ROLE_KEY, iwc) || iwc.getAccessController().hasRole(CourseConstants.ADMINISTRATOR_ROLE_KEY, iwc);\n\t}\n\n\tprotected Layer getPersonInfo(IWContext iwc, User user, boolean showAddress) throws RemoteException {\n\t\tLayer layer = new Layer();\n\t\tlayer.setID(\"personInfo\");\n\t\tlayer.setStyleClass(\"info\");\n\n\t\tif (user != null) {\n\t\t\tAddress address = getUserBusiness().getUsersMainAddress(user);\n\t\t\tPostalCode postal = null;\n\t\t\tif (address != null) {\n\t\t\t\tpostal = address.getPostalCode();\n\t\t\t}\n\n\t\t\tLayer personInfo = new Layer(Layer.DIV);\n\t\t\tpersonInfo.setStyleClass(\"personInfo\");\n\t\t\tpersonInfo.setID(\"name\");\n\t\t\tpersonInfo.add(new Text(user.getName()));\n\t\t\tlayer.add(personInfo);\n\n\t\t\tpersonInfo = new Layer(Layer.DIV);\n\t\t\tpersonInfo.setStyleClass(\"personInfo\");\n\t\t\tpersonInfo.setID(\"personalID\");\n\t\t\tpersonInfo.add(new Text(PersonalIDFormatter.format(user.getPersonalID(), iwc.getCurrentLocale())));\n\t\t\tlayer.add(personInfo);\n\n\t\t\tpersonInfo = new Layer(Layer.DIV);\n\t\t\tpersonInfo.setStyleClass(\"personInfo\");\n\t\t\tpersonInfo.setID(\"address\");\n\t\t\tif (address != null && showAddress) {\n\t\t\t\tpersonInfo.add(new Text(address.getStreetAddress()));\n\t\t\t}\n\t\t\tlayer.add(personInfo);\n\n\t\t\tpersonInfo = new Layer(Layer.DIV);\n\t\t\tpersonInfo.setStyleClass(\"personInfo\");\n\t\t\tpersonInfo.setID(\"postal\");\n\t\t\tif (postal != null && showAddress) {\n\t\t\t\tpersonInfo.add(new Text(postal.getPostalAddress()));\n\t\t\t}\n\t\t\tlayer.add(personInfo);\n\n\t\t\tLayer clear = new Layer(Layer.DIV);\n\t\t\tclear.setStyleClass(\"Clear\");\n\t\t\tlayer.add(clear);\n\t\t}\n\n\t\treturn layer;\n\t}\n\n\tprotected DropdownMenu getProvidersDropdown(IWContext iwc) {\n\t\ttry {\n\t\t\tIWResourceBundle iwrb = getResourceBundle(iwc);\n\n\t\t\tSelectorUtility util = new SelectorUtility();\n\t\t\tDropdownMenu providers = (DropdownMenu) util.getSelectorFromIDOEntities(new DropdownMenu(PARAMETER_PROVIDER_PK), getBusiness(iwc).getProvidersForUser(iwc.getCurrentUser()), \"getSchoolName\");\n\t\t\tproviders.addMenuElementFirst(\"\", iwrb.getLocalizedString(\"select_provider\", \"Select provider\"));\n\t\t\tif (getSession(iwc).getProvider() != null) {\n\t\t\t\tproviders.setSelectedElement(getSession(iwc).getProvider().getPrimaryKey().toString());\n\t\t\t}\n\n\t\t\treturn providers;\n\t\t}\n\t\tcatch (RemoteException re) {\n\t\t\tthrow new IBORuntimeException(re);\n\t\t}\n\t}\n\n\tprotected DropdownMenu getAllProvidersDropdown(IWContext iwc) {\n\t\ttry {\n\t\t\tIWResourceBundle iwrb = getResourceBundle(iwc);\n\n\t\t\tSelectorUtility util = new SelectorUtility();\n\t\t\tDropdownMenu providers = (DropdownMenu) util.getSelectorFromIDOEntities(new DropdownMenu(PARAMETER_PROVIDER_PK), getBusiness(iwc).getProviders(), \"getSchoolName\");\n\t\t\tproviders.addMenuElementFirst(\"\", iwrb.getLocalizedString(\"select_provider\", \"Select provider\"));\n\t\t\tif (getSession(iwc).getProvider() != null) {\n\t\t\t\tproviders.setSelectedElement(getSession(iwc).getProvider().getPrimaryKey().toString());\n\t\t\t}\n\n\t\t\treturn providers;\n\t\t}\n\t\tcatch (RemoteException re) {\n\t\t\tthrow new IBORuntimeException(re);\n\t\t}\n\t}\n\n\tprotected void addChildInformationOverview(IWContext iwc, Layer section, IWResourceBundle iwrb, User owner, Child child) throws RemoteException {\n\t\tBoolean hasGrowthDeviation = child.hasGrowthDeviation(CourseConstants.COURSE_PREFIX + owner.getPrimaryKey());\n\t\tif (hasGrowthDeviation == null && isSchoolUser()) {\n\t\t\thasGrowthDeviation = child.hasGrowthDeviation(CourseConstants.COURSE_PREFIX);\n\t\t}\n\t\tif (hasGrowthDeviation == null) {\n\t\t\thasGrowthDeviation = child.hasGrowthDeviation();\n\t\t}\n\n\t\tString growthDeviation = child.getGrowthDeviationDetails(CourseConstants.COURSE_PREFIX + owner.getPrimaryKey());\n\t\tif (growthDeviation == null && isSchoolUser()) {\n\t\t\tgrowthDeviation = child.getGrowthDeviationDetails(CourseConstants.COURSE_PREFIX);\n\t\t}\n\t\tif (growthDeviation == null) {\n\t\t\tgrowthDeviation = child.getGrowthDeviationDetails();\n\t\t}\n\n\t\tBoolean hasAllergies = child.hasAllergies(CourseConstants.COURSE_PREFIX + owner.getPrimaryKey());\n\t\tif (hasAllergies == null && isSchoolUser()) {\n\t\t\thasAllergies = child.hasAllergies(CourseConstants.COURSE_PREFIX);\n\t\t}\n\t\tif (hasAllergies == null) {\n\t\t\thasAllergies = child.hasAllergies();\n\t\t}\n\n\t\tString allergies = child.getAllergiesDetails(CourseConstants.COURSE_PREFIX + owner.getPrimaryKey());\n\t\tif (allergies == null && isSchoolUser()) {\n\t\t\tallergies = child.getAllergiesDetails(CourseConstants.COURSE_PREFIX);\n\t\t}\n\t\tif (allergies == null) {\n\t\t\tallergies = child.getAllergiesDetails();\n\t\t}\n\n\t\tString otherInformation = child.getOtherInformation(CourseConstants.COURSE_PREFIX + owner.getPrimaryKey());\n\t\tif (StringUtil.isEmpty(otherInformation) && isSchoolUser()) {\n\t\t\totherInformation = child.getOtherInformation(CourseConstants.COURSE_PREFIX);\n\t\t}\n\n\t\tLayer formItem = new Layer(Layer.DIV);\n\t\tformItem.setStyleClass(\"formItem\");\n\t\tformItem.setStyleClass(\"informationItem\");\n\t\tLabel label = new Label();\n\t\tlabel.add(new Text(iwrb.getLocalizedString(\"child.has_growth_deviation_overview\", \"Has growth deviation\")));\n\t\tLayer span = new Layer(Layer.SPAN);\n\n\t\tParagraph paragraph = new Paragraph();\n\t\tparagraph.add(new Text(getBooleanValue(iwc, hasGrowthDeviation)));\n\t\tspan.add(paragraph);\n\t\tformItem.add(label);\n\t\tformItem.add(span);\n\t\tsection.add(formItem);\n\n\t\tif (hasGrowthDeviation != null) {\n\t\t\tif (growthDeviation != null) {\n\t\t\t\tparagraph.add(new Text(\", \"));\n\t\t\t\tparagraph.add(growthDeviation);\n\t\t\t}\n\t\t}\n\n\t\tformItem = new Layer(Layer.DIV);\n\t\tformItem.setStyleClass(\"formItem\");\n\t\tformItem.setStyleClass(\"informationItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(new Text(iwrb.getLocalizedString(\"child.has_allergies_overview\", \"Has allergies\")));\n\t\tspan = new Layer(Layer.SPAN);\n\t\tparagraph = new Paragraph();\n\t\tparagraph.add(new Text(getBooleanValue(iwc, hasAllergies)));\n\t\tspan.add(paragraph);\n\t\tformItem.add(label);\n\t\tformItem.add(span);\n\t\tsection.add(formItem);\n\n\t\tif (hasAllergies != null) {\n\t\t\tif (allergies != null) {\n\t\t\t\tparagraph.add(new Text(\", \"));\n\t\t\t\tparagraph.add(allergies);\n\t\t\t}\n\t\t}\n\n\t\tformItem = new Layer(Layer.DIV);\n\t\tformItem.setStyleClass(\"formItem\");\n\t\tformItem.setStyleClass(\"informationItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(new Text(this.iwrb.getLocalizedString(\"child.other_information\", \"Other information\")));\n\t\tspan = new Layer(Layer.SPAN);\n\t\tparagraph = new Paragraph();\n\t\tparagraph.add(new Text(otherInformation));\n\t\tspan.add(paragraph);\n\t\tformItem.add(label);\n\t\tformItem.add(span);\n\t\tsection.add(formItem);\n\t}\n\n\tprotected Layer getCustodians(IWContext iwc, IWResourceBundle iwrb, User owner, Child child, Collection<Custodian> custodians) throws RemoteException {\n\t\tLayer layer = new Layer(Layer.DIV);\n\t\tlayer.setStyleClass(\"formSection\");\n\n\t\tLayer relation = new Layer(Layer.DIV);\n\t\trelation.setStyleClass(\"formItem\");\n\t\trelation.setStyleClass(\"multiValueItem\");\n\t\tLabel label = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"relation\", \"Relation\"));\n\t\trelation.add(label);\n\t\tlayer.add(relation);\n\n\t\tLayer name = new Layer(Layer.DIV);\n\t\tname.setStyleClass(\"formItem\");\n\t\tname.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"name\", \"Name\"));\n\t\tname.add(label);\n\t\tlayer.add(name);\n\n\t\tLayer personalID = new Layer(Layer.DIV);\n\t\tpersonalID.setStyleClass(\"formItem\");\n\t\tpersonalID.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"personal_id\", \"Personal ID\"));\n\t\tpersonalID.add(label);\n\t\tlayer.add(personalID);\n\n\t\tLayer address = new Layer(Layer.DIV);\n\t\taddress.setStyleClass(\"formItem\");\n\t\taddress.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"address\", \"Address\"));\n\t\taddress.add(label);\n\t\tlayer.add(address);\n\n\t\tLayer postal = new Layer(Layer.DIV);\n\t\tpostal.setStyleClass(\"formItem\");\n\t\tpostal.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"zip_code\", \"Zip code\"));\n\t\tpostal.add(label);\n\t\tlayer.add(postal);\n\n\t\tLayer homePhone = new Layer(Layer.DIV);\n\t\thomePhone.setStyleClass(\"formItem\");\n\t\thomePhone.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"home_phone\", \"Home phone\"));\n\t\thomePhone.add(label);\n\t\tlayer.add(homePhone);\n\n\t\tLayer workPhone = new Layer(Layer.DIV);\n\t\tworkPhone.setStyleClass(\"formItem\");\n\t\tworkPhone.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"work_phone\", \"Work phone\"));\n\t\tworkPhone.add(label);\n\t\tlayer.add(workPhone);\n\n\t\tLayer mobile = new Layer(Layer.DIV);\n\t\tmobile.setStyleClass(\"formItem\");\n\t\tmobile.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"mobile_phone\", \"Mobile phone\"));\n\t\tmobile.add(label);\n\t\tlayer.add(mobile);\n\n\t\tLayer email = new Layer(Layer.DIV);\n\t\temail.setStyleClass(\"formItem\");\n\t\temail.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"email\", \"E-mail\"));\n\t\temail.add(label);\n\t\tlayer.add(email);\n\n\t\t/*\n\t\t * Layer maritalStatus = new Layer(Layer.DIV); maritalStatus.setStyleClass(\"formItem\"); maritalStatus.setStyleClass(\"multiValueItem\"); label = new\n\t\t * Label(); label.add(iwrb.getLocalizedString(\"marital_status\", \"Marital status\")); maritalStatus.add(label); layer.add(maritalStatus);\n\t\t */\n\n\t\tIterator<Custodian> iter = custodians.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tCustodian custodian = iter.next();\n\t\t\tboolean hasRelation = isSchoolAdministrator(iwc) || getFamilyLogic(iwc).isRelatedTo(custodian, owner) || owner.getPrimaryKey().equals(custodian.getPrimaryKey());\n\n\t\t\tAddress userAddress = getUserBusiness(iwc).getUsersMainAddress(custodian);\n\t\t\tPhone userPhone = null;\n\t\t\tPhone userWork = null;\n\t\t\tPhone userMobile = null;\n\t\t\tEmail userEmail = null;\n\n\t\t\ttry {\n\t\t\t\tuserPhone = getUserBusiness(iwc).getUsersHomePhone(custodian);\n\t\t\t}\n\t\t\tcatch (NoPhoneFoundException npfe) {\n\t\t\t\tuserPhone = null;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tuserWork = getUserBusiness(iwc).getUsersWorkPhone(custodian);\n\t\t\t}\n\t\t\tcatch (NoPhoneFoundException npfe) {\n\t\t\t\tuserWork = null;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tuserMobile = getUserBusiness(iwc).getUsersMobilePhone(custodian);\n\t\t\t}\n\t\t\tcatch (NoPhoneFoundException npfe) {\n\t\t\t\tuserMobile = null;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tuserEmail = getUserBusiness(iwc).getUsersMainEmail(custodian);\n\t\t\t}\n\t\t\tcatch (NoEmailFoundException nefe) {\n\t\t\t\tuserEmail = null;\n\t\t\t}\n\n\t\t\tLayer span = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(iwrb.getLocalizedString(\"relation.\" + child.getRelation(custodian), \"\")));\n\t\t\trelation.add(span);\n\n\t\t\tName custodianName = new Name(custodian.getFirstName(), custodian.getMiddleName(), custodian.getLastName());\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(custodianName.getName(iwc.getCurrentLocale())));\n\t\t\tname.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(PersonalIDFormatter.format(custodian.getPersonalID(), iwc.getCurrentLocale())));\n\t\t\tpersonalID.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(userAddress.getStreetAddress()));\n\t\t\taddress.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(userAddress.getPostalAddress()));\n\t\t\tpostal.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (userPhone != null && userPhone.getNumber() != null && hasRelation) {\n\t\t\t\tspan.add(new Text(userPhone.getNumber()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\thomePhone.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (userWork != null && userWork.getNumber() != null && hasRelation) {\n\t\t\t\tspan.add(new Text(userWork.getNumber()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\tworkPhone.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (userMobile != null && userMobile.getNumber() != null && hasRelation) {\n\t\t\t\tspan.add(new Text(userMobile.getNumber()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\tmobile.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (userEmail != null && userEmail.getEmailAddress() != null && hasRelation) {\n\t\t\t\tspan.add(new Text(userEmail.getEmailAddress()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\temail.add(span);\n\n\t\t\t/*\n\t\t\t * span = new Layer(Layer.SPAN); if (custodian.getMaritalStatus() != null) { span.add(new Text(iwrb.getLocalizedString(\"marital_status.\" +\n\t\t\t * custodian.getMaritalStatus()))); } else { span.add(Text.getNonBrakingSpace()); } maritalStatus.add(span);\n\t\t\t */\n\t\t}\n\n\t\tLayer clearLayer = new Layer(Layer.DIV);\n\t\tclearLayer.setStyleClass(\"Clear\");\n\t\tlayer.add(clearLayer);\n\n\t\treturn layer;\n\t}\n\n\tprotected Layer getRelatives(IWContext iwc, IWResourceBundle iwrb, Collection<Relative> relatives) {\n\t\tLayer layer = new Layer(Layer.DIV);\n\t\tlayer.setStyleClass(\"formSection\");\n\n\t\tLayer relation = new Layer(Layer.DIV);\n\t\trelation.setStyleClass(\"formItem\");\n\t\trelation.setStyleClass(\"multiValueItem\");\n\t\tLabel label = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"relation\", \"Relation\"));\n\t\trelation.add(label);\n\t\tlayer.add(relation);\n\n\t\tLayer name = new Layer(Layer.DIV);\n\t\tname.setStyleClass(\"formItem\");\n\t\tname.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"name\", \"Name\"));\n\t\tname.add(label);\n\t\tlayer.add(name);\n\n\t\tLayer homePhone = new Layer(Layer.DIV);\n\t\thomePhone.setStyleClass(\"formItem\");\n\t\thomePhone.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"home_phone\", \"Home phone\"));\n\t\thomePhone.add(label);\n\t\tlayer.add(homePhone);\n\n\t\tLayer workPhone = new Layer(Layer.DIV);\n\t\tworkPhone.setStyleClass(\"formItem\");\n\t\tworkPhone.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"work_phone\", \"Work phone\"));\n\t\tworkPhone.add(label);\n\t\tlayer.add(workPhone);\n\n\t\tLayer mobile = new Layer(Layer.DIV);\n\t\tmobile.setStyleClass(\"formItem\");\n\t\tmobile.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"mobile_phone\", \"Mobile phone\"));\n\t\tmobile.add(label);\n\t\tlayer.add(mobile);\n\n\t\tLayer email = new Layer(Layer.DIV);\n\t\temail.setStyleClass(\"formItem\");\n\t\temail.setStyleClass(\"multiValueItem\");\n\t\tlabel = new Label();\n\t\tlabel.add(iwrb.getLocalizedString(\"email\", \"E-mail\"));\n\t\temail.add(label);\n\t\tlayer.add(email);\n\n\t\tIterator<Relative> iter = relatives.iterator();\n\t\twhile (iter.hasNext()) {\n\t\t\tRelative relative = iter.next();\n\n\t\t\tLayer span = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(iwrb.getLocalizedString(\"relation.\" + relative.getRelation(), \"\")));\n\t\t\trelation.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tspan.add(new Text(relative.getName()));\n\t\t\tname.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (relative.getHomePhone() != null) {\n\t\t\t\tspan.add(new Text(relative.getHomePhone()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\thomePhone.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (relative.getWorkPhone() != null) {\n\t\t\t\tspan.add(new Text(relative.getWorkPhone()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\tworkPhone.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (relative.getMobilePhone() != null) {\n\t\t\t\tspan.add(new Text(relative.getMobilePhone()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\tmobile.add(span);\n\n\t\t\tspan = new Layer(Layer.SPAN);\n\t\t\tif (relative.getEmail() != null) {\n\t\t\t\tspan.add(new Text(relative.getEmail()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tspan.add(Text.getNonBrakingSpace());\n\t\t\t}\n\t\t\temail.add(span);\n\t\t}\n\n\t\tLayer clearLayer = new Layer(Layer.DIV);\n\t\tclearLayer.setStyleClass(\"Clear\");\n\t\tlayer.add(clearLayer);\n\n\t\treturn layer;\n\t}\n\n\tprivate Layer getPhases(int phase, int totalPhases) {\n\t\tLayer layer = new Layer(Layer.DIV);\n\t\tlayer.setStyleClass(\"phases\");\n\n\t\tLists list = new Lists();\n\t\tfor (int a = 1; a <= totalPhases; a++) {\n\t\t\tListItem item = new ListItem();\n\t\t\titem.add(new Text(String.valueOf(a)));\n\t\t\tif (a == phase) {\n\t\t\t\titem.setStyleClass(\"current\");\n\t\t\t}\n\n\t\t\tlist.add(item);\n\t\t}\n\t\tlayer.add(list);\n\n\t\treturn layer;\n\t}\n\n\tprotected Layer getHeader(String text) {\n\t\treturn getPhasesHeader(text, -1, -1);\n\t}\n\n\tprotected Layer getPhasesHeader(String text, int phase, int totalPhases) {\n\t\treturn getPhasesHeader(text, phase, totalPhases, true);\n\t}\n\n\tprotected Layer getPhasesHeader(String text, int phase, int totalPhases, boolean showNumberInText) {\n\t\tLayer layer = new Layer(Layer.DIV);\n\t\tlayer.setStyleClass(\"header\");\n\n\t\tif (phase != -1) {\n\t\t\tHeading1 heading = new Heading1((showNumberInText ? (String.valueOf(phase) + \". \") : \"\") + text);\n\t\t\tlayer.add(heading);\n\t\t\tlayer.add(getPhases(phase, totalPhases));\n\t\t}\n\t\telse {\n\t\t\tHeading1 heading = new Heading1(text);\n\t\t\tlayer.add(heading);\n\t\t}\n\n\t\treturn layer;\n\t}\n\n\tprotected String getBooleanValue(IWContext iwc, boolean booleanValue) {\n\t\treturn getBooleanValue(iwc, new Boolean(booleanValue));\n\t}\n\n\tprotected String getBooleanValue(IWContext iwc, Boolean booleanValue) {\n\t\tif (this.iwrb == null) {\n\t\t\tthis.iwrb = getResourceBundle(iwc);\n\t\t}\n\n\t\tif (booleanValue == null) {\n\t\t\treturn this.iwrb.getLocalizedString(\"no_answer\", \"Won't answer\");\n\t\t}\n\t\telse if (booleanValue.booleanValue()) {\n\t\t\treturn this.iwrb.getLocalizedString(\"yes\", \"Yes\");\n\t\t}\n\t\telse {\n\t\t\treturn this.iwrb.getLocalizedString(\"no\", \"No\");\n\t\t}\n\t}\n\n\tprotected Link getButtonLink(String text) {\n\t\tLayer all = new Layer(Layer.SPAN);\n\t\tall.setStyleClass(\"buttonSpan\");\n\n\t\tLayer left = new Layer(Layer.SPAN);\n\t\tleft.setStyleClass(\"left\");\n\t\tall.add(left);\n\n\t\tLayer middle = new Layer(Layer.SPAN);\n\t\tmiddle.setStyleClass(\"middle\");\n\t\tmiddle.add(new Text(text));\n\t\tall.add(middle);\n\n\t\tLayer right = new Layer(Layer.SPAN);\n\t\tright.setStyleClass(\"right\");\n\t\tall.add(right);\n\n\t\tLink link = new Link(all);\n\t\tlink.setStyleClass(\"button\");\n\n\t\treturn link;\n\t}\n\n\tprotected void setError(String parameter, String error) {\n\t\tif (this.iErrors == null) {\n\t\t\tthis.iErrors = new HashMap<String, String>();\n\t\t}\n\n\t\tthis.iHasErrors = true;\n\t\tthis.iErrors.put(parameter, error);\n\t}\n\n\tprotected boolean hasErrors() {\n\t\treturn this.iHasErrors;\n\t}\n\n\tprotected boolean hasError(String parameter) {\n\t\tif (hasErrors()) {\n\t\t\treturn this.iErrors.containsKey(parameter);\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Adds the errors encountered\n\t *\n\t * @param iwc\n\t * @param errors\n\t */\n\tprotected void addErrors(IWContext iwc, UIComponent parent) {\n\t\tif (this.iHasErrors) {\n\t\t\tLayer layer = new Layer(Layer.DIV);\n\t\t\tlayer.setStyleClass(\"errorLayer\");\n\n\t\t\tLayer image = new Layer(Layer.DIV);\n\t\t\timage.setStyleClass(\"errorImage\");\n\t\t\tlayer.add(image);\n\n\t\t\tHeading1 heading = new Heading1(getResourceBundle(iwc).getLocalizedString(\"application_errors_occured\", \"There was a problem with the following items\"));\n\t\t\tlayer.add(heading);\n\n\t\t\tLists list = new Lists();\n\t\t\tlayer.add(list);\n\n\t\t\tIterator<String> iter = this.iErrors.values().iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tString element = iter.next();\n\t\t\t\tListItem item = new ListItem();\n\t\t\t\titem.add(new Text(element));\n\n\t\t\t\tlist.add(item);\n\t\t\t}\n\n\t\t\tparent.getChildren().add(layer);\n\t\t}\n\t}\n\n\tprotected ICPage getResponsePage() {\n\t\treturn this.iResponsePage;\n\t}\n\n\tpublic void setResponsePage(ICPage responsePage) {\n\t\tthis.iResponsePage = responsePage;\n\t}\n\n\tprotected ICPage getBackPage() {\n\t\treturn this.iBackPage;\n\t}\n\n\tpublic void setBackPage(ICPage responsePage) {\n\t\tthis.iBackPage = responsePage;\n\t}\n}" ]
import is.idega.block.family.data.Child; import is.idega.idegaweb.egov.accounting.business.CitizenBusiness; import is.idega.idegaweb.egov.course.CourseConstants; import is.idega.idegaweb.egov.course.data.Course; import is.idega.idegaweb.egov.course.data.CourseApplication; import is.idega.idegaweb.egov.course.data.CourseChoice; import is.idega.idegaweb.egov.course.presentation.CourseBlock; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.idega.business.IBOLookup; import com.idega.core.file.util.MimeTypeUtil; import com.idega.idegaweb.IWApplicationContext; import com.idega.idegaweb.IWResourceBundle; import com.idega.io.DownloadWriter; import com.idega.io.MediaWritable; import com.idega.io.MemoryFileBuffer; import com.idega.io.MemoryInputStream; import com.idega.io.MemoryOutputStream; import com.idega.presentation.IWContext; import com.idega.user.data.User; import com.idega.util.PersonalIDFormatter; import com.idega.util.StringHandler; import com.idega.util.text.Name;
/* * $Id$ Created on Mar 28, 2007 * * Copyright (C) 2007 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.course.business; public class CourseAttendanceWriter extends DownloadWriter implements MediaWritable { private MemoryFileBuffer buffer = null; private CourseBusiness business; private CitizenBusiness userBusiness; private Locale locale; private IWResourceBundle iwrb; private String courseName; public CourseAttendanceWriter() { } @Override public void init(HttpServletRequest req, IWContext iwc) { try { this.locale = iwc.getApplicationSettings().getApplicationLocale(); this.business = getCourseBusiness(iwc); this.userBusiness = getUserBusiness(iwc); this.iwrb = iwc.getIWMainApplication().getBundle(CourseConstants.IW_BUNDLE_IDENTIFIER).getResourceBundle(this.locale);
if (req.getParameter(CourseBlock.PARAMETER_COURSE_PK) != null) {
4
OpenNTF/POI4Xpages
poi4xpages/bundles/biz.webgate.dominoext.poi/src/biz/webgate/dominoext/poi/component/kernel/document/EmbeddedDataSourceExportProcessor.java
[ "public class DocumentTable extends AbstractDataExporter {\n\n\t/*\n\t * private String m_Var; private String m_Index; private Integer m_StepSize;\n\t * private IExportSource m_DataSource; private String m_DataSourceVar;\n\t */\n\tprivate Integer m_StartRow;\n\tprivate List<DocColumnDefinition> m_DocColumns;\n\tprivate Integer m_MaxRow;\n\tprivate Integer m_TableNr;\n\tprivate List<DocCellValue> m_DocCellValues;\n\tprivate Boolean m_IncludeHeader;\n\n\tpublic List<DocCellValue> getDocCellValues() {\n\t\treturn m_DocCellValues;\n\t}\n\n\tpublic void setDocCellValues(List<DocCellValue> docCellValues) {\n\t\tm_DocCellValues = docCellValues;\n\t}\n\n\tpublic void addDocCellValue(DocCellValue icvCurrent) {\n\t\tif (m_DocCellValues == null) {\n\t\t\tm_DocCellValues = new ArrayList<>();\n\t\t}\n\t\tm_DocCellValues.add(icvCurrent);\n\t}\n\n\tpublic int getStartRow() {\n\t\tif (m_StartRow != null) {\n\t\t\treturn m_StartRow;\n\t\t}\n\t\tValueBinding vb = getValueBinding(\"startRow\");\n\t\tif (vb != null) {\n\t\t\tInteger intValue = (Integer) vb.getValue(getFacesContext());\n\t\t\tif (intValue != null)\n\t\t\t\treturn intValue;\n\t\t}\n\t\treturn 0;\n\n\t}\n\n\tpublic void setStartRow(int startRow) {\n\t\tm_StartRow = startRow;\n\t}\n\n\n\tpublic List<DocColumnDefinition> getDocColumns() {\n\t\treturn m_DocColumns;\n\t}\n\n\tpublic void setDocColumns(List<DocColumnDefinition> docColumns) {\n\t\tm_DocColumns = docColumns;\n\t}\n\n\tpublic void addDocColumn(DocColumnDefinition cdCurrent) {\n\t\tif (m_DocColumns == null) {\n\t\t\tm_DocColumns = new ArrayList<>();\n\t\t}\n\t\tm_DocColumns.add(cdCurrent);\n\t}\n\n\tpublic int getMaxRow() {\n\t\tif (m_MaxRow != null) {\n\t\t\treturn m_MaxRow;\n\t\t}\n\t\tValueBinding vb = getValueBinding(\"maxRow\");\n\t\tif (vb != null) {\n\t\t\tInteger intValue = (Integer) vb.getValue(getFacesContext());\n\t\t\tif (intValue != null)\n\t\t\t\treturn intValue;\n\t\t}\n\t\treturn 100;\n\n\t}\n\n\tpublic void setMaxRow(int maxRow) {\n\t\tm_MaxRow = maxRow;\n\t}\n\n\tpublic int getTableNr() {\n\t\treturn m_TableNr;\n\t}\n\n\tpublic void setTableNr(int tableNr) {\n\t\tm_TableNr = tableNr;\n\t}\n\t/*\n\t * public IExportSource getDataSource() { return m_DataSource; }\n\t *\n\t * public void setDataSource(IExportSource dataSource) { m_DataSource =\n\t * dataSource; }\n\t *\n\t * public int getStepSize() { if (m_StepSize != null) { return m_StepSize; }\n\t * ValueBinding vb = getValueBinding(\"stepSize\"); if (vb != null) { Integer\n\t * intValue = (Integer) vb.getValue(getFacesContext()); if (intValue !=\n\t * null) return intValue; } return 1; }\n\t *\n\t * public void setStepSize(int stepSize) { m_StepSize = stepSize; }\n\t *\n\t * public String getVar() { return m_Var; }\n\t *\n\t * public void setVar(String var) { m_Var = var; }\n\t *\n\t * public String getIndex() { return m_Index; }\n\t *\n\t * public void setIndex(String index) { m_Index = index; }\n\t *\n\t * public String getDataSourceVar() { if (m_DataSourceVar != null) { return\n\t * m_DataSourceVar; } ValueBinding vb = getValueBinding(\"dataSourceVar\"); if\n\t * (vb != null) { String strValue = (String) vb.getValue(getFacesContext());\n\t * if (strValue != null) return strValue; } return null;\n\t *\n\t * }\n\t *\n\t * public void setDataSourceVar(String dataSourceVar) { m_DataSourceVar =\n\t * dataSourceVar; }\n\t *\n\t * public DataSource getPageDataSource() { String strName =\n\t * getDataSourceVar(); System.out.println(strName); if\n\t * (StringUtil.isNotEmpty(strName)) {\n\t *\n\t * UIViewRoot vrCurrent = getFacesContext().getViewRoot(); if (vrCurrent\n\t * instanceof UIViewRootEx) { for (DataSource dsCurrent : ((UIViewRootEx)\n\t * vrCurrent).getData()) { if (strName.equals(dsCurrent.getVar())) { return\n\t * dsCurrent; } } } } System.out.println(\"Datasource name:\" +\n\t * m_DataSourceVar); return null;\n\t *\n\t * }\n\t */\n\n\n\n\n\n\tpublic boolean getIncludeHeader() {\n\t\tif (null != m_IncludeHeader) {\n\t\t\treturn m_IncludeHeader;\n\t\t}\n\t\tValueBinding _vb = getValueBinding(\"includeHeader\"); //$NON-NLS-1$\n\t\tif (_vb != null) {\n\t\t\treturn (Boolean) _vb.getValue(FacesContext.getCurrentInstance());\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic void setIncludeHeader(boolean includeHeader) {\n\t\tm_IncludeHeader = includeHeader;\n\t}\n\n\t@Override\n\tpublic Object saveState(FacesContext context) {\n\t\ttry {\n\n\t\t\tObject[] state = new Object[7];\n\t\t\tstate[0] = super.saveState(context);\n\t\t\tstate[1] = StateHolderUtil.saveList(context, m_DocCellValues);\n\t\t\tstate[2] = m_StartRow;\n\t\t\tstate[3] = StateHolderUtil.saveList(context, m_DocColumns);\n\t\t\tstate[4] = m_MaxRow;\n\t\t\tstate[5] = m_TableNr;\n\t\t\tstate[6] = m_IncludeHeader;\n\t\t\t/*\n\t\t\t * state[5] = m_StepSize; state[6] =\n\t\t\t * FacesUtil.objectToSerializable(getFacesContext(), m_DataSource);\n\t\t\t * state[7] = m_DataSourceVar; state[8] = m_Var; state[9] = m_Index;\n\t\t\t */\n\t\t\treturn state;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void restoreState(FacesContext context, Object arg1) {\n\t\tObject[] state = (Object[]) arg1;\n\t\tsuper.restoreState(context, state[0]);\n\t\tm_DocCellValues = StateHolderUtil.restoreList(context, getComponent(), state[1]);\n\t\tm_StartRow = (Integer) state[2];\n\t\tm_DocColumns = StateHolderUtil.restoreList(context, getComponent(), state[3]);\n\t\tm_MaxRow = (Integer) state[4];\n\t\tm_TableNr = (Integer) state[5];\n\t\tm_IncludeHeader = (Boolean) state[6];\n\t}\n\n\n}", "public class DocColumnDefinition extends AbstractDefinition implements IDefinition {\n\tprivate Integer m_ColumnNumber;\n\tprivate String m_ColumnTitle;\n\tprivate String m_ColumnHeader;\n\tprivate Integer m_RowShift = 0;\n\n\t// private PoiCellStyle m_PoiCellStyle;\n\n\tpublic int getColumnNumber() {\n\t\tif (m_ColumnNumber != null) {\n\t\t\treturn m_ColumnNumber;\n\t\t}\n\t\tValueBinding vb = getValueBinding(\"columnNumber\");\n\t\tif (vb != null) {\n\t\t\tInteger intValue = (Integer) vb.getValue(getFacesContext());\n\t\t\tif (intValue != null) {\n\t\t\t\treturn intValue;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\n\t}\n\n\tpublic void setColumnNumber(int columnNumber) {\n\t\tm_ColumnNumber = columnNumber;\n\t}\n\n\tpublic int getRowShift() {\n\t\tif (m_RowShift != null) {\n\t\t\treturn m_RowShift;\n\t\t}\n\t\tValueBinding vb = getValueBinding(\"rowShift\");\n\t\tif (vb != null) {\n\t\t\tInteger intValue = (Integer) vb.getValue(getFacesContext());\n\t\t\tif (intValue != null) {\n\t\t\t\treturn intValue;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\n\t}\n\n\tpublic void setRowShift(int rowShift) {\n\t\tm_RowShift = rowShift;\n\t}\n\n\n\t@Override\n\tpublic String getColumnTitle() {\n\t\tif (m_ColumnTitle != null) {\n\t\t\treturn m_ColumnTitle;\n\t\t}\n\t\tValueBinding vb = getValueBinding(\"columnTitle\");\n\t\tif (vb != null) {\n\t\t\tString strValue = (String) vb.getValue(getFacesContext());\n\t\t\tif (strValue != null) {\n\t\t\t\treturn strValue;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void setColumnTitle(String columnTitle) {\n\t\tm_ColumnTitle = columnTitle;\n\t}\n\n\tpublic String getColumnHeader() {\n\t\tif (m_ColumnHeader != null) {\n\t\t\treturn m_ColumnHeader;\n\t\t}\n\t\tValueBinding vb = getValueBinding(\"columnHeader\");\n\t\tif (vb != null) {\n\t\t\tString strValue = (String) vb.getValue(getFacesContext());\n\t\t\tif (strValue != null) {\n\t\t\t\treturn strValue;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void setColumnHeader(String columnHeader) {\n\t\tm_ColumnHeader = columnHeader;\n\t}\n\n\t@Override\n\tpublic Object saveState(FacesContext context) {\n\t\tObject[] state = new Object[6];\n\t\tstate[0] = super.saveState(context);\n\t\tstate[1] = m_ColumnNumber;\n\t\tstate[2] = m_RowShift;\n\t\tstate[3] = m_ColumnTitle;\n\t\tstate[4] = StateHolderUtil\n\t\t\t\t.saveMethodBinding(context, getComputeValue());\n\t\tstate[5] = m_ColumnHeader;\n\t\treturn state;\n\t}\n\n\t@Override\n\tpublic void restoreState(FacesContext context, Object arg1) {\n\t\tObject[] state = (Object[]) arg1;\n\t\tsuper.restoreState(context, state[0]);\n\t\tm_ColumnNumber = (Integer) state[1];\n\t\tm_RowShift = (Integer) state[2];\n\t\tm_ColumnTitle = (String) state[3];\n\t\tsetComputeValue(StateHolderUtil.restoreMethodBinding(context,\n\t\t\t\tgetComponent(), state[4]));\n\t\tm_ColumnHeader = (String) state[5];\n\t}\n\n\n}", "public interface IExportSource {\n\n\tpublic Object getValue(IDefinition idCurrent, FacesContext context);\n\n\tpublic int accessNextRow();\n\n\tpublic int accessSource() throws POIException;\n\n\tpublic int closeSource();\n\n\tpublic Object getDataRow();\n}", "public enum RequestVarsHandler {\n\tINSTANCE;\n\tpublic void pushVars(FacesContext context, String varobject, String varIndex, Object object, int index) {\n\n\t\tString varNameUse = buildVarName(varobject, \"exportRow\");\n\t\tString indNameUse = buildVarName(varIndex, \"indexRow\");\n\n\t\tMap<String, Object> localMap = TypedUtil.getRequestMap(context.getExternalContext());\n\t\tlocalMap.put(varNameUse, object);\n\t\tlocalMap.put(indNameUse, Integer.valueOf(index));\n\t}\n\n\tpublic void removeVars(FacesContext context, String varobject, String varIndex) {\n\t\tString varNameUse = buildVarName(varobject, \"exportRow\");\n\t\tString indNameUse = buildVarName(varIndex, \"indexRow\");\n\n\t\tMap<String, Object> localMap = TypedUtil.getRequestMap(context.getExternalContext());\n\t\tlocalMap.remove(varNameUse);\n\t\tlocalMap.remove(indNameUse);\n\t}\n\n\tpublic List<DataPublisher.ShadowedObject> publishControlData(FacesContext paramFacesContext, String varobject, String varIndex) {\n\t\tString varNameUse = buildVarName(varobject, \"exportRow\");\n\t\tString indNameUse = buildVarName(varIndex, \"indexRow\");\n\n\t\tDataPublisher localDataPublisher = ((FacesContextEx) paramFacesContext).getDataPublisher();\n\t\tList<DataPublisher.ShadowedObject> localList = null;\n\t\tlocalList = localDataPublisher.pushShadowObjects(localList, new String[] { varNameUse, indNameUse });\n\t\treturn localList;\n\t}\n\n\tpublic void revokeControlData(List<DataPublisher.ShadowedObject> paramList, FacesContext paramFacesContext) {\n\t\tDataPublisher localDataPublisher = ((FacesContextEx) paramFacesContext).getDataPublisher();\n\t\tlocalDataPublisher.popObjects(paramList);\n\t}\n\n\tprivate String buildVarName(String name, String defaultName) {\n\t\treturn StringUtil.isEmpty(name) ? defaultName : name;\n\t}\n}", "public class POIException extends Exception {\n\n\n\t/**\n\t *\n\t */\n\tprivate static final long serialVersionUID = 1L;\n\tpublic POIException() {\n\t\tsuper();\n\t}\n\tpublic POIException(String strMessage) {\n\t\tsuper(strMessage);\n\t}\n\tpublic POIException(Throwable t) {\n\t\tsuper(t);\n\t}\n\tpublic POIException(String strMessage,Throwable t) {\n\t\tsuper(strMessage,t);\n\t}\n}", "public class LoggerFactory {\n\tprivate static HashMap<String, Logger> m_RegistredLoggers = new HashMap<>();\n\n\tprivate static int m_logLevel = -1;\n\tprivate static int m_logLevelPDF = -1;\n\tprivate static int m_logLevelFOP = -1;\n\n\tpublic static Logger getLogger(String strName) {\n\t\ttry {\n\t\t\tif (m_RegistredLoggers.containsKey(strName)) {\n\t\t\t\treturn m_RegistredLoggers.get(strName);\n\t\t\t}\n\t\t\tLogger logRC = java.util.logging.Logger.getAnonymousLogger();\n\t\t\tif (m_logLevel == -1) {\n\t\t\t\tcheckLogLevel();\n\t\t\t}\n\t\t\tlogRC.setLevel(getLogLevel(getLogLevelForClass(strName)));\n\t\t\tConsoleHandler ch = new ConsoleHandler(strName,\n\t\t\t\t\tgetLogLevel(m_logLevel));\n\t\t\tlogRC.addHandler(ch);\n\t\t\tm_RegistredLoggers.put(strName, logRC);\n\t\t\treturn logRC;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Level getLogLevel(int nLevel) {\n\t\tswitch (nLevel) {\n\t\tcase 0:\n\t\t\treturn Level.OFF;\n\t\tcase 1:\n\t\t\treturn Level.SEVERE;\n\t\tcase 2:\n\t\t\treturn Level.WARNING;\n\t\tcase 3:\n\t\t\treturn Level.INFO;\n\t\tcase 4:\n\t\t\treturn Level.FINE;\n\t\tcase 5:\n\t\t\treturn Level.FINER;\n\t\tcase 6:\n\t\t\treturn Level.FINEST;\n\n\t\t}\n\t\treturn Level.ALL;\n\n\t}\n\n\tprivate static void checkLogLevel() {\n\t\ttry {\n\t\t\tString strPOI = LibUtil.getCurrentSession().getEnvironmentString(\n\t\t\t\t\t\"DEBUG_POI\", true);\n\t\t\tif (strPOI == null || \"\".equals(strPOI)) {\n\t\t\t\tm_logLevel = 1;\n\t\t\t}\n\t\t\tString strPOIPDF = LibUtil.getCurrentSession()\n\t\t\t\t\t.getEnvironmentString(\"DEBUG_POI_PDF\", true);\n\t\t\tif (strPOIPDF == null || \"\".equals(strPOIPDF)) {\n\t\t\t\tm_logLevelPDF = 1;\n\t\t\t}\n\t\t\tString strPOIFOP = LibUtil.getCurrentSession()\n\t\t\t\t\t.getEnvironmentString(\"DEBUG_POI_FOP\", true);\n\t\t\tif (strPOIFOP == null || \"\".equals(strPOIFOP)) {\n\t\t\t\tm_logLevelFOP = 1;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (strPOI != null && !\"\".equals(strPOI)) {\n\t\t\t\t\tm_logLevel = Integer.parseInt(strPOI);\n\t\t\t\t}\n\t\t\t\tif (strPOIPDF != null && !\"\".equals(strPOIPDF)) {\n\t\t\t\t\tm_logLevelPDF = Integer.parseInt(strPOIPDF);\n\t\t\t\t}\n\t\t\t\tif (strPOIFOP != null && !\"\".equals(strPOIFOP)) {\n\t\t\t\t\tm_logLevelFOP = Integer.parseInt(strPOIFOP);\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tm_logLevel = 0;\n\t\t\t}\n\t\t\tSystem.out.println(\"POI LOG-LEVEL is set to: \" + strPOI +\" / \"+ m_logLevel);\n\t\t\tSystem.out.println(\"POI PDF LOG-LEVEL is set to: \" + strPOIPDF+\" / \"+ m_logLevelPDF);\n\t\t\tSystem.out.println(\"POI FOP LOG-LEVEL is set to: \" + strPOIFOP+\" / \"+ m_logLevelFOP);\n\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tprivate static int getLogLevelForClass(String strClass) {\n\t\tif (strClass == null) {\n\t\t\treturn m_logLevel;\n\t\t}\n\t\tif (strClass.toLowerCase().startsWith(\n\t\t\t\t\"biz.webgate.dominoext.poi.pdf.fopdocx4j\")) {\n\t\t\treturn m_logLevelFOP;\n\t\t}\n\t\tif (strClass.toLowerCase().startsWith(\"biz.webgate.dominoext.poi.pdf\")) {\n\t\t\treturn m_logLevelPDF;\n\t\t}\n\t\treturn m_logLevel;\n\t}\n}" ]
import biz.webgate.dominoext.poi.util.RequestVarsHandler; import biz.webgate.dominoext.poi.utils.exceptions.POIException; import biz.webgate.dominoext.poi.utils.logging.LoggerFactory; import java.util.List; import java.util.logging.Logger; import javax.faces.context.FacesContext; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import com.ibm.xsp.util.DataPublisher.ShadowedObject; import biz.webgate.dominoext.poi.component.data.document.table.DocumentTable; import biz.webgate.dominoext.poi.component.data.document.table.cell.DocColumnDefinition; import biz.webgate.dominoext.poi.component.sources.IExportSource;
/** * Copyright (c) 2012-2021 WebGate Consulting AG and others * * 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 biz.webgate.dominoext.poi.component.kernel.document; public enum EmbeddedDataSourceExportProcessor implements IDataSourceExportProcessor { INSTANCE; @Override
public XWPFTable processExportTable(DocumentTable lstExport, XWPFDocument dxDocument, FacesContext context, String strVar, String strIndex) throws POIException {
0
Fabric3/spring-samples
apps/bigbank/bigbank-client/src/main/java/org/fabric3/samples/bigbank/client/ws/LoanServiceClient.java
[ "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"address\", propOrder = {\n \"city\",\n \"state\",\n \"street\",\n \"zip\"\n})\npublic class Address {\n\n protected String city;\n protected String state;\n protected String street;\n protected int zip;\n\n /**\n * Gets the value of the city property.\n *\n * @return possible object is {@link String }\n */\n public String getCity() {\n return city;\n }\n\n /**\n * Sets the value of the city property.\n *\n * @param value allowed object is {@link String }\n */\n public void setCity(String value) {\n this.city = value;\n }\n\n /**\n * Gets the value of the state property.\n *\n * @return possible object is {@link String }\n */\n public String getState() {\n return state;\n }\n\n /**\n * Sets the value of the state property.\n *\n * @param value allowed object is {@link String }\n */\n public void setState(String value) {\n this.state = value;\n }\n\n /**\n * Gets the value of the street property.\n *\n * @return possible object is {@link String }\n */\n public String getStreet() {\n return street;\n }\n\n /**\n * Sets the value of the street property.\n *\n * @param value allowed object is {@link String }\n */\n public void setStreet(String value) {\n this.street = value;\n }\n\n /**\n * Gets the value of the zip property.\n */\n public int getZip() {\n return zip;\n }\n\n /**\n * Sets the value of the zip property.\n */\n public void setZip(int value) {\n this.zip = value;\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"loanApplication\", propOrder = {\n \"options\",\n \"status\"\n})\npublic class LoanApplication {\n\n @XmlElement(nillable = true)\n protected List<LoanOption> options;\n protected int status;\n\n /**\n * Gets the value of the options property.\n * <p/>\n * <p/>\n * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be\n * present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for the options property.\n * <p/>\n * <p/>\n * For example, to add a new item, do as follows:\n * <pre>\n * getOptions().add(newItem);\n * </pre>\n * <p/>\n * <p/>\n * <p/>\n * Objects of the following type(s) are allowed in the list {@link LoanOption }\n */\n public List<LoanOption> getOptions() {\n if (options == null) {\n options = new ArrayList<LoanOption>();\n }\n return this.options;\n }\n\n /**\n * Gets the value of the status property.\n */\n public int getStatus() {\n return status;\n }\n\n /**\n * Sets the value of the status property.\n */\n public void setStatus(int value) {\n this.status = value;\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"loanOption\", propOrder = {\n \"apr\",\n \"rate\",\n \"type\"\n})\npublic class LoanOption {\n\n protected float apr;\n protected float rate;\n protected String type;\n\n /**\n * Gets the value of the apr property.\n */\n public float getApr() {\n return apr;\n }\n\n /**\n * Sets the value of the apr property.\n */\n public void setApr(float value) {\n this.apr = value;\n }\n\n /**\n * Gets the value of the rate property.\n */\n public float getRate() {\n return rate;\n }\n\n /**\n * Sets the value of the rate property.\n */\n public void setRate(float value) {\n this.rate = value;\n }\n\n /**\n * Gets the value of the type property.\n *\n * @return possible object is {@link String }\n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n *\n * @param value allowed object is {@link String }\n */\n public void setType(String value) {\n this.type = value;\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"loanRequest\", propOrder = {\n \"amount\",\n \"downPayment\",\n \"email\",\n \"propertyAddress\",\n \"ssn\"\n})\npublic class LoanRequest {\n\n protected double amount;\n protected double downPayment;\n protected String email;\n protected Address propertyAddress;\n @XmlElement(name = \"SSN\")\n protected String ssn;\n\n /**\n * Gets the value of the amount property.\n */\n public double getAmount() {\n return amount;\n }\n\n /**\n * Sets the value of the amount property.\n */\n public void setAmount(double value) {\n this.amount = value;\n }\n\n /**\n * Gets the value of the downPayment property.\n */\n public double getDownPayment() {\n return downPayment;\n }\n\n /**\n * Sets the value of the downPayment property.\n */\n public void setDownPayment(double value) {\n this.downPayment = value;\n }\n\n /**\n * Gets the value of the email property.\n *\n * @return possible object is {@link String }\n */\n public String getEmail() {\n return email;\n }\n\n /**\n * Sets the value of the email property.\n *\n * @param value allowed object is {@link String }\n */\n public void setEmail(String value) {\n this.email = value;\n }\n\n /**\n * Gets the value of the propertyAddress property.\n *\n * @return possible object is {@link Address }\n */\n public Address getPropertyAddress() {\n return propertyAddress;\n }\n\n /**\n * Sets the value of the propertyAddress property.\n *\n * @param value allowed object is {@link Address }\n */\n public void setPropertyAddress(Address value) {\n this.propertyAddress = value;\n }\n\n /**\n * Gets the value of the ssn property.\n *\n * @return possible object is {@link String }\n */\n public String getSSN() {\n return ssn;\n }\n\n /**\n * Sets the value of the ssn property.\n *\n * @param value allowed object is {@link String }\n */\n public void setSSN(String value) {\n this.ssn = value;\n }\n\n}", "@WebService(name = \"LoanService\", targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\")\n@XmlSeeAlso({\n ObjectFactory.class\n})\npublic interface LoanService {\n\n\n /**\n * @param arg0\n */\n @WebMethod\n @RequestWrapper(localName = \"accept\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Accept\")\n @ResponseWrapper(localName = \"acceptResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.AcceptResponse\")\n public void accept(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n OptionSelection arg0);\n\n /**\n * @param arg0\n * @return returns org.fabric3.samples.bigbank.client.ws.loan.LoanApplication\n */\n @WebMethod\n @WebResult(targetNamespace = \"\")\n @RequestWrapper(localName = \"retrieve\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Retrieve\")\n @ResponseWrapper(localName = \"retrieveResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.RetrieveResponse\")\n public LoanApplication retrieve(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n long arg0);\n\n /**\n * @param arg0\n * @return returns long\n */\n @WebMethod\n @WebResult(targetNamespace = \"\")\n @RequestWrapper(localName = \"apply\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Apply\")\n @ResponseWrapper(localName = \"applyResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.ApplyResponse\")\n public long apply(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n LoanRequest arg0);\n\n /**\n * @param arg0\n */\n @WebMethod\n @RequestWrapper(localName = \"decline\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Decline\")\n @ResponseWrapper(localName = \"declineResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.DeclineResponse\")\n public void decline(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n long arg0);\n\n}", "@WebServiceClient(name = \"LoanServiceService\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n wsdlLocation = \"http://localhost:8181/loanService?wsdl\")\npublic class LoanServiceService\n extends Service {\n\n private final static URL LOANSERVICESERVICE_WSDL_LOCATION;\n private final static Logger logger = Logger.getLogger(org.fabric3.samples.bigbank.client.ws.loan.LoanServiceService.class.getName());\n\n static {\n URL url = null;\n try {\n URL baseUrl;\n baseUrl = org.fabric3.samples.bigbank.client.ws.loan.LoanServiceService.class.getResource(\".\");\n url = new URL(baseUrl, \"http://localhost:8181/loanService?wsdl\");\n } catch (MalformedURLException e) {\n logger.warning(\"Failed to create URL for the wsdl Location: 'http://localhost:8181/loanService?wsdl', retrying as a local file\");\n logger.warning(e.getMessage());\n }\n LOANSERVICESERVICE_WSDL_LOCATION = url;\n }\n\n public LoanServiceService(URL wsdlLocation, QName serviceName) {\n super(wsdlLocation, serviceName);\n }\n\n public LoanServiceService() {\n super(LOANSERVICESERVICE_WSDL_LOCATION, new QName(\"http://loan.api.bigbank.samples.fabric3.org/\", \"LoanServiceService\"));\n }\n\n /**\n * @return returns LoanService\n */\n @WebEndpoint(name = \"LoanServicePort\")\n public LoanService getLoanServicePort() {\n return super.getPort(new QName(\"http://loan.api.bigbank.samples.fabric3.org/\", \"LoanServicePort\"), LoanService.class);\n }\n\n /**\n * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the\n * <code>features</code> parameter will have their default values.\n * @return returns LoanService\n */\n @WebEndpoint(name = \"LoanServicePort\")\n public LoanService getLoanServicePort(WebServiceFeature... features) {\n return super.getPort(new QName(\"http://loan.api.bigbank.samples.fabric3.org/\", \"LoanServicePort\"), LoanService.class, features);\n }\n\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"optionSelection\", propOrder = {\n \"id\",\n \"type\"\n})\npublic class OptionSelection {\n\n protected long id;\n protected String type;\n\n /**\n * Gets the value of the id property.\n */\n public long getId() {\n return id;\n }\n\n /**\n * Sets the value of the id property.\n */\n public void setId(long value) {\n this.id = value;\n }\n\n /**\n * Gets the value of the type property.\n *\n * @return possible object is {@link String }\n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n *\n * @param value allowed object is {@link String }\n */\n public void setType(String value) {\n this.type = value;\n }\n\n}" ]
import javax.xml.namespace.QName; import java.net.URL; import java.util.UUID; import org.fabric3.samples.bigbank.client.ws.loan.Address; import org.fabric3.samples.bigbank.client.ws.loan.LoanApplication; import org.fabric3.samples.bigbank.client.ws.loan.LoanOption; import org.fabric3.samples.bigbank.client.ws.loan.LoanRequest; import org.fabric3.samples.bigbank.client.ws.loan.LoanService; import org.fabric3.samples.bigbank.client.ws.loan.LoanServiceService; import org.fabric3.samples.bigbank.client.ws.loan.OptionSelection;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.fabric3.samples.bigbank.client.ws; /** * Demonstrates interacting with the BigBank Loan Service via web services. This client would typically be a part of a third-party system which interacted with * BigBank. * <p/> * Note the URL needs to be changed depending on the runtime the application is deployed to. */ public class LoanServiceClient { public static void main(String[] args) throws Exception { // Note you must change the port on the URL when loan service deployed in the cluster without a load-balancer on localhost // Zone 1 port: 8182 URL url = new URL("http://localhost:8180/loanService?wsdl"); // URL when loan service deployed to WebLogic without a load-balancer and a Managed server set to port 7003 on localhost // URL url = new URL("http://localhost:7003/loanService?wsdl"); QName name = new QName("http://loan.api.bigbank.samples.fabric3.org/", "LoanServiceService"); LoanServiceService endpoint = new LoanServiceService(url, name); LoanService loanService = endpoint.getLoanServicePort(); // apply for a loan
LoanRequest request = new LoanRequest();
3
Ghosts/Maus
src/main/java/GUI/Views/ClientView.java
[ "public class BottomBar implements Repository {\n private static Label connectionsLabel = null;\n\n public static Label getConnectionsLabel() {\n return connectionsLabel;\n }\n\n public HBox getBottomBar() {\n HBox hBox = new HBox();\n HBox.setHgrow(hBox, Priority.ALWAYS);\n VBox vBox = new VBox();\n vBox.getStylesheets().add(getClass().getResource(\"/css/global.css\").toExternalForm());\n VBox.setVgrow(vBox, Priority.ALWAYS);\n connectionsLabel = new Label(\" Connections: \" + CONNECTIONS.size());\n connectionsLabel = (Label) Styler.styleAdd(connectionsLabel, \"label-light\");\n vBox.getChildren().add(connectionsLabel);\n hBox.getChildren().add(vBox);\n hBox.setId(\"stat-bar\");\n return hBox;\n }\n}", "public class ClientList implements Repository {\n private static TableView tableView;\n\n public static TableView getTableView() {\n return tableView;\n }\n\n public TableView getClientList() {\n\n tableView = new TableView();\n tableView.setEditable(true);\n tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);\n tableView.getStylesheets().add(getClass().getResource(\"/css/global.css\").toExternalForm());\n\n TableColumn<String, String> onlineStatus = new TableColumn<>(\"Status\");\n onlineStatus.setMaxWidth(70);\n onlineStatus.setResizable(false);\n onlineStatus.setCellValueFactory(\n new PropertyValueFactory<>(\"onlineStatus\"));\n\n TableColumn<ClientObject, String> nickName = new TableColumn<>(\"Nickname\");\n nickName.setMinWidth(150);\n nickName.setMaxWidth(200);\n nickName.setResizable(false);\n nickName.setCellValueFactory(new PropertyValueFactory<>(\"nickName\"));\n nickName.setCellFactory(TextFieldTableCell.forTableColumn());\n nickName.setOnEditCommit(\n t -> t.getTableView().getItems().get(\n t.getTablePosition().getRow()).setNickName(t.getNewValue())\n );\n\n TableColumn<ClientObject, String> IP = new TableColumn<>(\"IP\");\n IP.setMinWidth(600);\n IP.setResizable(false);\n IP.setCellValueFactory(new PropertyValueFactory<>(\"IP\"));\n IP.setCellFactory(col -> {\n final TableCell<ClientObject, String> cell = new TableCell<>();\n cell.textProperty().bind(cell.itemProperty());\n cell.setOnMouseClicked(event -> {\n if (event.getButton().equals(MouseButton.SECONDARY) && cell.getTableView().getSelectionModel().getSelectedItem() != null && cell.getTableView().getSelectionModel().getSelectedItem().getClient().isConnected()) {\n IPContextMenu.getIPContextMenu(cell, event);\n }\n });\n return cell;\n });\n ObservableList<ClientObject> list = FXCollections.observableArrayList();\n list.addAll(CONNECTIONS.values());\n tableView.setItems(list);\n tableView.getColumns().addAll(onlineStatus, nickName, IP);\n\n return tableView;\n }\n}", "public class TopBar {\n\n public VBox getTopBar(Stage stage) {\n Image image = new Image(getClass().getResourceAsStream(\"/Images/logo.png\"));\n ImageView imageView = new ImageView(image);\n\n VBox vBox = new VBox();\n vBox.setAlignment(Pos.CENTER);\n Label label = (Label) Styler.styleAdd(new Label(\"Dashboard\"), \"label-light\");\n vBox.getChildren().addAll(new ImageView(new Image(getClass().getResourceAsStream(\"/Images/Icons/icon.png\"))), label);\n vBox.setPadding(new Insets(5, 10, 0, 5));\n vBox.setId(\"homeButton\");\n\n\n VBox vBox1 = new VBox();\n vBox1.setAlignment(Pos.CENTER);\n vBox1.getChildren().add(new ImageView(new Image(getClass().getResourceAsStream(\"/Images/logo.png\"))));\n vBox1.setPadding(new Insets(5, 10, 5, 5));\n\n HBox hBox = Styler.hContainer(new HBox(), vBox, vBox1);\n vBox.setOnMouseClicked(event -> Controller.changePrimaryStage(new MainView().getMainView()));\n imageView.setFitWidth(100);\n imageView.setFitHeight(50);\n return Styler.vContainer(new VBox(), new TitleBar().getMenuBar(stage), hBox);\n }\n\n public VBox getTopBarSansOptions(Stage stage) {\n Image image = new Image(getClass().getResourceAsStream(\"/Images/logo.png\"));\n ImageView imageView = new ImageView(image);\n\n VBox vBox1 = new VBox();\n vBox1.setAlignment(Pos.CENTER);\n vBox1.getChildren().add(new ImageView(new Image(getClass().getResourceAsStream(\"/Images/logo.png\"))));\n vBox1.setPadding(new Insets(5, 10, 5, 5));\n\n HBox hBox = Styler.hContainer(new HBox(), vBox1);\n imageView.setFitWidth(100);\n imageView.setFitHeight(50);\n return Styler.vContainer(new VBox(), new TitleBar().getMenuBar(stage), hBox);\n }\n}", "public class Styler {\n /* Adds a CSS style class to a Node. */\n public static Node styleAdd(Node node, String styleName) {\n node.getStyleClass().add(styleName);\n return node;\n }\n\n /* Returns a VBox with the provided nodes added to it. */\n public static VBox vContainer(Node... nodes) {\n VBox vBox = new VBox();\n VBox.setVgrow(vBox, Priority.ALWAYS);\n vBox.setMaxWidth(Double.MAX_VALUE);\n for (Node r : nodes) {\n vBox.getChildren().add(r);\n }\n return vBox;\n }\n\n /* Returns a VBox with the provided nodes added to it, spaced by an int. */\n public static VBox vContainer(int spacing, Node... nodes) {\n VBox vBox = new VBox(spacing);\n VBox.setVgrow(vBox, Priority.ALWAYS);\n vBox.setMaxWidth(Double.MAX_VALUE);\n for (Node r : nodes) {\n vBox.getChildren().add(r);\n }\n return vBox;\n }\n\n /* Returns a HBox with the provided nodes added to it, spaced by an int. */\n public static HBox hContainer(int spacing, Node... nodes) {\n HBox hBox = new HBox(spacing);\n HBox.setHgrow(hBox, Priority.ALWAYS);\n hBox.setMaxWidth(Double.MAX_VALUE);\n for (Node r : nodes) {\n hBox.getChildren().add(r);\n }\n return hBox;\n }\n\n /* Returns a HBox with the provided nodes added to it. */\n public static HBox hContainer(Node... nodes) {\n HBox hBox = new HBox();\n HBox.setHgrow(hBox, Priority.ALWAYS);\n hBox.setMaxWidth(Double.MAX_VALUE);\n for (Node r : nodes) {\n hBox.getChildren().add(r);\n }\n return hBox;\n }\n\n}", "public class Maus extends Application {\n private static Stage primaryStage;\n private static Server server = new Server();\n public static SystemTray systemTray;\n\n public static Stage getPrimaryStage() {\n return primaryStage;\n }\n\n public static void main(String[] args) {\n if (lockInstance()) {\n launch(args);\n } else {\n System.exit(0);\n }\n }\n\n /* Ensure only one instance of Maus is running on a system (server, not client). */\n private static boolean lockInstance() {\n try {\n final File file = new File(System.getProperty(\"user.home\") + \"/.lock\");\n final RandomAccessFile randomAccessFile = new RandomAccessFile(file, \"rw\");\n final FileLock fileLock = randomAccessFile.getChannel().tryLock();\n if (fileLock != null) {\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n try {\n fileLock.release();\n randomAccessFile.close();\n file.delete();\n /*Before Maus is closed - write Maus data to file (server settings, clients, etc.) */\n try {\n PseudoBase.writeMausData();\n Logger.log(Level.INFO, \"MausData saved to file. \");\n } catch (IOException e) {\n Logger.log(Level.ERROR, e.toString());\n }\n } catch (Exception e) {\n Logger.log(Level.ERROR, e.toString());\n }\n }));\n return true;\n }\n } catch (Exception e) {\n Logger.log(Level.ERROR, e.toString());\n }\n return false;\n }\n\n @Override\n public void start(Stage primaryStage) throws IOException, ClassNotFoundException {\n Maus.primaryStage = primaryStage;\n /* Ensure that the necessary files exist */\n new PseudoBase().createMausData();\n /* Load data from files - including client data, server settings, etc. */\n new PseudoBase().loadData();\n /* Set up primary view */\n getPrimaryStage().setTitle(MausSettings.CURRENT_VERSION);\n\n SwingUtilities.invokeLater(this::addAppToTray);\n Platform.setImplicitExit(false);\n Scene mainScene = new Scene(new MainView().getMainView(), 900, 500);\n mainScene.getStylesheets().add(getClass().getResource(\"/css/global.css\").toExternalForm());\n getPrimaryStage().setScene(mainScene);\n getPrimaryStage().getIcons().add(new Image(getClass().getResourceAsStream(\"/Images/Icons/icon.png\")));\n getPrimaryStage().setOnCloseRequest(event -> System.exit(0));\n\n /* Maus is running! */\n Logger.log(Level.INFO, \"Maus is running.\");\n getPrimaryStage().initStyle(StageStyle.UNDECORATED);\n\n /* Set user's IP as Server IP */\n URL whatismyip = new URL(\"http://checkip.amazonaws.com\");\n BufferedReader in = new BufferedReader(new InputStreamReader(\n whatismyip.openStream()));\n\n String ip = in.readLine();\n MausSettings.CONNECTION_IP = ip;\n getPrimaryStage().show();\n\n /* Start the server to listen for client connections. */\n Runnable startServer = server;\n new Thread(startServer).start();\n }\n\n\n /* Attempt to add Maus to the System Tray - regardless of persistence (handled in TitleBar) */\n private void addAppToTray() {\n try {\n Toolkit.getDefaultToolkit();\n\n if (!SystemTray.isSupported()) {\n System.out.println(\"No system tray support, application exiting.\");\n Platform.exit();\n }\n\n systemTray = SystemTray.getSystemTray();\n java.awt.Image image = ImageIO.read(getClass().getResourceAsStream(\"/Images/Icons/icon.png\"));\n TrayIcon trayIcon = new TrayIcon(image);\n trayIcon.setImageAutoSize(true);\n trayIcon.addActionListener(event -> Platform.runLater(this::showStage));\n\n MenuItem openItem = new MenuItem(\"Open Maus\");\n openItem.addActionListener(event -> Platform.runLater(this::showStage));\n\n Font defaultFont = Font.decode(null);\n Font boldFont = defaultFont.deriveFont(java.awt.Font.BOLD);\n openItem.setFont(boldFont);\n\n MenuItem exitItem = new MenuItem(\"Exit\");\n exitItem.addActionListener(event -> {\n Platform.exit();\n systemTray.remove(trayIcon);\n System.exit(0);\n });\n final PopupMenu popup = new PopupMenu();\n popup.add(openItem);\n popup.addSeparator();\n popup.add(exitItem);\n trayIcon.setPopupMenu(popup);\n systemTray.add(trayIcon);\n } catch (Exception e) {\n Logger.log(Level.ERROR, \"Unable to access system tray.\");\n e.printStackTrace();\n }\n }\n\n private void showStage() {\n getPrimaryStage().setScene(new Scene(new MainView().getMainView(), 900, 500));\n getPrimaryStage().show();\n getPrimaryStage().toFront();\n }\n}" ]
import GUI.Components.BottomBar; import GUI.Components.ClientList; import GUI.Components.TopBar; import GUI.Styler; import Maus.Maus; import javafx.scene.layout.BorderPane;
package GUI.Views; class ClientView { BorderPane getClientView() { BorderPane borderPane = new BorderPane(); borderPane.getStylesheets().add(getClass().getResource("/css/global.css").toExternalForm()); borderPane.getStyleClass().add("root");
borderPane.setTop(new TopBar().getTopBar(Maus.getPrimaryStage()));
4
YagelNasManit/environment.monitor
environment.monitor.test.extension/src/main/java/org/yagel/environment/monitor/test/extension/provider/DataBaseStatusProvider.java
[ "public class StatusRandomizer {\n\n public static Status random() {\n int rnd = new Random().nextInt(Status.values().length);\n return Status.values()[rnd];\n }\n}", "public interface EnvironmentConfig {\n\n String getEnvName();\n\n String getHost();\n\n long getTaskDelay();\n\n int getAppVersion();\n\n Set<String> getCheckResources();\n\n Map<String, String> getAdditionalProperties();\n\n}", "public interface Resource {\n\n String getId();\n\n String getName();\n\n}", "public class ResourceImpl implements Resource {\n\n private String id;\n private String name;\n\n\n public ResourceImpl(String id, String name) {\n this.id = id;\n this.name = name;\n }\n\n @Override\n public String getId() {\n return this.id;\n }\n\n\n @Override\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getId(), getName());\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof ResourceImpl)) return false;\n ResourceImpl resource = (ResourceImpl) o;\n return Objects.equals(getId(), resource.getId()) &&\n Objects.equals(getName(), resource.getName());\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"id\", id)\n .append(\"name\", name)\n .toString();\n }\n}", "public enum Status {\n\n @XmlEnumValue(\"Online\")\n Online(0), // s0\n @XmlEnumValue(\"BorderLine\")\n BorderLine(1), // s1\n @XmlEnumValue(\"Unavailable\")\n Unavailable(2), // s2\n @XmlEnumValue(\"Unknown\")\n Unknown(3); // s3\n\n int seriaNumber;\n\n Status(int seriaNumber) {\n this.seriaNumber = seriaNumber;\n }\n\n public static int seriaNumbers() {\n return 3;\n }\n\n public static Status fromSerialNumber(int serialNumber) {\n return Stream.of(Status.values())\n .filter(status -> status.getSeriaNumber() == serialNumber)\n .findFirst()\n .orElseThrow(() -> new IllegalArgumentException(\"illegal resource status\"));\n }\n\n public int getSeriaNumber() {\n return seriaNumber;\n }\n\n\n}" ]
import org.yagel.environment.monitor.test.util.StatusRandomizer; import org.yagel.monitor.EnvironmentConfig; import org.yagel.monitor.Resource; import org.yagel.monitor.resource.ResourceImpl; import org.yagel.monitor.resource.Status;
package org.yagel.environment.monitor.test.extension.provider; public class DataBaseStatusProvider extends AbstractResourceStatusProvider { public DataBaseStatusProvider(EnvironmentConfig config) { super(config); } @Override public String getName() { return null; } @Override public Status reloadStatus() {
return StatusRandomizer.random();
0
dakshj/TMDb_Sample
app/src/main/java/com/daksh/tmdbsample/movielist/MovieListActivity.java
[ "public abstract class BaseActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n Icepick.restoreInstanceState(this, savedInstanceState);\n\n setupComponent();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n\n Icepick.saveInstanceState(this, outState);\n }\n\n private void setupComponent() {\n injectActivity(Injector.INSTANCE.getAppComponent());\n }\n\n public abstract void injectActivity(AppComponent appComponent);\n}", "public class SortOrder {\n\n public static final int POPULAR = 0;\n public static final int TOP_RATED = 1;\n\n public final int value;\n\n public SortOrder(@SortOrderDef int value) {\n this.value = value;\n }\n\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({POPULAR, TOP_RATED})\n public @interface SortOrderDef {}\n}", "public class Movie implements Parcelable {\n\n public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {\n @Override\n public Movie createFromParcel(Parcel source) {\n return new Movie(source);\n }\n\n @Override\n public Movie[] newArray(int size) {\n return new Movie[size];\n }\n };\n\n public static final String USER_RATING_APPEND = \" / 10\";\n\n /**\n * (Height / Width) Aspect Ratio of Poster Image\n */\n public static final double POSTER_IMAGE_ASPECT_RATIO = 1.5;\n\n /**\n * (Width / Height) Aspect Ratio of Backdrop Image\n */\n public static final double BACKDROP_IMAGE_ASPECT_RATIO = 1.77;\n\n /**\n * Date format used for parsing JSON to Date object\n */\n public static final DateFormat DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd\", Locale.getDefault());\n\n /**\n * Poster Image Quality in terms of width in px\n */\n private static final String POSTER_IMAGE_QUALITY = \"w500\";\n\n /**\n * Backdrop Image Quality in terms of width in px\n */\n private static final String BACKDROP_IMAGE_QUALITY = \"w1280\";\n\n /**\n * Image's Base URL\n */\n private static final String IMAGE_BASE_URL = \"http://image.tmdb.org/t/p/\";\n\n private final String title;\n\n @SerializedName(\"poster_path\")\n private final String posterImageUrl;\n\n @SerializedName(\"backdrop_path\")\n private final String backdropImageUrl;\n\n @SerializedName(\"overview\")\n private final String synopsis;\n\n @SerializedName(\"vote_average\")\n private final double userRating;\n\n private final Date releaseDate;\n\n public Movie(String title, String posterImageUrl, String backdropImageUrl, String synopsis,\n double userRating, Date releaseDate) {\n this.title = title;\n this.posterImageUrl = posterImageUrl;\n this.backdropImageUrl = backdropImageUrl;\n this.synopsis = synopsis;\n this.userRating = userRating;\n this.releaseDate = releaseDate;\n }\n\n protected Movie(Parcel in) {\n this.title = in.readString();\n this.posterImageUrl = in.readString();\n this.backdropImageUrl = in.readString();\n this.synopsis = in.readString();\n this.userRating = in.readDouble();\n long tmpReleaseDate = in.readLong();\n this.releaseDate = tmpReleaseDate == -1 ? null : new Date(tmpReleaseDate);\n }\n\n /**\n * Function used by DataBinding to load the poster image into an ImageView\n * by calling {@link Movie#posterImageUrl}\n */\n @BindingAdapter({\"posterImageUrl\"})\n public static void loadPosterImage(ImageView view, String imageUrl) {\n loadImage(view, IMAGE_BASE_URL + POSTER_IMAGE_QUALITY + imageUrl);\n }\n\n /**\n * Function used by DataBinding to load the backdrop image into an ImageView\n * by calling {@link Movie#backdropImageUrl}\n */\n @BindingAdapter({\"backdropImageUrl\"})\n public static void loadBackdropImage(ImageView view, String imageUrl) {\n loadImage(view, IMAGE_BASE_URL + BACKDROP_IMAGE_QUALITY + imageUrl);\n }\n\n private static void loadImage(ImageView view, String imageUrl) {\n Picasso.with(view.getContext())\n .load(imageUrl)\n .into(view);\n }\n\n /**\n * Function used by DataBinding to load the user rating into a TextView\n * by calling {@link Movie#userRating}\n */\n @BindingAdapter({\"userRating\"})\n public static void loadUserRating(TextView view, double userRating) {\n view.setText(getFormattedUserRating(userRating));\n }\n\n /**\n * @param userRating The {@link Movie#userRating} of a {@link Movie}.\n * @return A formatted String of the {@link Movie#userRating} for displaying purposes.\n */\n public static String getFormattedUserRating(double userRating) {\n double rounded = round(userRating, 2);\n\n String formatted;\n\n // Used to remove any redundant decimal zeroes.\n if (rounded == (long) rounded) {\n formatted = String.format(Locale.getDefault(), \"%d\", (long) rounded);\n } else {\n formatted = String.format(\"%s\", rounded);\n }\n\n return formatted.concat(USER_RATING_APPEND);\n }\n\n /**\n * Safely round a double to required places.\n * <br/>\n * <strong>Read:</strong> http://stackoverflow.com/a/2808648/1558717\n *\n * @param value The value to be rounded\n * @param places The decimal places to round the value to\n * @return The rounded value\n */\n private static double round(double value, int places) {\n if (places < 0) throw new IllegalArgumentException();\n\n BigDecimal bd = new BigDecimal(value);\n bd = bd.setScale(places, RoundingMode.HALF_UP);\n return bd.doubleValue();\n }\n\n /**\n * Function used by DataBinding to load the release date into a TextView\n * by calling {@link Movie#releaseDate}\n */\n @BindingAdapter({\"releaseDate\"})\n public static void loadReleaseDate(TextView view, Date releaseDate) {\n view.setText(getFormattedReleaseDate(releaseDate));\n }\n\n /**\n * @param releaseDate The {@link Movie#releaseDate} of a {@link Movie}.\n * @return A formatted String of the {@link Movie#releaseDate} for displaying purposes.\n */\n public static String getFormattedReleaseDate(Date releaseDate) {\n return new SimpleDateFormat(\"d MMM, y\", Locale.getDefault()).format(releaseDate);\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getPosterImageUrl() {\n return posterImageUrl;\n }\n\n public String getBackdropImageUrl() {\n return backdropImageUrl;\n }\n\n public String getSynopsis() {\n return synopsis;\n }\n\n public double getUserRating() {\n return userRating;\n }\n\n public Date getReleaseDate() {\n return releaseDate;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.title);\n dest.writeString(this.posterImageUrl);\n dest.writeString(this.backdropImageUrl);\n dest.writeString(this.synopsis);\n dest.writeDouble(this.userRating);\n dest.writeLong(this.releaseDate != null ? this.releaseDate.getTime() : -1);\n }\n}", "@Singleton\n@Component(modules = {\n AppModule.class,\n NetworkModule.class,\n StorageModule.class\n})\npublic interface AppComponent {\n\n void inject(TmdbApplication application);\n\n MovieListComponent getMovieListComponent(MovieListModule movieListModule);\n\n MovieDetailComponent getMovieDetailComponent(MovieDetailModule movieDetailModule);\n}", "@Module\npublic class MovieListModule {\n\n private final MovieListContract.View view;\n\n public MovieListModule(MovieListContract.View view) {\n this.view = view;\n }\n\n @Provides\n @ActivityScope\n MovieListContract.View provideMovieListView() {\n return view;\n }\n\n @Provides\n @ActivityScope\n MovieListContract.Presenter provideMovieListPresenter(TmdbApi api, AppSettings appSettings) {\n return new MovieListPresenter(view, api, appSettings);\n }\n}", "public class MovieDetailActivity extends BaseActivity implements MovieDetailContract.View {\n\n @State\n Movie movie;\n\n private ActivityMovieDetailBinding B;\n\n /**\n * Used for starting {@link MovieDetailActivity} with no transitions.\n *\n * @param context Context using which {@link MovieDetailActivity} can be started.\n * @param movie The {@link Movie} to be loaded.\n */\n public static void start(@NonNull Context context, @NonNull Movie movie) {\n context.startActivity(getCallingIntent(context, movie));\n }\n\n /**\n * Used for starting {@link MovieDetailActivity} with Shared Element Transition of the\n * Poster Image.\n *\n * @param context Context using which {@link MovieDetailActivity} can be started.\n * @param movie The {@link Movie} to be loaded.\n * @param profileImageTransitionOptions The Shared Element Transition for the Poster Image.\n */\n public static void start(@NonNull Context context, @NonNull Movie movie,\n @Nullable ActivityOptionsCompat profileImageTransitionOptions) {\n Intent intent = getCallingIntent(context, movie);\n\n if (profileImageTransitionOptions != null) {\n context.startActivity(intent, profileImageTransitionOptions.toBundle());\n } else {\n context.startActivity(intent);\n }\n }\n\n /**\n * Intent from which {@link MovieDetailActivity} can be started.\n *\n * @param context Context using which {@link MovieDetailActivity} can be started.\n * @param movie The {@link Movie} to be loaded.\n * @return Calling Intent for {@link MovieDetailActivity}.\n */\n public static Intent getCallingIntent(@NonNull Context context, @NonNull Movie movie) {\n return new Intent(context, MovieDetailActivity.class)\n .putExtra(MovieDetailFragment.ARG_MOVIE, movie);\n }\n\n @Override\n public void injectActivity(AppComponent appComponent) {\n // Not needed because injection is performed and injected dependencies are\n // used in MovieDetailFragment.\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n B = DataBindingUtil.setContentView(this, R.layout.activity_movie_detail);\n\n setSupportActionBar(B.layoutAppBarLayout.toolbar);\n\n B.layoutAppBarLayout.toolbar.setTitle(\"\");\n setSupportActionBar(B.layoutAppBarLayout.toolbar);\n\n // Show the Up button in the action bar.\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n }\n\n // savedInstanceState is non-null when there is fragment state\n // saved from previous configurations of this activity.\n // In this case, the fragment will automatically be re-added\n // to its container so we don't need to manually add it.\n if (savedInstanceState == null) {\n movie = getIntent().getParcelableExtra(MovieDetailFragment.ARG_MOVIE);\n\n if (movie == null) {\n Logger.errorLog(\"Movie is null in MovieDetailActivity!\");\n finish();\n return;\n }\n\n getSupportFragmentManager().beginTransaction()\n .add(R.id.movieDetailContainer, MovieDetailFragment.newInstance(movie))\n .commit();\n }\n\n if (movie != null) {\n B.setMovie(movie);\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n NavUtils.navigateUpTo(this, new Intent(this, MovieListActivity.class));\n return true;\n\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n}", "public class MovieDetailFragment extends BaseFragment implements MovieDetailContract.View {\n\n public static final String ARG_MOVIE = \"movie\";\n\n @Inject\n MovieDetailContract.Presenter presenter;\n\n private Movie movie;\n private MovieDetailBinding B;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public MovieDetailFragment() {\n }\n\n public static MovieDetailFragment newInstance(@NonNull final Movie movie) {\n Bundle arguments = new Bundle();\n arguments.putParcelable(MovieDetailFragment.ARG_MOVIE, movie);\n MovieDetailFragment fragment = new MovieDetailFragment();\n fragment.setArguments(arguments);\n\n return fragment;\n }\n\n @Override\n public void injectFragment(AppComponent applicationComponent) {\n applicationComponent.getMovieDetailComponent(new MovieDetailModule(this)).inject(this);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (getArguments().containsKey(ARG_MOVIE)) {\n movie = getArguments().getParcelable(ARG_MOVIE);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n B = DataBindingUtil.inflate(inflater, R.layout.movie_detail, container, false);\n\n if (movie != null) {\n B.setMovie(movie);\n }\n\n return B.getRoot();\n }\n}", "public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener {\n\n private RecyclerView.LayoutManager mLayoutManager;\n\n /**\n * The minimum amount of items to have below your current scroll position before loading more.\n */\n private int visibleThreshold = 5;\n\n /**\n * The current offset index of data you have loaded.\n */\n private int currentPageIndex = 0;\n\n /**\n * The total number of items in the dataset after the last load.\n */\n private int previousTotalItemCount = 0;\n\n /**\n * The last page index of this endless scrolling dataset.\n */\n private long lastPageIndex = -1;\n\n private boolean loading = true;\n\n public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {\n mLayoutManager = layoutManager;\n }\n\n public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) {\n mLayoutManager = layoutManager;\n visibleThreshold = visibleThreshold * layoutManager.getSpanCount();\n }\n\n public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) {\n mLayoutManager = layoutManager;\n visibleThreshold = visibleThreshold * layoutManager.getSpanCount();\n }\n\n public int getLastVisibleItem(int[] lastVisibleItemPositions) {\n int maxSize = 0;\n for (int i = 0; i < lastVisibleItemPositions.length; i++) {\n if (i == 0) {\n maxSize = lastVisibleItemPositions[i];\n } else if (lastVisibleItemPositions[i] > maxSize) {\n maxSize = lastVisibleItemPositions[i];\n }\n }\n return maxSize;\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 onScrolled(RecyclerView view, int dx, int dy) {\n int lastVisibleItemPosition = 0;\n int totalItemCount = mLayoutManager.getItemCount();\n\n if (mLayoutManager instanceof StaggeredGridLayoutManager) {\n int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);\n // get maximum element within the list\n lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);\n } else if (mLayoutManager instanceof LinearLayoutManager) {\n lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();\n } else if (mLayoutManager instanceof GridLayoutManager) {\n lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();\n }\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 currentPageIndex = 0;\n previousTotalItemCount = totalItemCount;\n if (totalItemCount == 0) {\n loading = true;\n }\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 }\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 // threshold should reflect how many total columns there are too\n if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {\n //If a lastPageIndex has been set, and is equal to currentPageIndex, then do nothing.\n if (lastPageIndex != -1 && currentPageIndex == lastPageIndex) {\n return;\n }\n\n currentPageIndex++;\n onLoadMore(currentPageIndex, totalItemCount);\n loading = true;\n }\n }\n\n /**\n * Defines the process for actually loading more data based on page\n *\n * @param pageIndex\n * @param totalItemCount\n */\n public abstract void onLoadMore(int pageIndex, int totalItemCount);\n\n /**\n * Indicates that loading for the corresponding page index has failed\n *\n * @param pageIndex The page index for which loading failed.\n * @return The current page index being internally maintained.\n */\n public int loadingFailed(int pageIndex) {\n if (pageIndex == currentPageIndex) {\n currentPageIndex--;\n loading = false;\n }\n\n return currentPageIndex;\n }\n\n /**\n * Set the last page index of this endless scrolling dataset.\n *\n * @param lastPageIndex THe last page's index.\n */\n public void setLastPageIndex(long lastPageIndex) {\n this.lastPageIndex = lastPageIndex;\n }\n\n /**\n * Use this to set the current page's index after a configuration change has occured.\n * Setting it incorrectly will result in either wrong page data being loaded,\n * or no more data being loaded at all!\n *\n * @param currentPageIndex The current page's index.\n */\n public void setCurrentPageIndexAfterConfigurationChange(int currentPageIndex) {\n this.currentPageIndex = currentPageIndex;\n }\n}" ]
import android.app.SearchManager; import android.content.Context; import android.databinding.DataBindingUtil; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.app.AlertDialog; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.transition.ChangeImageTransform; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import com.daksh.tmdbsample.R; import com.daksh.tmdbsample.base.BaseActivity; import com.daksh.tmdbsample.data.intdef.SortOrder; import com.daksh.tmdbsample.data.model.Movie; import com.daksh.tmdbsample.databinding.ActivityMovieListBinding; import com.daksh.tmdbsample.databinding.ActivityMovieListSortDialogBinding; import com.daksh.tmdbsample.databinding.MovieListItemBinding; import com.daksh.tmdbsample.di.component.AppComponent; import com.daksh.tmdbsample.di.module.MovieListModule; import com.daksh.tmdbsample.moviedetail.MovieDetailActivity; import com.daksh.tmdbsample.moviedetail.MovieDetailFragment; import com.daksh.tmdbsample.util.EndlessRecyclerViewScrollListener; import com.jakewharton.rxbinding.support.v4.view.RxMenuItemCompat; import com.jakewharton.rxbinding.support.v7.widget.RxSearchView; import com.jakewharton.rxbinding.view.MenuItemActionViewEvent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import icepick.State; import rx.android.schedulers.AndroidSchedulers;
package com.daksh.tmdbsample.movielist; public class MovieListActivity extends BaseActivity implements MovieListContract.View { /** * Defines the duration to wait (in millis) before automatically running a query */ public static final long QUERY_TYPING_RUN_WAIT_MILLIS = 1000; private static final int GRID_COLUMNS = 2; private static final String STATE_RECYCLER_VIEW = "STATE_RECYCLER_VIEW"; @Inject MovieListContract.Presenter presenter; @State
ArrayList<Movie> movies;
2
LMAX-Exchange/parallel-junit
src/main/java/com/lmax/ant/paralleljunit/util/process/ManagedProcessFactory.java
[ "public interface ParallelJUnitTaskConfig\n{\n long NO_TIMEOUT = -1;\n\n Queue<JUnitTest> getTestQueue();\n\n List<String> getCommand(Class<?> mainClass, int workerId, int serverPort);\n\n File getDirectory(int workerId);\n\n boolean isNewEnvironment();\n\n Map<String, String> getEnvironment();\n\n long getTimeout();\n\n boolean isLogFailedTests();\n\n ProjectComponent getProjectComponent();\n\n int getThreads();\n}", "public class RemoteTestRunnerProcessFactory\n{\n private final ProcessBuilderFactory processBuilderFactory;\n\n public RemoteTestRunnerProcessFactory(final ProcessBuilderFactory processBuilderFactory)\n {\n this.processBuilderFactory = processBuilderFactory;\n }\n\n public Process createForkedProcess(final int workerId, final ParallelJUnitTaskConfig config, final int serverPort)\n {\n final List<String> jvmCommand = config.getCommand(RemoteTestRunner.class, workerId, serverPort);\n\n final DelegatingProcessBuilder processBuilder = processBuilderFactory.createProcessBuilder(jvmCommand);\n\n final File workingDirectory = config.getDirectory(workerId);\n if (workingDirectory != null)\n {\n if (!workingDirectory.mkdirs() && !workingDirectory.isDirectory())\n {\n throw new BuildException(\"Failed to create worker directory: \" + workingDirectory.getPath());\n }\n processBuilder.directory(workingDirectory);\n }\n\n final Map<String, String> environment = processBuilder.environment();\n\n if (config.isNewEnvironment())\n {\n environment.clear();\n }\n\n environment.putAll(config.getEnvironment());\n\n try\n {\n return processBuilder.start();\n }\n catch (final IOException e)\n {\n throw new BuildException(\"Error starting forked process.\", e);\n }\n }\n}", "public class EOFAwareInputStream extends InputStream\n{\n private final InputStream delegate;\n private final CountDownLatch endOfStream = new CountDownLatch(1);\n\n public EOFAwareInputStream(final InputStream delegate)\n {\n this.delegate = delegate;\n }\n\n public boolean waitFor(final int timeout, final TimeUnit timeUnit) throws InterruptedException\n {\n return endOfStream.await(timeout, timeUnit);\n }\n\n @Override\n public int read() throws IOException\n {\n try\n {\n return checkEOF(delegate.read());\n }\n catch (final IOException e)\n {\n endOfStream();\n throw e;\n }\n }\n\n @Override\n public int read(final byte[] b) throws IOException\n {\n try\n {\n return checkEOF(delegate.read(b));\n }\n catch (final IOException e)\n {\n endOfStream();\n throw e;\n }\n }\n\n @Override\n public int read(final byte[] b, final int off, final int len) throws IOException\n {\n try\n {\n return checkEOF(delegate.read(b, off, len));\n }\n catch (final IOException e)\n {\n endOfStream();\n throw e;\n }\n }\n\n @Override\n public long skip(final long n) throws IOException\n {\n return delegate.skip(n);\n }\n\n @Override\n public int available() throws IOException\n {\n // This is a horrible subversion of Ant's StreamPumper.useAvailable. We effectively tell it there's always data available, so it calls read. It's quite happy if read returns 0 bytes. So this\n // doesn't break it. But in the mean time, our read method is invoked so we can see when EOF happens.\n return 1;\n }\n\n @Override\n public void close() throws IOException\n {\n delegate.close();\n }\n\n @Override\n public synchronized void mark(final int readlimit)\n {\n delegate.mark(readlimit);\n }\n\n @Override\n public synchronized void reset() throws IOException\n {\n delegate.reset();\n }\n\n @Override\n public boolean markSupported()\n {\n return delegate.markSupported();\n }\n\n private int checkEOF(final int bytes)\n {\n if (bytes < 0)\n {\n endOfStream();\n }\n return bytes;\n }\n\n private void endOfStream()\n {\n endOfStream.countDown();\n }\n}", "public class EOFAwareInputStreamFactory\n{\n public EOFAwareInputStream create(final InputStream delegate)\n {\n return new EOFAwareInputStream(delegate);\n }\n}", "public class ExecuteStreamHandlerFactory\n{\n private final PumpStreamHandlerFactory pumpStreamHandlerFactory;\n\n public ExecuteStreamHandlerFactory(final PumpStreamHandlerFactory pumpStreamHandlerFactory)\n {\n this.pumpStreamHandlerFactory = pumpStreamHandlerFactory;\n }\n\n public ExecuteStreamHandler create(final InputStream processOutputStream, final InputStream processErrorStream, final OutputStream processInputStream)\n {\n final ExecuteStreamHandler streamHandler = pumpStreamHandlerFactory.create();\n try\n {\n streamHandler.setProcessOutputStream(processOutputStream);\n streamHandler.setProcessErrorStream(processErrorStream);\n streamHandler.setProcessInputStream(processInputStream);\n streamHandler.start();\n }\n catch (IOException e)\n {\n // The ExecuteStreamHandler interface declares IOException on all the above methods, but the PumpStreamHandler implementation never throws them\n throw new BuildException(e);\n }\n return streamHandler;\n }\n}" ]
import java.util.Collection; import java.util.concurrent.ExecutorService; import com.lmax.ant.paralleljunit.ParallelJUnitTaskConfig; import com.lmax.ant.paralleljunit.remote.controller.RemoteTestRunnerProcessFactory; import com.lmax.ant.paralleljunit.util.io.EOFAwareInputStream; import com.lmax.ant.paralleljunit.util.io.EOFAwareInputStreamFactory; import com.lmax.ant.paralleljunit.util.io.ExecuteStreamHandlerFactory; import org.apache.tools.ant.taskdefs.ExecuteStreamHandler; import org.apache.tools.ant.taskdefs.ExecuteWatchdog; import static java.util.Arrays.asList;
/** * Copyright 2012-2013 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.ant.paralleljunit.util.process; public class ManagedProcessFactory { private final RemoteTestRunnerProcessFactory remoteTestRunnerProcessFactory; private final ProcessDestroyer destroyer; private final ExecuteStreamHandlerFactory executeStreamHandlerFactory; private final ExecuteWatchdogFactory watchdogFactory; private final EOFAwareInputStreamFactory eofAwareInputStreamFactory; private final ExecutorService executorService; public ManagedProcessFactory(final RemoteTestRunnerProcessFactory remoteTestRunnerProcessFactory, final ProcessDestroyer destroyer, final ExecuteStreamHandlerFactory executeStreamHandlerFactory, final ExecuteWatchdogFactory watchdogFactory, final EOFAwareInputStreamFactory eofAwareInputStreamFactory, final ExecutorService executorService) { this.remoteTestRunnerProcessFactory = remoteTestRunnerProcessFactory; this.destroyer = destroyer; this.executeStreamHandlerFactory = executeStreamHandlerFactory; this.watchdogFactory = watchdogFactory; this.eofAwareInputStreamFactory = eofAwareInputStreamFactory; this.executorService = executorService; }
public ManagedProcess create(final int workerId, final ParallelJUnitTaskConfig config, final int serverPort)
0
Ecwid/consul-api
src/main/java/com/ecwid/consul/v1/catalog/CatalogServiceRequest.java
[ "public interface ConsulRequest {\n\n\tpublic List<UrlParameters> asUrlParameters();\n\n}", "public final class SingleUrlParameters implements UrlParameters {\n\n\tprivate final String key;\n\tprivate final String value;\n\n\tpublic SingleUrlParameters(String key) {\n\t\tthis.key = key;\n\t\tthis.value = null;\n\t}\n\n\tpublic SingleUrlParameters(String key, String value) {\n\t\tthis.key = key;\n\t\tthis.value = value;\n\t}\n\n\t@Override\n\tpublic List<String> toUrlParameters() {\n\t\tif (value != null) {\n\t\t\treturn Collections.singletonList(key + \"=\" + Utils.encodeValue(value));\n\t\t} else {\n\t\t\treturn Collections.singletonList(key);\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(o instanceof SingleUrlParameters)) {\n\t\t\treturn false;\n\t\t}\n\t\tSingleUrlParameters that = (SingleUrlParameters) o;\n\t\treturn Objects.equals(key, that.key) &&\n\t\t\tObjects.equals(value, that.value);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(key, value);\n\t}\n}", "public final class TagsParameters implements UrlParameters {\n\n\tprivate final String[] tags;\n\n\tpublic TagsParameters(String[] tags) {\n\t\tthis.tags = tags;\n\t}\n\n\t@Override\n\tpublic List<String> toUrlParameters() {\n\t\tList<String> params = new ArrayList<>();\n\n\t\tif (tags != null) {\n\t\t\tfor (String tag : tags) {\n\t\t\t\tif (tag != null) {\n\t\t\t\t\tparams.add(\"tag=\" + tag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn params;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(o instanceof TagsParameters)) {\n\t\t\treturn false;\n\t\t}\n\t\tTagsParameters that = (TagsParameters) o;\n\t\treturn Arrays.equals(tags, that.tags);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Arrays.hashCode(tags);\n\t}\n}", "public interface UrlParameters {\n\n\tpublic List<String> toUrlParameters();\n\n}", "public final class NodeMetaParameters implements UrlParameters {\n\n private final Map<String, String> nodeMeta;\n\n public NodeMetaParameters(Map<String, String> nodeMeta) {\n this.nodeMeta = nodeMeta;\n }\n\n @Override\n public List<String> toUrlParameters() {\n List<String> params = new ArrayList<>();\n\n if (nodeMeta != null) {\n String key = \"node-meta\";\n\n for (Map.Entry<String, String> entry : nodeMeta.entrySet()) {\n String value = entry.getKey() + \":\" + entry.getValue();\n params.add(key + \"=\" + value);\n }\n }\n\n return params;\n }\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(o instanceof NodeMetaParameters)) {\n\t\t\treturn false;\n\t\t}\n\t\tNodeMetaParameters that = (NodeMetaParameters) o;\n\t\treturn Objects.equals(nodeMeta, that.nodeMeta);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(nodeMeta);\n\t}\n}", "public final class QueryParams implements UrlParameters {\n\tpublic static final class Builder {\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tprivate String datacenter;\n\t\tprivate ConsistencyMode consistencyMode;\n\t\tprivate long waitTime;\n\t\tprivate long index;\n\t\tprivate String near;\n\n\t\tprivate Builder() {\n\t\t\tthis.datacenter = null;\n\t\t\tthis.consistencyMode = ConsistencyMode.DEFAULT;\n\t\t\tthis.waitTime = -1;\n\t\t\tthis.index = -1;\n\t\t\tthis.near = null;\n\t\t}\n\n\t\tpublic Builder setConsistencyMode(ConsistencyMode consistencyMode) {\n\t\t\tthis.consistencyMode = consistencyMode;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setDatacenter(String datacenter) {\n\t\t\tthis.datacenter = datacenter;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setWaitTime(long waitTime) {\n\t\t\tthis.waitTime = waitTime;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setIndex(long index) {\n\t\t\tthis.index = index;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder setNear(String near) {\n\t\t\tthis.near = near;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic QueryParams build() {\n\t\t\treturn new QueryParams(datacenter, consistencyMode, waitTime, index, near);\n\t\t}\n\t}\n\n\tpublic static final QueryParams DEFAULT = new QueryParams(ConsistencyMode.DEFAULT);\n\n\tprivate final String datacenter;\n\tprivate final ConsistencyMode consistencyMode;\n\tprivate final long waitTime;\n\tprivate final long index;\n\tprivate final String near;\n\n\tprivate QueryParams(String datacenter, ConsistencyMode consistencyMode, long waitTime, long index, String near) {\n\t\tthis.datacenter = datacenter;\n\t\tthis.consistencyMode = consistencyMode;\n\t\tthis.waitTime = waitTime;\n\t\tthis.index = index;\n\t\tthis.near = near;\n\t}\n\n\tprivate QueryParams(String datacenter, ConsistencyMode consistencyMode, long waitTime, long index) {\n\t\tthis(datacenter, consistencyMode, waitTime, index, null);\n\t}\n\n\tpublic QueryParams(String datacenter) {\n\t\tthis(datacenter, ConsistencyMode.DEFAULT, -1, -1);\n\t}\n\n\tpublic QueryParams(ConsistencyMode consistencyMode) {\n\t\tthis(null, consistencyMode, -1, -1);\n\t}\n\n\tpublic QueryParams(String datacenter, ConsistencyMode consistencyMode) {\n\t\tthis(datacenter, consistencyMode, -1, -1);\n\t}\n\n\tpublic QueryParams(long waitTime, long index) {\n\t\tthis(null, ConsistencyMode.DEFAULT, waitTime, index);\n\t}\n\n public QueryParams(String datacenter, long waitTime, long index) {\n\t\tthis(datacenter, ConsistencyMode.DEFAULT, waitTime, index, null);\n }\n\n\tpublic String getDatacenter() {\n\t\treturn datacenter;\n\t}\n\n\tpublic ConsistencyMode getConsistencyMode() {\n\t\treturn consistencyMode;\n\t}\n\n\tpublic long getWaitTime() {\n\t\treturn waitTime;\n\t}\n\n\tpublic long getIndex() {\n\t\treturn index;\n\t}\n\n\tpublic String getNear() {\n\t\treturn near;\n\t}\n\n\t@Override\n\tpublic List<String> toUrlParameters() {\n\t\tList<String> params = new ArrayList<String>();\n\n\t\t// add basic params\n\t\tif (datacenter != null) {\n\t\t\tparams.add(\"dc=\" + Utils.encodeValue(datacenter));\n\t\t}\n\n\t\tif (consistencyMode != ConsistencyMode.DEFAULT) {\n\t\t\tparams.add(consistencyMode.name().toLowerCase());\n\t\t}\n\n\t\tif (waitTime != -1) {\n\t\t\tparams.add(\"wait=\" + Utils.toSecondsString(waitTime));\n\t\t}\n\n\t\tif (index != -1) {\n\t\t\tparams.add(\"index=\" + Long.toUnsignedString(index));\n\t\t}\n\n\t\tif (near != null) {\n\t\t\tparams.add(\"near=\" + Utils.encodeValue(near));\n\t\t}\n\n\t\treturn params;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(o instanceof QueryParams)) {\n\t\t\treturn false;\n\t\t}\n\t\tQueryParams that = (QueryParams) o;\n\t\treturn waitTime == that.waitTime &&\n\t\t\tindex == that.index &&\n\t\t\tObjects.equals(datacenter, that.datacenter) &&\n\t\t\tconsistencyMode == that.consistencyMode &&\n\t\t\tObjects.equals(near, that.near);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(datacenter, consistencyMode, waitTime, index, near);\n\t}\n}" ]
import com.ecwid.consul.ConsulRequest; import com.ecwid.consul.SingleUrlParameters; import com.ecwid.consul.v1.TagsParameters; import com.ecwid.consul.UrlParameters; import com.ecwid.consul.v1.NodeMetaParameters; import com.ecwid.consul.v1.QueryParams; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects;
package com.ecwid.consul.v1.catalog; public final class CatalogServiceRequest implements ConsulRequest { private final String datacenter; private final String[] tags; private final String near; private final Map<String, String> nodeMeta; private final QueryParams queryParams; private final String token; private CatalogServiceRequest(String datacenter, String[] tags, String near, Map<String, String> nodeMeta, QueryParams queryParams, String token) { this.datacenter = datacenter; this.tags = tags; this.near = near; this.nodeMeta = nodeMeta; this.queryParams = queryParams; this.token = token; } public String getDatacenter() { return datacenter; } public String getTag() { return tags != null && tags.length > 0 ? tags[0] : null; } public String[] getTags() { return tags; } public String getNear() { return near; } public Map<String, String> getNodeMeta() { return nodeMeta; } public QueryParams getQueryParams() { return queryParams; } public String getToken() { return token; } public static class Builder { private String datacenter; private String[] tags; private String near; private Map<String, String> nodeMeta; private QueryParams queryParams; private String token; private Builder() { } public Builder setDatacenter(String datacenter) { this.datacenter = datacenter; return this; } public Builder setTag(String tag) { this.tags = new String[]{tag}; return this; } public Builder setTags(String[] tags) { this.tags = tags; return this; } public Builder setNear(String near) { this.near = near; return this; } public Builder setNodeMeta(Map<String, String> nodeMeta) { if (nodeMeta == null) { this.nodeMeta = null; } else { this.nodeMeta = Collections.unmodifiableMap(nodeMeta); } return this; } public Builder setQueryParams(QueryParams queryParams) { this.queryParams = queryParams; return this; } public Builder setToken(String token) { this.token = token; return this; } public CatalogServiceRequest build() { return new CatalogServiceRequest(datacenter, tags, near, nodeMeta, queryParams, token); } } public static Builder newBuilder() { return new Builder(); } @Override public List<UrlParameters> asUrlParameters() { List<UrlParameters> params = new ArrayList<>(); if (datacenter != null) {
params.add(new SingleUrlParameters("dc", datacenter));
1
privly/privly-android
app/src/main/java/ly/priv/mobile/GmailLinkGrabberService.java
[ "public class PrivlyApplication {\n\n public static String MESSAGE_APP = \"Message\";\n public static String PLAINPOST_APP = \"PlainPost\";\n public static String HISTORY_APP = \"History\";\n String name, path;\n IconDrawable drawable;\n\n public PrivlyApplication(String name, String path, IconDrawable drawable) {\n this.name = name;\n this.path = path;\n this.drawable = drawable;\n }\n\n public String getName() {\n return name;\n }\n\n public String getPath() {\n return path;\n }\n\n public IconDrawable getDrawable() {\n return drawable;\n }\n}", "public class PrivlyApplicationFragment extends Fragment {\n\n private String LOGTAG = getClass().getSimpleName();\n\n public PrivlyApplicationFragment() {\n\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View rootView = inflater.inflate(R.layout.fragment_privly_application, container, false);\n getActivity().setTitle(getArguments().getString(ConstantValues.PRIVLY_APPLICATION_KEY));\n WebView webview = (WebView) rootView.findViewById(R.id.webview);\n webview.getSettings().setJavaScriptEnabled(true);\n webview.getSettings().setDomStorageEnabled(true);\n webview.addJavascriptInterface(new JsObject(getActivity()),\n ConstantValues.JAVASCRIPT_BRIDGE_NAME);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)\n webview.getSettings().setAllowUniversalAccessFromFileURLs(true);\n\n // Logs all Js Console messages on the logcat.\n webview.setWebChromeClient(new WebChromeClient() {\n @Override\n public boolean onConsoleMessage(ConsoleMessage cm) {\n Log.d(LOGTAG,\n cm.message() + \" -- From line \" + cm.lineNumber()\n + \" of \" + cm.sourceId());\n return true;\n }\n });\n\n webview.loadUrl(Utilities.getFilePathURLFromAppName(getArguments().getString(ConstantValues.PRIVLY_APPLICATION_KEY)));\n webview.loadUrl(\"javascript: window.onload = function() {document.getElementsByClassName('navbar-toggle')[0].style.visibility = 'hidden';\"\n + \"document.getElementsByClassName('collapse navbar-collapse')[0].style.visibility = 'hidden';}\");\n return rootView;\n }\n}", "public class ConstantValues {\r\n\r\n final public static String DEFAULT_CONTENT_SERVER = \"https://privlyalpha.org\";\r\n final public static String TOKEN_AUTHENTICATION_ENDPOINT = \"/token_authentications.json\";\r\n final public static String POST_PARAM_NAME_EMAIL = \"email\";\r\n final public static String POST_PARAM_NAME_PWD = \"password\";\r\n final public static String AUTH_ERROR_KEY = \"error\";\r\n final public static String JAVASCRIPT_BRIDGE_NAME = \"androidJsBridge\";\r\n final public static String PRIVLY_APPLICATION_KEY = \"Privly_Application_Key\";\r\n final public static String PRIVLY_URL_KEY = \"Privly_Url_Key\";\r\n\r\n\r\n \r\n // Constant for Privly Preferences\r\n public static String APP_PREFERENCES = \"prefsFile\";\r\n public static String APP_PREFERENCES_BASE_URL = \"base_url\";\r\n public static String APP_PREFERENCES_AUTH_TOKEN = \"auth_token\";\r\n public static String APP_PREFERENCES_UNAME = \"uname\";\r\n public static String APP_PREFERENCES_VERIFIED_AT_LOGIN = \"verified_at_login\";\r\n public static String APP_PREFERENCE_LAST_LOGIN = \"lastlogin\";\r\n public static String APP_PREFERENCE_GMAIL_ID = \"gmailId\";\r\n\r\n // Swipe options\r\n public static String SWIPE_MIN_DISTANCE = \"swipeMinDistance\";\r\n public static String SWIPE_THRESHOLD_VELOCITY = \"swipeThresholdVelocity\";\r\n public static String SWIPE_MAX_OFF_PATH = \"swipeMaxOffPath\";\r\n\r\n // Constant for FaceBook\r\n public static String PREFERENCE_FACEBOOK_USER_ID = \"FacebookID\";\r\n // Constant for Twitter\r\n public static String TWITTER_CALLBACK_URL = \"oauth://privlyT4JCallback\";\r\n public static String URL_PARAMETER_TWITTER_OAUTH_VERIFIER = \"oauth_verifier\";\r\n public static String PREFERENCE_TWITTER_OAUTH_TOKEN = \"TWITTER_OAUTH_TOKEN\";\r\n public static String PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET = \"TWITTER_OAUTH_TOKEN_SECRET\";\r\n public static String PREFERENCE_TWITTER_IS_LOGGED_IN = \"TWITTER_IS_LOGGED_IN\";\r\n}\r", "public class Utilities {\n /**\n * Check validity of an EMail address using RegEx\n *\n * @param {String} emailToCheck\n * @return {Boolean}\n */\n public static boolean isValidEmail(String emailToCheck) {\n String emailPattern = \"^[_A-Za-z0-9-\\\\+]+(\\\\.[_A-Za-z0-9-]+)*@\"\n + \"[A-Za-z0-9-]+(\\\\.[A-Za-z0-9]+)*(\\\\.[A-Za-z]{2,})$\";\n if (emailToCheck.matches(emailPattern))\n return true;\n else\n return false;\n }\n\n /**\n * Returns a Set of email addresses combining the last login email address, if any,\n * with the existing account email addresses on the device .\n *\n * @param {Context} context Context of the calling class.\n * @return {Set<String>} emailSet\n */\n public static Set<String> emailIdSuggestor(Context context) {\n Account[] accounts = AccountManager.get(context).getAccounts();\n Set<String> emailSet = new HashSet<String>();\n String username = Values.getInstance().getLastLoginEmailAddress();\n if (username != null) {\n if (Utilities.isValidEmail(username)) {\n emailSet.add(username);\n }\n }\n for (Account account : accounts) {\n if (Utilities.isValidEmail(account.name)) {\n emailSet.add(account.name);\n }\n }\n return emailSet;\n }\n\n /**\n * Show Toast on screen.\n *\n * @param {Context} context Context of the calling class.\n * @param {String} textToToast\n * @param {String} longToast\n */\n public static Boolean showToast(Context context, String textToToast,\n Boolean longToast) {\n if (longToast) {\n Toast.makeText(context, textToToast, Toast.LENGTH_LONG).show();\n return true;\n } else {\n Toast.makeText(context, textToToast, Toast.LENGTH_SHORT).show();\n return true;\n }\n }\n\n /**\n * Show dialog on screen.\n *\n * @param activity\n * @param mess\n * @return\n */\n public static AlertDialog showDialog(final Activity activity, String mess) {\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n builder.setTitle(R.string.dialog_info_title);\n builder.setCancelable(true);\n builder.setMessage(mess);\n builder.setPositiveButton(android.R.string.ok,\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n }\n });\n return builder.create();\n }\n\n /**\n * Returns HTML string which will be loaded in the webview in Share\n * Activity.\n *\n * @param {String} url\n * @return {String} html Returns the HTML String which is used to display\n * Privly link in the WebView\n */\n public static String getShareableHTML(String url) {\n String html = \"<a href=\\\"\" + url + \"\\\">\" + url + \"</a>\";\n return html;\n }\n\n /**\n * Checks for data connection availability\n *\n * @param {Context} context\n * @return {Boolean}\n */\n public static Boolean isDataConnectionAvailable(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = connectivityManager\n .getActiveNetworkInfo();\n return activeNetworkInfo != null && activeNetworkInfo.isConnected();\n }\n\n /**\n * Appends the current auth_token to any url.\n *\n * @param {String} url The Url to be displayed in the WebWiev\n * @param {Context} context Calling Context\n * @return {Boolean}\n */\n public static String getGetRequestUrl(String url, Context context) {\n String authTokenString = \"auth_token=\" + Values.getInstance().getAuthToken();\n if (url.indexOf(\"?\") >= 0\n && (url.indexOf(\"?\") < url.indexOf(\"#\") || url.indexOf(\"#\") == -1)) {\n return url.replace(\"?\", \"?\" + authTokenString + \"&\");\n // else if there is an anchor\n } else if (url.indexOf(\"#\") >= 0) {\n return url.replace(\"#\", \"?\" + authTokenString + \"#\");\n } else {\n return url + \"?\" + authTokenString;\n }\n }\n\n /**\n * This method uses regex to find out any Privly URLs in a given String\n *\n * @param {String} message\n * @return {ArrayList<String>} listOfUrls List of Privly Urls contained in a\n * string.\n */\n public static ArrayList<String> fetchPrivlyUrls(String message) {\n ArrayList<String> listOfUrls = new ArrayList<String>();\n String regEx = \"(https?://)?[^ ]*privlyInject1[^ ]*\";\n Pattern pattern = Pattern.compile(regEx);\n\n if (message != null) {\n Matcher matcher = pattern.matcher(message);\n while (matcher.find()) {\n listOfUrls.add(matcher.group());\n }\n }\n return listOfUrls;\n }\n\n public static void setHederFont(Activity activity) {\n TextView hederText = (TextView) activity.findViewById(R.id.twHederText);\n Typeface lobster = Typeface.createFromAsset(activity.getAssets(),\n \"fonts/Lobster.ttf\");\n hederText.setTypeface(lobster);\n }\n\n /**\n * Conversion Facebook time into local time\n *\n * @param time\n * @return\n * @author Ivan Metla\n */\n public static String getTimeForFacebook(String time) {\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\n \"yyyy-MM-dd'T'HH:mm:ssZ\");\n Date date = null;\n try {\n date = simpleDateFormat.parse(time);\n } catch (ParseException e) {\n e.printStackTrace();\n }\n Calendar fDate = Calendar.getInstance();\n fDate.setTime(date);\n Calendar curDate = Calendar.getInstance();\n if (fDate.get(Calendar.YEAR) == curDate.get(Calendar.YEAR)) {\n if (curDate.get(Calendar.DAY_OF_YEAR) == fDate\n .get(Calendar.DAY_OF_YEAR)) {\n simpleDateFormat = new SimpleDateFormat(\"HH:mm\");\n } else if (curDate.get(Calendar.WEEK_OF_YEAR) == fDate\n .get(Calendar.WEEK_OF_YEAR)) {\n simpleDateFormat = new SimpleDateFormat(\"E, HH:mm\");\n } else\n simpleDateFormat = new SimpleDateFormat(\"MMM dd, HH:mm\");\n } else {\n simpleDateFormat = new SimpleDateFormat(\"MM/dd/yyyy, HH:mm\");\n }\n return simpleDateFormat.format(fDate.getTime());\n }\n\n /**\n * Conversion Twitter time into local time\n *\n * @return\n * @paramtime\n * @author Ivan Metla\n */\n public static String getTimeForTwitter(Date date) {\n SimpleDateFormat simpleDateFormat;\n\n Calendar tDate = Calendar.getInstance();\n tDate.setTime(date);\n Calendar curDate = Calendar.getInstance();\n if (tDate.get(Calendar.YEAR) == curDate.get(Calendar.YEAR)) {\n if (curDate.get(Calendar.DAY_OF_YEAR) == tDate\n .get(Calendar.DAY_OF_YEAR)) {\n simpleDateFormat = new SimpleDateFormat(\"HH:mm\");\n } else if (curDate.get(Calendar.WEEK_OF_YEAR) == tDate\n .get(Calendar.WEEK_OF_YEAR)) {\n simpleDateFormat = new SimpleDateFormat(\"E, HH:mm\");\n } else\n simpleDateFormat = new SimpleDateFormat(\"MMM dd, HH:mm\");\n } else {\n simpleDateFormat = new SimpleDateFormat(\"MM/dd/yyyy, HH:mm\");\n }\n return simpleDateFormat.format(tDate.getTime());\n }\n\n public static String getTimeForGmail(String time) {\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\n \"EEE, d MMM yyyy HH:mm:ss Z\", Locale.US);\n Date date = null;\n try {\n date = simpleDateFormat.parse(time);\n\n Calendar fDate = Calendar.getInstance();\n fDate.setTime(date);\n Calendar curDate = Calendar.getInstance();\n if (fDate.get(Calendar.YEAR) == curDate.get(Calendar.YEAR)) {\n if (curDate.get(Calendar.DAY_OF_YEAR) == fDate\n .get(Calendar.DAY_OF_YEAR)) {\n simpleDateFormat = new SimpleDateFormat(\"HH:mm\");\n } else if (curDate.get(Calendar.WEEK_OF_YEAR) == fDate\n .get(Calendar.WEEK_OF_YEAR)) {\n simpleDateFormat = new SimpleDateFormat(\"E, HH:mm\");\n } else\n simpleDateFormat = new SimpleDateFormat(\"MMM dd, HH:mm\");\n } else {\n simpleDateFormat = new SimpleDateFormat(\"MM/dd/yyyy, HH:mm\");\n }\n return simpleDateFormat.format(fDate.getTime());\n } catch (ParseException e) {\n e.printStackTrace();\n\n return \"1800 BC\";\n }\n\n }\n\n /**\n * Check for Null or Whitespace\n *\n * @param string\n * @return\n */\n public static boolean isNullOrWhitespace(String string) {\n return string == null || string.isEmpty() || string.trim().isEmpty();\n }\n\n public static String getFilePathURLFromAppName(String appName) {\n return \"file:///android_asset/PrivlyApplications/\" + appName\n + \"/new.html\";\n }\n}", "public final class Values {\n private static SharedPreferences mSharedPrefs;\n private static Context mContext;\n private static Values values;\n\n /* We do not want classes to create an object of this class, so make this contructor private */\n private Values() {\n\n }\n\n public static void init(Context context) {\n if (values == null) {\n Log.d(\"Values\", \"Initing Values\");\n values = new Values();\n mContext = context;\n mSharedPrefs = context.getSharedPreferences(ConstantValues.APP_PREFERENCES, Context.MODE_PRIVATE);\n } else {\n Log.d(\"Values\", \"Already Inited\");\n }\n }\n\n public static Values getInstance() {\n return values;\n }\n\n /**\n * The content server URL\n *\n * @return {String} baseUrl\n */\n public String getContentServer() {\n String contentServer = mSharedPrefs.getString(\n ConstantValues.APP_PREFERENCES_BASE_URL, null);\n if (contentServer == null) {\n contentServer = ConstantValues.DEFAULT_CONTENT_SERVER;\n }\n return contentServer;\n }\n\n /**\n * Returns Authentication token for user's session\n *\n * @return {String} authToken\n */\n public String getAuthToken() {\n String authToken = mSharedPrefs.getString(\n ConstantValues.APP_PREFERENCES_AUTH_TOKEN, null);\n return authToken;\n }\n\n /**\n * Returns username of the currently logged in user.\n *\n * @return userName\n */\n public String getUserName() {\n String userName = mSharedPrefs.getString(\n ConstantValues.APP_PREFERENCES_UNAME, null);\n return userName;\n }\n\n public void setUserName(String userName) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.APP_PREFERENCES_UNAME, userName);\n editor.commit();\n }\n\n /**\n * Returns username of the last logged in user.\n *\n * @return userName\n */\n public String getLastLoginEmailAddress() {\n String userName = mSharedPrefs.getString(\n ConstantValues.APP_PREFERENCE_LAST_LOGIN, null);\n return userName;\n\n }\n\n public void setLastLoginEmailAddress(String lastloginusername) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.APP_PREFERENCE_LAST_LOGIN, lastloginusername);\n editor.commit();\n\n }\n\n /**\n * Save authentication token to SharedPrefs\n *\n * @param authToken\n */\n public void setAuthToken(String authToken) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.APP_PREFERENCES_AUTH_TOKEN, authToken);\n editor.commit();\n }\n\n /**\n * Save content server to SharedPrefs\n *\n * @param url\n */\n public void setContentServer(String url) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.APP_PREFERENCES_BASE_URL, url);\n editor.commit();\n }\n\n /**\n * Returns value of verified_at_login flag. Use this to prevent re\n * authentication at Home Screen.\n *\n * @return {Boolean}\n */\n public Boolean isUserVerifiedAtLogin() {\n return mSharedPrefs.getBoolean(\n ConstantValues.APP_PREFERENCES_VERIFIED_AT_LOGIN, false);\n }\n\n /**\n * Sets the value of verified_at_login Flag.\n *\n * @param {Boolean} bool\n */\n public void setUserVerifiedAtLogin(Boolean bool) {\n Editor editor = mSharedPrefs.edit();\n editor.putBoolean(ConstantValues.APP_PREFERENCES_VERIFIED_AT_LOGIN,\n bool);\n editor.commit();\n }\n\n /**\n * Get optimal parameter values to determine a swipe on a View.\n *\n * @return HashMap<String, Integer>\n */\n public HashMap<String, Integer> getValuesForSwipe() {\n HashMap<String, Integer> swipeValues = new HashMap<String, Integer>();\n ViewConfiguration vc = ViewConfiguration.get(mContext);\n swipeValues.put(ConstantValues.SWIPE_MIN_DISTANCE,\n vc.getScaledPagingTouchSlop());\n swipeValues.put(ConstantValues.SWIPE_THRESHOLD_VELOCITY,\n vc.getScaledMinimumFlingVelocity());\n swipeValues.put(ConstantValues.SWIPE_MAX_OFF_PATH,\n vc.getScaledMinimumFlingVelocity());\n return swipeValues;\n }\n\n // / -------- FaceBook------------------------\n\n /**\n * Set FaceBook user ID\n *\n * @param id - Facebook user id\n * @author Ivan Metla\n */\n public void setFacebookID(String id) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.PREFERENCE_FACEBOOK_USER_ID, id);\n editor.commit();\n }\n\n /**\n * Get Facebook User ID\n *\n * @return Facebook user ID\n * @author Ivan Metla\n */\n public String getFacebookID() {\n return mSharedPrefs.getString(\n ConstantValues.PREFERENCE_FACEBOOK_USER_ID, \"\");\n }\n\n // / -------- Twitter------------------------\n\n /**\n *\n */\n\n public String getTwitterConsumerKey() {\n return mContext.getResources().getString(R.string.twitter_consumer_key);\n }\n\n /**\n *\n */\n\n public String getTwitterConsumerSecret() {\n return mContext.getResources().getString(R.string.twitter_consumer_secret);\n }\n\n /**\n * Set Twitter Logged in\n *\n * @param loggedIn\n */\n public void setTwitterLoggedIn(boolean loggedIn) {\n Editor editor = mSharedPrefs.edit();\n editor.putBoolean(ConstantValues.PREFERENCE_TWITTER_IS_LOGGED_IN,\n loggedIn);\n editor.commit();\n }\n\n /**\n * Get Twitter Logged in\n *\n * @return Twitter Logged in\n */\n public boolean getTwitterLoggedIn() {\n return mSharedPrefs.getBoolean(\n ConstantValues.PREFERENCE_TWITTER_IS_LOGGED_IN, false);\n }\n\n /**\n * Set Twitter Oauth Token\n *\n * @param token\n */\n public void setTwitterOauthToken(String token) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN, token);\n editor.commit();\n }\n\n /**\n * Get Twitter Oauth Token\n *\n * @return\n */\n public String getTwitterOauthToken() {\n return mSharedPrefs.getString(\n ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN, \"\");\n }\n\n /**\n * Set Twitter Oauth Token Secret\n *\n * @param tokenSecret\n */\n public void setTwitterOauthTokenSecret(String tokenSecret) {\n Editor editor = mSharedPrefs.edit();\n editor.putString(ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET,\n tokenSecret);\n editor.commit();\n }\n\n /**\n * Get Twitter Oauth Token Secret\n *\n * @return\n */\n public String getTwitterOauthTokenSecret() {\n return mSharedPrefs.getString(\n ConstantValues.PREFERENCE_TWITTER_OAUTH_TOKEN_SECRET, \"\");\n }\n\n public String getGmailId() {\n return mSharedPrefs.getString(ConstantValues.APP_PREFERENCE_GMAIL_ID, null);\n }\n\n public void setGmailId(String gmailId) {\n mSharedPrefs.edit().putString(ConstantValues.APP_PREFERENCE_GMAIL_ID, gmailId).commit();\n }\n\n public void clearGmailId() {\n mSharedPrefs.edit().remove(ConstantValues.APP_PREFERENCE_GMAIL_ID).commit();\n }\n}" ]
import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.ProgressBar; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.AccountPicker; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.ListThreadsResponse; import com.google.api.services.gmail.model.MessagePartHeader; import com.google.api.services.gmail.model.Thread; import java.io.IOException; import java.util.ArrayList; import java.util.List; import ly.priv.mobile.gui.drawer.PrivlyApplication; import ly.priv.mobile.gui.fragments.PrivlyApplicationFragment; import ly.priv.mobile.utils.ConstantValues; import ly.priv.mobile.utils.Utilities; import ly.priv.mobile.utils.Values;
package ly.priv.mobile; /** * Authenticates user with Gmail and grabs Privly links from message inbox. * <p> * <ul> * <li>Shows Account Picker</li> * <li>Asks user for permission to access mails first time</li> * <li>Gets the access token using Play Services SDK</li> * <li>Uses access token to login to IMAP to fetch emails</li> * </ul> * </p> * * @author Gitanshu Sardana */ public class GmailLinkGrabberService extends Fragment { private static final String GMAIL_SCOPE = "oauth2:https://www.googleapis.com/auth/gmail.readonly"; private static final String APP_NAME = "Privly Gmail"; String accountName; Gmail mailService; ListView threadListView; ArrayList<EmailThreadObject> mailThreads; ProgressBar progressBar; ListMailThreadsAdapter threadAdapter; Values mValues; public GmailLinkGrabberService() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.activity_list, container, false); getActivity().setTitle("Gmail"); threadListView = (ListView) view.findViewById(R.id.lView); progressBar = (ProgressBar) view.findViewById(R.id.pbLoadingData); mValues = Values.getInstance(); threadListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { EmailThreadObject thread = mailThreads.get(arg2); Fragment mailThread = new GmailSingleThreadFragment(); Bundle args = new Bundle(); args.putParcelable("currentThread", thread); mailThread.setArguments(args); FragmentTransaction transaction = getActivity() .getSupportFragmentManager().beginTransaction(); transaction.add(R.id.container, mailThread); transaction.addToBackStack(null); transaction.commit(); } }); // Shows Account Picker with google accounts if not stored in shared // preferences Boolean accountFound = false; if (mValues.getGmailId() != null) { Account[] accounts = AccountManager.get(getActivity()) .getAccounts(); accountName = mValues.getGmailId(); Log.d("accountName", accountName); for (Account a : accounts) { if (a.type.equals(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE) && a.name.equals(accountName)) { accountFound = true; progressBar.setVisibility(View.VISIBLE); new getAuthToken().execute(); break; } } } if (!accountFound) { Intent googlePicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, true, null, null, null, null); startActivityForResult(googlePicker, 1); } return view; } // Gets selected email account and runs getAuthToken AsyncTask for selected // account @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == Activity.RESULT_OK) { progressBar.setVisibility(View.VISIBLE); accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); mValues.setGmailId(accountName); new getAuthToken().execute(); } else {
PrivlyApplicationFragment messageFragment = new PrivlyApplicationFragment();
1