hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e1580b7649b156dab6f1405c77a089271e87e6f
3,221
java
Java
src/main/java/work/toolset/code/jvm/web/minapp/type/adapter/RecordTypeAdapterFactory.java
app-util/minapp-api
6042e98bc955be2d6ea16153d9fd9e6da57c8a2e
[ "MIT" ]
null
null
null
src/main/java/work/toolset/code/jvm/web/minapp/type/adapter/RecordTypeAdapterFactory.java
app-util/minapp-api
6042e98bc955be2d6ea16153d9fd9e6da57c8a2e
[ "MIT" ]
null
null
null
src/main/java/work/toolset/code/jvm/web/minapp/type/adapter/RecordTypeAdapterFactory.java
app-util/minapp-api
6042e98bc955be2d6ea16153d9fd9e6da57c8a2e
[ "MIT" ]
null
null
null
28.758929
95
0.545172
9,138
package work.toolset.code.jvm.web.minapp.type.adapter; import com.google.gson.*; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import work.toolset.code.jvm.web.minapp.database.Record; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class RecordTypeAdapterFactory implements TypeAdapterFactory { private Map<Class, Info> cache = new HashMap<>(); @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class clz = type.getRawType(); Info info = cache.get(clz); if (info != null) { return new InstanceTypeAdapter(info.constructor, info.setter, info.getter); } if (Record.class.isAssignableFrom(clz)) { try { Constructor constructor = clz.getDeclaredConstructor(); Method setter = clz.getMethod("_setJson", JsonObject.class); Method getter = clz.getMethod("_getJson"); if (constructor != null && setter != null && getter != null) { info = new Info(constructor, setter, getter); cache.put(clz, info); return new InstanceTypeAdapter(info.constructor, info.setter, info.getter); } } catch (Exception e) { } } return null; } private static class InstanceTypeAdapter extends TypeAdapter { private Constructor constructor; private Method setter; private Method getter; InstanceTypeAdapter(Constructor constructor, Method setter, Method getter) { this.constructor = constructor; this.setter = setter; this.getter = getter; } @Override public void write(JsonWriter out, Object value) throws IOException { try { JsonObject json = (JsonObject) getter.invoke(value); Streams.write(json, out); } catch (Exception e) { throw new IOException(e); } } @Override public Object read(JsonReader in) throws IOException { try { JsonObject json = Streams.parse(in).getAsJsonObject(); Object object = constructor.newInstance(); setter.invoke(object, json); return object; } catch (Exception e) { throw new IOException(e); } } } private static class Info { Constructor constructor; Method setter; Method getter; Info(Constructor constructor, Method setter, Method getter) { this.constructor = constructor; this.setter = setter; this.getter = getter; } } }
3e1580eb9cc5115401dc642f7120009e697b0880
3,863
java
Java
hodor-common/src/test/java/com/dromara/hodor/common/CircleQueueTest.java
tincopper/hodor
2c4c351cd8ed7ad2352941c77186374f1789eb62
[ "Apache-2.0" ]
55
2020-12-08T16:59:36.000Z
2022-01-11T14:43:11.000Z
hodor-common/src/test/java/com/dromara/hodor/common/CircleQueueTest.java
jcmob-afj/hodor
c5c02c411232b70a2d7ca45ae8b449baa7769c5f
[ "Apache-2.0" ]
6
2021-02-01T02:51:02.000Z
2022-01-21T23:50:57.000Z
hodor-common/src/test/java/com/dromara/hodor/common/CircleQueueTest.java
jcmob-afj/hodor
c5c02c411232b70a2d7ca45ae8b449baa7769c5f
[ "Apache-2.0" ]
35
2021-01-26T13:18:21.000Z
2022-03-12T16:31:00.000Z
30.904
91
0.631116
9,139
package com.dromara.hodor.common; import org.dromara.hodor.common.queue.AbortEnqueuePolicy; import org.dromara.hodor.common.queue.CircleQueue; import org.dromara.hodor.common.queue.DiscardOldestElementPolicy; import org.dromara.hodor.common.queue.ResizeQueuePolicy; import org.junit.Assert; import org.junit.Test; /** * @author tomgs * @since 2021/1/21 */ public class CircleQueueTest { @Test public void testBase() { CircleQueue<String> queue = new CircleQueue<>(4, new AbortEnqueuePolicy<>()); if (queue.isEmpty()) { System.out.println("队列为空"); } System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); System.out.println("添加元素..."); queue.offer("a"); if (!queue.isEmpty()) { System.out.println("队列不为空"); } System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); queue.offer("b"); queue.offer("c"); queue.offer("d"); System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); System.out.println(queue.toString()); if (queue.isFull()) { System.out.println("队列已满"); System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); String poll = queue.poll(); System.out.println("出队元素:" + poll); } queue.offer("e"); System.out.println(queue.toString()); System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); // 设置入队拒绝策略 queue.setRejectedEnqueueHandler(new DiscardOldestElementPolicy<>()); queue.offer("f"); System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); System.out.println(queue.toString()); // 设置入队拒绝策略 queue.setRejectedEnqueueHandler(new ResizeQueuePolicy<>()); queue.offer("g"); queue.offer("h"); queue.offer("j"); queue.offer("j"); queue.offer("j"); System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); System.out.println(queue.toString()); while (!queue.isEmpty()) { System.out.println(queue.poll()); } queue.offer("k"); System.out.println("队列大小:" + queue.size() + ", 容量:" + queue.getCapacity()); System.out.println(queue.toString()); } @Test public void testShrinksCapacity() { CircleQueue<String> queue = new CircleQueue<>(16, new AbortEnqueuePolicy<>()); queue.offer("a"); queue.offer("b"); queue.offer("c"); queue.offer("d"); queue.offer("e"); System.out.println(queue.poll()); System.out.println(queue); Assert.assertEquals(queue.getCapacity(), 10); } @Test public void testPerformance() { long maxMemory = Runtime.getRuntime().maxMemory(); long freeMemory = Runtime.getRuntime().freeMemory(); System.out.println("maxMemory(MB):" + maxMemory / (1024 * 1024)); System.out.println("freeMemory(MB):" + freeMemory / (1024 * 1024)); // jvm args: -Xmx1G -Xms1G // offer 1954ms, poll 51ms // CircleQueue<String> queue = new CircleQueue<>(10000000, new AbortEnqueuePolicy<>()); // offer 1977ms, poll 62ms CircleQueue<String> queue = new CircleQueue<>(16, new ResizeQueuePolicy<>()); long startTime = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { queue.offer("" + i); } long endOfferTime = System.currentTimeMillis(); System.out.println("入队时间(ms):" + (endOfferTime - startTime)); maxMemory = Runtime.getRuntime().maxMemory(); freeMemory = Runtime.getRuntime().freeMemory(); System.out.println("maxMemory(MB):" + maxMemory / (1024 * 1024)); System.out.println("freeMemory(MB):" + freeMemory / (1024 * 1024)); startTime = System.currentTimeMillis(); // 51ms for (int i = 0; i < 10000000; i++) { queue.poll(); } long endPollTime = System.currentTimeMillis(); System.out.println("出队时间(ms):" + (endPollTime - startTime)); } }
3e15816a247a3259219b79c8fb6f33a543356f78
23,081
java
Java
src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java
eikemeier/bazel
8dcf27e590ce77241a15fd2f2f8b9889a3d7731b
[ "Apache-2.0" ]
16,989
2015-09-01T19:57:15.000Z
2022-03-31T23:54:00.000Z
src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java
eikemeier/bazel
8dcf27e590ce77241a15fd2f2f8b9889a3d7731b
[ "Apache-2.0" ]
12,562
2015-09-01T09:06:01.000Z
2022-03-31T22:26:20.000Z
src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java
eikemeier/bazel
8dcf27e590ce77241a15fd2f2f8b9889a3d7731b
[ "Apache-2.0" ]
3,707
2015-09-02T19:20:01.000Z
2022-03-31T17:06:14.000Z
45.70495
100
0.712794
9,140
// Copyright 2014 The Bazel 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.devtools.build.lib.runtime; import static com.google.common.base.Strings.isNullOrEmpty; import com.google.devtools.build.lib.profiler.MemoryProfiler.MemoryProfileStableHeapParameters; import com.google.devtools.build.lib.profiler.ProfilerTask; import com.google.devtools.build.lib.runtime.CommandLineEvent.ToolCommandLineEvent; import com.google.devtools.build.lib.util.OptionsUtils; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.common.options.Converter; import com.google.devtools.common.options.Converters; import com.google.devtools.common.options.Converters.AssignmentConverter; import com.google.devtools.common.options.EnumConverter; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionDocumentationCategory; import com.google.devtools.common.options.OptionEffectTag; import com.google.devtools.common.options.OptionMetadataTag; import com.google.devtools.common.options.OptionsBase; import com.google.devtools.common.options.OptionsParsingException; import com.google.devtools.common.options.TriState; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Level; /** Options common to all commands. */ public class CommonCommandOptions extends OptionsBase { /** * To create a new incompatible change, see the javadoc for {@link * AllIncompatibleChangesExpansion}. */ @Option( name = "all_incompatible_changes", defaultValue = "null", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.NO_OP}, metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE}, help = "No-op, being removed. See https://github.com/bazelbuild/bazel/issues/13892") public Void allIncompatibleChanges; @Option( name = "enable_platform_specific_config", defaultValue = "false", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.UNKNOWN}, help = "If true, Bazel picks up host-OS-specific config lines from bazelrc files. For example, " + "if the host OS is Linux and you run bazel build, Bazel picks up lines starting " + "with build:linux. Supported OS identifiers are linux, macos, windows, freebsd, " + "and openbsd. Enabling this flag is equivalent to using --config=linux on Linux, " + "--config=windows on Windows, etc.") public boolean enablePlatformSpecificConfig; @Option( name = "config", defaultValue = "null", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.UNKNOWN}, allowMultiple = true, help = "Selects additional config sections from the rc files; for every <command>, it " + "also pulls in the options from <command>:<config> if such a section exists; " + "if this section doesn't exist in any .rc file, Blaze fails with an error. " + "The config sections and flag combinations they are equivalent to are " + "located in the tools/*.blazerc config files.") public List<String> configs; @Option( name = "logging", defaultValue = "3", // Level.INFO documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS}, converter = Converters.LogLevelConverter.class, help = "The logging level.") public Level verbosity; @Option( name = "client_cwd", defaultValue = "", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, metadataTags = {OptionMetadataTag.HIDDEN}, effectTags = {OptionEffectTag.CHANGES_INPUTS}, converter = OptionsUtils.PathFragmentConverter.class, help = "A system-generated parameter which specifies the client's working directory") public PathFragment clientCwd; @Option( name = "announce_rc", defaultValue = "false", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS}, help = "Whether to announce rc options.") public boolean announceRcOptions; @Option( name = "always_profile_slow_operations", defaultValue = "true", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_INTERNAL_CONFIGURATION}, help = "Whether profiling slow operations is always turned on") public boolean alwaysProfileSlowOperations; /** Converter for UUID. Accepts values as specified by {@link UUID#fromString(String)}. */ public static class UUIDConverter implements Converter<UUID> { @Override public UUID convert(String input) throws OptionsParsingException { if (isNullOrEmpty(input)) { return null; } try { return UUID.fromString(input); } catch (IllegalArgumentException e) { throw new OptionsParsingException( String.format("Value '%s' is not a value UUID.", input), e); } } @Override public String getTypeDescription() { return "a UUID"; } } /** * Converter for options (--build_request_id) that accept prefixed UUIDs. Since we do not care * about the structure of this value after validation, we store it as a string. */ public static class PrefixedUUIDConverter implements Converter<String> { @Override public String convert(String input) throws OptionsParsingException { if (isNullOrEmpty(input)) { return null; } // UUIDs that are accepted by UUID#fromString have 36 characters. Interpret the last 36 // characters as an UUID and the rest as a prefix. We do not check anything about the contents // of the prefix. try { int uuidStartIndex = input.length() - 36; UUID.fromString(input.substring(uuidStartIndex)); } catch (IllegalArgumentException | IndexOutOfBoundsException e) { throw new OptionsParsingException( String.format("Value '%s' does not end in a valid UUID.", input), e); } return input; } @Override public String getTypeDescription() { return "An optionally prefixed UUID. The last 36 characters will be verified as a UUID."; } } // Command ID and build request ID can be set either by flag or environment variable. In most // cases, the internally generated ids should be sufficient, but we allow these to be set // externally if required. Option wins over environment variable, if both are set. // TODO(b/67895628) Stop reading ids from the environment after the compatibility window has // passed. @Option( name = "invocation_id", defaultValue = "", converter = UUIDConverter.class, documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.BAZEL_MONITORING, OptionEffectTag.BAZEL_INTERNAL_CONFIGURATION}, help = "Unique identifier, in UUID format, for the command being run. If explicitly specified" + " uniqueness must be ensured by the caller. The UUID is printed to stderr, the BEP" + " and remote execution protocol.") public UUID invocationId; @Option( name = "build_request_id", defaultValue = "", converter = PrefixedUUIDConverter.class, documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.BAZEL_MONITORING, OptionEffectTag.BAZEL_INTERNAL_CONFIGURATION}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "Unique string identifier for the build being run.") public String buildRequestId; @Option( name = "build_metadata", converter = AssignmentConverter.class, defaultValue = "null", allowMultiple = true, documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, help = "Custom key-value string pairs to supply in a build event.") public List<Map.Entry<String, String>> buildMetadata; @Option( name = "oom_message", defaultValue = "", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.BAZEL_MONITORING, OptionEffectTag.TERMINAL_OUTPUT}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "Custom message to be emitted on an out of memory failure.") public String oomMessage; @Option( name = "generate_json_trace_profile", oldName = "experimental_generate_json_trace_profile", defaultValue = "auto", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "If enabled, Bazel profiles the build and writes a JSON-format profile into a file in" + " the output base. View profile by loading into chrome://tracing. By default Bazel" + " writes the profile for all build-like commands and query.") public TriState enableTracer; @Option( name = "experimental_profile_additional_tasks", converter = ProfilerTaskConverter.class, defaultValue = "null", allowMultiple = true, documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "Specifies additional profile tasks to be included in the profile.") public List<ProfilerTask> additionalProfileTasks; @Option( name = "slim_profile", oldName = "experimental_slim_json_profile", defaultValue = "true", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "Slims down the size of the JSON profile by merging events if the profile gets " + " too large.") public boolean slimProfile; @Option( name = "experimental_profile_include_primary_output", oldName = "experimental_include_primary_output", defaultValue = "false", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "Includes the extra \"out\" attribute in action events that contains the exec path " + "to the action's primary output.") public boolean includePrimaryOutput; @Option( name = "experimental_profile_include_target_label", defaultValue = "false", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "Includes target label in action events' JSON profile data.") public boolean profileIncludeTargetLabel; @Option( name = "experimental_announce_profile_path", defaultValue = "false", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "If enabled, adds the JSON profile path to the log.") public boolean announceProfilePath; @Option( name = "profile", defaultValue = "null", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, converter = OptionsUtils.PathFragmentConverter.class, help = "If set, profile Bazel and write data to the specified " + "file. Use bazel analyze-profile to analyze the profile.") public PathFragment profilePath; @Option( name = "starlark_cpu_profile", defaultValue = "", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.BAZEL_MONITORING}, help = "Writes into the specified file a pprof profile of CPU usage by all Starlark threads.") public String starlarkCpuProfile; @Option( name = "record_full_profiler_data", defaultValue = "false", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "By default, Bazel profiler will record only aggregated data for fast but numerous " + "events (such as statting the file). If this option is enabled, profiler will " + "record each event - resulting in more precise profiling data but LARGE " + "performance hit. Option only has effect if --profile used as well.") public boolean recordFullProfilerData; @Option( name = "memory_profile", defaultValue = "null", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, converter = OptionsUtils.PathFragmentConverter.class, help = "If set, write memory usage data to the specified file at phase ends and stable heap to" + " master log at end of build.") public PathFragment memoryProfilePath; @Option( name = "memory_profile_stable_heap_parameters", defaultValue = "1,0", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.BAZEL_MONITORING}, converter = MemoryProfileStableHeapParameters.Converter.class, help = "Tune memory profile's computation of stable heap at end of build. Should be two" + " integers separated by a comma. First parameter is the number of GCs to perform." + " Second parameter is the number of seconds to wait between GCs.") public MemoryProfileStableHeapParameters memoryProfileStableHeapParameters; @Option( name = "experimental_oom_more_eagerly_threshold", defaultValue = "100", documentationCategory = OptionDocumentationCategory.EXECUTION_STRATEGY, effectTags = {OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS}, help = "If this flag is set to a value less than 100, Bazel will OOM if, after two full GC's, " + "more than this percentage of the (old gen) heap is still occupied.") public int oomMoreEagerlyThreshold; @Option( name = "heap_dump_on_oom", defaultValue = "false", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.BAZEL_MONITORING}, help = "Whether to manually output a heap dump if an OOM is thrown (including OOMs due to" + " --experimental_oom_more_eagerly_threshold). The dump will be written to" + " <output_base>/<invocation_id>.heapdump.hprof. This option effectively replaces" + " -XX:+HeapDumpOnOutOfMemoryError, which has no effect because OOMs are caught and" + " redirected to Runtime#halt.") public boolean heapDumpOnOom; @Option( name = "startup_time", defaultValue = "0", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "The time in ms the launcher spends before sending the request to the bazel server.") public long startupTime; @Option( name = "extract_data_time", defaultValue = "0", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "The time in ms spent on extracting the new bazel version.") public long extractDataTime; @Option( name = "command_wait_time", defaultValue = "0", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "The time in ms a command had to wait on a busy Bazel server process.") public long waitTime; @Option( name = "tool_tag", defaultValue = "", documentationCategory = OptionDocumentationCategory.LOGGING, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, help = "A tool name to attribute this Bazel invocation to.") public String toolTag; @Option( name = "restart_reason", defaultValue = "no_restart", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "The reason for the server restart.") public String restartReason; @Option( name = "binary_path", defaultValue = "", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.BAZEL_MONITORING}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "The absolute path of the bazel binary.") public String binaryPath; @Option( name = "experimental_allow_project_files", defaultValue = "false", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.CHANGES_INPUTS}, metadataTags = {OptionMetadataTag.EXPERIMENTAL, OptionMetadataTag.HIDDEN}, help = "Enable processing of +<file> parameters.") public boolean allowProjectFiles; @Option( name = "block_for_lock", defaultValue = "true", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.BAZEL_INTERNAL_CONFIGURATION}, metadataTags = {OptionMetadataTag.HIDDEN}, help = "If set (the default), a command will block if there is another one running. If " + "unset, these commands will immediately return with an error.") public boolean blockForLock; // We could accept multiple of these, in the event where there's a chain of tools that led to a // Bazel invocation. We would not want to expect anything from the order of these, and would need // to guarantee that the "label" for each command line is unique. Unless a need is demonstrated, // though, logs are a better place to track this information than flags, so let's try to avoid it. @Option( // In May 2018, this feature will have been out for 6 months. If the format we accept has not // changed in that time, we can remove the "experimental" prefix and tag. name = "experimental_tool_command_line", defaultValue = "", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.AFFECTS_OUTPUTS}, // Keep this flag HIDDEN so that it is not listed with our reported command lines, it being // reported separately. metadataTags = {OptionMetadataTag.EXPERIMENTAL, OptionMetadataTag.HIDDEN}, converter = ToolCommandLineEvent.Converter.class, help = "An extra command line to report with this invocation's command line. Useful for tools " + "that invoke Bazel and want the original information that the tool received to be " + "logged with the rest of the Bazel invocation.") public ToolCommandLineEvent toolCommandLine; @Option( name = "unconditional_warning", defaultValue = "null", documentationCategory = OptionDocumentationCategory.UNDOCUMENTED, effectTags = {OptionEffectTag.TERMINAL_OUTPUT}, allowMultiple = true, help = "A warning that will unconditionally get printed with build warnings and errors. This is" + " useful to deprecate bazelrc files or --config definitions. If the intent is to" + " effectively deprecate some flag or combination of flags, this is NOT sufficient." + " The flag or flags should use the deprecationWarning field in the option" + " definition, or the bad combination should be checked for programmatically.") public List<String> deprecationWarnings; @Option( name = "track_incremental_state", oldName = "keep_incrementality_data", defaultValue = "true", documentationCategory = OptionDocumentationCategory.BUILD_TIME_OPTIMIZATION, effectTags = {OptionEffectTag.LOSES_INCREMENTAL_STATE}, help = "If false, Blaze will not persist data that allows for invalidation and re-evaluation " + "on incremental builds in order to save memory on this build. Subsequent builds " + "will not have any incrementality with respect to this one. Usually you will want " + "to specify --batch when setting this to false.") public boolean trackIncrementalState; @Option( name = "keep_state_after_build", defaultValue = "true", documentationCategory = OptionDocumentationCategory.BUILD_TIME_OPTIMIZATION, effectTags = {OptionEffectTag.LOSES_INCREMENTAL_STATE}, help = "If false, Blaze will discard the inmemory state from this build when the build " + "finishes. Subsequent builds will not have any incrementality with respect to this " + "one.") public boolean keepStateAfterBuild; @Option( name = "repo_env", converter = Converters.OptionalAssignmentConverter.class, allowMultiple = true, defaultValue = "null", documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS, effectTags = {OptionEffectTag.ACTION_COMMAND_LINES}, help = "Specifies additional environment variables to be available only for repository rules." + " Note that repository rules see the full environment anyway, but in this way" + " configuration information can be passed to repositories through options without" + " invalidating the action graph.") public List<Map.Entry<String, String>> repositoryEnvironment; /** The option converter to check that the user can only specify legal profiler tasks. */ public static class ProfilerTaskConverter extends EnumConverter<ProfilerTask> { public ProfilerTaskConverter() { super(ProfilerTask.class, "profiler task"); } } }
3e158171d487c3077ede2010c9d31ba4a42b63b5
12,602
java
Java
src/main/java/org/attribyte/api/pubsub/impl/H2Datastore.java
attribyte/pubsubhub
8f4da0fc55a8b388ebbf7930b34bc322009ca2a2
[ "Apache-2.0" ]
2
2015-02-20T16:48:17.000Z
2017-11-09T16:44:46.000Z
src/main/java/org/attribyte/api/pubsub/impl/H2Datastore.java
attribyte/pubsubhub
8f4da0fc55a8b388ebbf7930b34bc322009ca2a2
[ "Apache-2.0" ]
6
2015-02-09T16:19:16.000Z
2022-01-21T23:17:46.000Z
src/main/java/org/attribyte/api/pubsub/impl/H2Datastore.java
attribyte/pubsubhub
8f4da0fc55a8b388ebbf7930b34bc322009ca2a2
[ "Apache-2.0" ]
1
2018-04-19T00:14:09.000Z
2018-04-19T00:14:09.000Z
40.5209
174
0.616966
9,141
package org.attribyte.api.pubsub.impl; import com.google.common.base.Charsets; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import org.attribyte.api.DatastoreException; import org.attribyte.api.InitializationException; import org.attribyte.api.Logger; import org.attribyte.api.http.AuthScheme; import org.attribyte.api.pubsub.HubDatastore; import org.attribyte.api.pubsub.Subscriber; import org.attribyte.api.pubsub.Subscription; import org.attribyte.api.pubsub.Topic; import org.attribyte.api.pubsub.impl.server.util.ServerUtil; import org.attribyte.util.SQLUtil; import org.h2.tools.RunScript; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import java.util.Properties; /** * A datastore implementation that uses H2 syntax. */ public class H2Datastore extends RDBDatastore { public static final String H2_INIT_FILE = "config/h2_pubsub_hub.sql"; @Override public void init(String prefix, Properties props, HubDatastore.EventHandler eventHandler, Logger logger) throws InitializationException { super.init(prefix,props, eventHandler, logger); String h2InitFile = props.getProperty("h2.initFile", H2_INIT_FILE); logger.info("Creating H2 database and tables..."); File sqlInitFile = new File(ServerUtil.systemInstallDir(), h2InitFile); if(!sqlInitFile.exists()) { throw new InitializationException("The " + sqlInitFile.getAbsolutePath() + " must exist to use H2"); } if(!sqlInitFile.canRead()) { throw new InitializationException("The " + sqlInitFile.getAbsolutePath() + " must be readable to use H2"); } Connection conn = null; try { conn = getConnection(); RunScript.execute(conn, new FileReader(sqlInitFile)); } catch(SQLException se) { throw new InitializationException("Problem initializing H2", se); } catch(IOException ioe) { throw new InitializationException("Problem reading the H2 init file", ioe); } finally { SQLUtil.closeQuietly(conn); } } private static final String getTopicSQL = "SELECT id, createTime FROM topic WHERE topicURL=?"; private static final String createTopicSQL = "INSERT INTO topic (topicURL, topicHash) VALUES (?,?)"; /** * Safe to assume (I hope!) that for H2 our process is the only one manipulating the database. */ private final Object CREATE_TOPIC_LOCK = new Object(); /** * H2 does not support the MD5 function. */ private final HashFunction md5 = Hashing.md5(); @Override public Topic getTopic(final String topicURL, final boolean create) throws DatastoreException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Topic newTopic = null; try { conn = getConnection(); stmt = conn.prepareStatement(getTopicSQL); stmt.setString(1, topicURL); rs = stmt.executeQuery(); if(rs.next()) { return new Topic(topicURL, rs.getLong(1), new Date(rs.getTimestamp(2).getTime())); } else if(create) { SQLUtil.closeQuietly(rs); rs = null; synchronized(CREATE_TOPIC_LOCK) { rs = stmt.executeQuery(); //Was the topic created while we were waiting for this lock? if(rs.next()) { return new Topic(topicURL, rs.getLong(1), new Date(rs.getTimestamp(2).getTime())); } SQLUtil.closeQuietly(stmt, rs); rs = null; stmt = null; stmt = conn.prepareStatement(createTopicSQL, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, topicURL); stmt.setString(2, md5.hashString(topicURL, Charsets.UTF_8).toString()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { newTopic = new Topic(topicURL, rs.getLong(1), new Date()); return newTopic; } else { throw new DatastoreException("Problem creating topic: Expecting 'id' to be generated."); } } } else { return null; } } catch(SQLException se) { throw new DatastoreException("Problem getting topic", se); } finally { SQLUtil.closeQuietly(conn, stmt, rs); if(newTopic != null && eventHandler != null) { eventHandler.newTopic(newTopic); } } } private static final String updateSubscriptionSQL = "UPDATE subscription SET endpointId=?, status=?, leaseSeconds=?, hmacSecret=? WHERE id=?"; private static final String updateSubscriptionExtendLeaseSQL = "UPDATE subscription SET endpointId=?, status=?, leaseSeconds=?, hmacSecret=?, expireTime=DATEADD('SECOND', ?, NOW()) WHERE id=?"; private static final String createSubscriptionSQL = "INSERT INTO subscription (endpointId, topicId, callbackURL, callbackHash, callbackHost, callbackPath, status, createTime, leaseSeconds, hmacSecret, expireTime)" + "VALUES (?,?,?,?,?,?,?,NOW(),?,?,DATEADD('SECOND', ?, NOW()))"; /** * Assume for H2 that this is the only process manipulating the database. */ private final Object UPDATE_SUBSCRIPTION_LOCK = new Object(); @Override public Subscription updateSubscription(final Subscription subscription, boolean extendLease) throws DatastoreException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; synchronized(UPDATE_SUBSCRIPTION_LOCK) { final Subscription currSubscription; if(subscription.getId() > 0L) { currSubscription = getSubscription(subscription.getId()); } else { currSubscription = getSubscription(subscription.getTopic().getURL(), subscription.getCallbackURL()); } Subscription newSubscription = null; try { if(currSubscription == null) { Topic topic = subscription.getTopic(); if(topic.getId() < 1) { topic = getTopic(topic.getURL(), true); //Create a new topic... } conn = getConnection(); stmt = conn.prepareStatement(createSubscriptionSQL, Statement.RETURN_GENERATED_KEYS); stmt.setLong(1, subscription.getEndpointId()); stmt.setLong(2, topic.getId()); stmt.setString(3, subscription.getCallbackURL()); stmt.setString(4, md5.hashString(subscription.getCallbackURL(), Charsets.UTF_8).toString()); stmt.setString(5, subscription.getCallbackHost()); stmt.setString(6, subscription.getCallbackPath()); stmt.setInt(7, subscription.getStatus().getValue()); stmt.setInt(8, subscription.getLeaseSeconds() < 0 ? 0 : subscription.getLeaseSeconds()); stmt.setString(9, subscription.getSecret()); stmt.setInt(10, subscription.getLeaseSeconds()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { long newId = rs.getLong(1); SQLUtil.closeQuietly(conn, stmt, rs); conn = null; stmt = null; rs = null; newSubscription = getSubscription(newId); return newSubscription; } else { throw new DatastoreException("Problem creating Subscription: Expecting id to be generated"); } } else { Subscription.Status newStatus = subscription.getStatus(); if(newStatus != Subscription.Status.ACTIVE) { extendLease = false; //Never extend the lease for inactive subscriptions. } conn = getConnection(); if(!extendLease) { stmt = conn.prepareStatement(updateSubscriptionSQL); } else { stmt = conn.prepareStatement(updateSubscriptionExtendLeaseSQL); } stmt.setLong(1, subscription.getEndpointId()); stmt.setInt(2, newStatus.getValue()); stmt.setInt(3, subscription.getLeaseSeconds() < 0 ? 0 : subscription.getLeaseSeconds()); stmt.setString(4, subscription.getSecret()); if(!extendLease) { stmt.setLong(5, currSubscription.getId()); } else { stmt.setInt(5, subscription.getLeaseSeconds()); stmt.setLong(6, currSubscription.getId()); } } stmt.executeUpdate(); SQLUtil.closeQuietly(conn, stmt); //Avoid using two connections concurrently... conn = null; stmt = null; rs = null; return getSubscription(currSubscription.getId()); } catch(SQLException se) { throw new DatastoreException("Problem updating subscription", se); } finally { SQLUtil.closeQuietly(conn, stmt, rs); if(newSubscription != null && eventHandler != null) { eventHandler.newSubscription(newSubscription); } } } } private static final String changeSubscriptionStatusSQL = "UPDATE subscription SET status=? WHERE id=?"; private static final String changeSubscriptionStatusLeaseSQL = "UPDATE subscription SET status=?, leaseSeconds=?, expireTime=DATEADD('SECOND', ?, NOW()) WHERE id=?"; @Override public void changeSubscriptionStatus(final long id, final Subscription.Status newStatus, final int newLeaseSeconds) throws DatastoreException { Connection conn = null; PreparedStatement stmt = null; try { conn = getConnection(); if(newLeaseSeconds > 0) { stmt = conn.prepareStatement(changeSubscriptionStatusLeaseSQL); stmt.setInt(1, newStatus.getValue()); stmt.setInt(2, newLeaseSeconds); stmt.setInt(3, newLeaseSeconds); stmt.setLong(4, id); } else { stmt = conn.prepareStatement(changeSubscriptionStatusSQL); stmt.setInt(1, newStatus.getValue()); stmt.setLong(2, id); } if(stmt.executeUpdate() == 0) { throw new DatastoreException("The subscription with id=" + id + " does not exist"); } } catch(SQLException se) { throw new DatastoreException("Problem updating subscription", se); } finally { SQLUtil.closeQuietly(conn, stmt); } } private static final String createSubscriberSQL = "INSERT INTO subscriber (endpointURL, authScheme, authId) VALUES (?,?,?)"; /** * Assume for H2 that this is the only process manipulating the database. */ private final Object CREATE_SUBSCRIBER_LOCK = new Object(); @Override public Subscriber createSubscriber(final String endpointURL, final AuthScheme scheme, final String authId) throws DatastoreException { synchronized(CREATE_SUBSCRIBER_LOCK) { //Was the subscriber created by another thread while we were waiting for this lock? Subscriber subscriber = getSubscriber(endpointURL, scheme, authId, false); if(subscriber != null) { return subscriber; } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.prepareStatement(createSubscriberSQL, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, endpointURL); stmt.setString(2, scheme == null ? "" : scheme.getScheme()); stmt.setString(3, authId == null ? "" : authId); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { return new Subscriber(endpointURL, rs.getLong(1), scheme, authId); } else { throw new DatastoreException("Problem creating subscriber: Expecting 'id' to be generated."); } } catch(SQLException se) { throw new DatastoreException("Problem creating subscriber", se); } finally { SQLUtil.closeQuietly(conn, stmt, rs); } } } }
3e1581f9dffe23c66d23446eaebb7c9f350c071b
869
java
Java
blogPessoal_Com_Teste_Unitario/src/main/java/org/generation/blogPessoal/model/UsuarioLogin.java
Brisola2021/Exercicios_SpringBoot
468649db68d210d0581e25bfa203e65330df4e78
[ "Apache-2.0" ]
1
2022-02-22T12:49:06.000Z
2022-02-22T12:49:06.000Z
blogPessoal_Com_Teste_Unitario/src/main/java/org/generation/blogPessoal/model/UsuarioLogin.java
Brisola2021/Exercicios_SpringBoot
468649db68d210d0581e25bfa203e65330df4e78
[ "Apache-2.0" ]
null
null
null
blogPessoal_Com_Teste_Unitario/src/main/java/org/generation/blogPessoal/model/UsuarioLogin.java
Brisola2021/Exercicios_SpringBoot
468649db68d210d0581e25bfa203e65330df4e78
[ "Apache-2.0" ]
null
null
null
13.369231
41
0.672037
9,142
package org.generation.blogPessoal.model; public class UsuarioLogin { private Long id; private String nome; private String usuario; private String senha; private String foto; private String token; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getFoto() { return foto; } public void setFoto(String foto) { this.foto = foto; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
3e15828cde43f2d499eb1075e2aea81471cd29c8
1,964
java
Java
jrosmessages/src/main/java/module-info.java
lambdaprime/jrosmessages
ca55fa692aadc2c9b41e929cf8b515fceeef892c
[ "Apache-2.0" ]
null
null
null
jrosmessages/src/main/java/module-info.java
lambdaprime/jrosmessages
ca55fa692aadc2c9b41e929cf8b515fceeef892c
[ "Apache-2.0" ]
null
null
null
jrosmessages/src/main/java/module-info.java
lambdaprime/jrosmessages
ca55fa692aadc2c9b41e929cf8b515fceeef892c
[ "Apache-2.0" ]
null
null
null
41.851064
100
0.749365
9,143
/* * Copyright 2022 jrosmessages project * * Website: https://github.com/lambdaprime/jrosmessages * * 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. */ /** * Java module with ROS (Robot Operating System) message definitions. These message definitions are * currently used in <a href="https://github.com/lambdaprime/jrosclient">jrosclient</a> but they are * independent from it and can be used in other Java projects too. * * <p>By default every message in this module implements toString method which returns ROS message * representation in JSON format (including all its values). * * @see <a href= "http://portal2.atwebpages.com/jrosclient/Defining_messages.html">Defining new * messages</a> * @see <a href= "https://github.com/lambdaprime/jrosmessages/releases">Download</a> * @see <a href="https://github.com/lambdaprime/jrosmessages">GitHub repository</a> * @see <a href= "http://portal2.atwebpages.com/jrosclient/">jrosclient documentation</a> * @author * lambdaprime ychag@example.com */ module jrosmessages { requires id.xfunction; requires id.kineticstreamer; requires java.logging; exports id.jrosmessages; exports id.jrosmessages.primitives; exports id.jrosmessages.std_msgs; exports id.jrosmessages.geometry_msgs; exports id.jrosmessages.sensor_msgs; exports id.jrosmessages.trajectory_msgs; exports id.jrosmessages.shape_msgs; exports id.jrosmessages.object_recognition_msgs; }
3e158357898bc0da5dc9570aa6f60ba3a91fc1b0
13,364
java
Java
cloudgraph-hbase/src/main/java/org/cloudgraph/hbase/filter/MultiColumnPredicateVisitor.java
cloudgraph/cloudgraph
d81d0192c354c7ea755363b8ce8b9605e924792f
[ "ECL-2.0", "Apache-2.0" ]
14
2017-07-21T03:01:10.000Z
2022-01-16T20:40:02.000Z
cloudgraph-hbase/src/main/java/org/cloudgraph/hbase/filter/MultiColumnPredicateVisitor.java
cloudgraph/cloudgraph
d81d0192c354c7ea755363b8ce8b9605e924792f
[ "ECL-2.0", "Apache-2.0" ]
46
2017-07-31T02:16:22.000Z
2022-03-13T19:05:13.000Z
cloudgraph-hbase/src/main/java/org/cloudgraph/hbase/filter/MultiColumnPredicateVisitor.java
cloudgraph/cloudgraph
d81d0192c354c7ea755363b8ce8b9605e924792f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
40.49697
108
0.720368
9,144
/** * Copyright 2017 TerraMeta Software, 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 org.cloudgraph.hbase.filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.BinaryPrefixComparator; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.FilterList.Operator; import org.apache.hadoop.hbase.filter.QualifierFilter; import org.apache.hadoop.hbase.filter.RegexStringComparator; import org.apache.hadoop.hbase.filter.ValueFilter; import org.cloudgraph.hbase.key.CompositeColumnKeyFactory; import org.cloudgraph.hbase.service.HBaseDataConverter; import org.cloudgraph.store.lang.GraphFilterException; import org.cloudgraph.store.lang.InvalidOperatorException; import org.plasma.query.model.AbstractPathElement; import org.plasma.query.model.Expression; import org.plasma.query.model.Literal; import org.plasma.query.model.LogicalOperator; import org.plasma.query.model.NullLiteral; import org.plasma.query.model.Path; import org.plasma.query.model.PathElement; import org.plasma.query.model.PredicateOperator; import org.plasma.query.model.Property; import org.plasma.query.model.QueryConstants; import org.plasma.query.model.Term; import org.plasma.query.model.WildcardPathElement; import org.plasma.sdo.DataFlavor; import org.plasma.sdo.PlasmaProperty; import org.plasma.sdo.PlasmaType; import org.plasma.sdo.access.DataAccessException; import org.plasma.sdo.helper.DataConverter; /** * Creates an HBase column filter hierarchy using <a target="#" href= * "http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/QualifierFilter.html" * >QualifierFilter</a> /<a target="#" href= * "http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/ValueFilter.html" * >ValueFilter</a> pairs recreating composite column qualifier prefixes using * {@link CompositeColumnKeyFactory}. Processes visitor events for query model * elements specific to assembly of HBase column filters, such as properties, * wildcards, literals, logical operators, relational operators, within the * context of HBase filter hierarchy assembly. Maintains various context * information useful to subclasses. * <p> * HBase filters may be collected into lists using <a href= * "http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FilterList.html" * target="#">FilterList</a> each with a <a href= * "http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FilterList.Operator.html#MUST_PASS_ALL" * target="#">MUST_PASS_ALL</a> or <a href= * "http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/filter/FilterList.Operator.html#MUST_PASS_ONE" * target="#">MUST_PASS_ONE</a> (logical) operator. Lists may then be assembled * into hierarchies used to represent complex expression trees filtering either * rows or columns in HBase. * </p> * * @see org.cloudgraph.common.key.CompositeColumnKeyFactory * @author Scott Cinnamond * @since 0.5 */ public class MultiColumnPredicateVisitor extends PredicateVisitor { private static Log log = LogFactory.getLog(MultiColumnPredicateVisitor.class); protected CompositeColumnKeyFactory columnKeyFac; protected String contextPropertyPath; protected Property contextQueryProperty; protected FilterList qualifierFilterList = new FilterList(FilterList.Operator.MUST_PASS_ONE); protected FilterList valueFilterList = new FilterList(FilterList.Operator.MUST_PASS_ALL); public MultiColumnPredicateVisitor(PlasmaType rootType) { super(rootType); } /** * Process the traversal start event for a query * {@link org.plasma.query.model.Expression expression} creating a new HBase * {@link org.apache.hadoop.hbase.filter.FilterList filter list} with a * default {@link Operator#MUST_PASS_ALL AND} operator and pushes it onto the * stack. Any subsequent {@link org.plasma.query.model.Literal literals} * encountered then cause a new * {@link org.apache.hadoop.hbase.filter.RowFilter row filter} to be created * and added to this new filter list which is on the top of the stack. * * @param expression * the expression */ @Override public void start(Expression expression) { int childExprCount = getChildExpressionCount(expression); if (childExprCount > 0) { if (log.isDebugEnabled()) log.debug("pushing AND expression filter"); this.pushFilter(FilterList.Operator.MUST_PASS_ALL); } for (Term term : expression.getTerms()) if (term.getPredicateOperator() != null) { switch (term.getPredicateOperator().getValue()) { case IN: case NOT_IN: case EXISTS: case NOT_EXISTS: throw new GraphFilterException("subqueries for row filters not yet supported"); default: } } } /** * Process the traversal end event for a query * {@link org.plasma.query.model.Expression expression} removing the current * (top) HBase {@link org.apache.hadoop.hbase.filter.FilterList filter list} * from the stack. * * @param expression * the expression */ @Override public void end(Expression expression) { if (hasChildExpressions(expression)) { if (log.isDebugEnabled()) log.debug("poping expression filter"); this.popFilter(); } } /** * Process the traversal start event for a query * {@link org.plasma.query.model.Property property} within an * {@link org.plasma.query.model.Expression expression} just traversing the * property path if exists and capturing context information for the current * {@link org.plasma.query.model.Expression expression}. * * @see org.plasma.query.visitor.DefaultQueryVisitor#start(org.plasma.query.model.Property) */ @Override public void start(Property property) { Path path = property.getPath(); PlasmaType targetType = (PlasmaType) this.contextType; if (path != null) { for (int i = 0; i < path.getPathNodes().size(); i++) { AbstractPathElement pathElem = path.getPathNodes().get(i).getPathElement(); if (pathElem instanceof WildcardPathElement) throw new DataAccessException( "wildcard path elements applicable for 'Select' clause paths only, not 'Where' clause paths"); PathElement namedPathElem = ((PathElement) pathElem); PlasmaProperty prop = (PlasmaProperty) targetType.getProperty(namedPathElem.getValue()); namedPathElem.setPhysicalNameBytes(prop.getPhysicalNameBytes()); targetType = (PlasmaType) prop.getType(); // traverse } } PlasmaProperty endpointProp = (PlasmaProperty) targetType.getProperty(property.getName()); this.contextProperty = endpointProp; this.contextType = targetType; this.contextPropertyPath = property.asPathString(); this.contextQueryProperty = property; byte[] colKey = this.columnKeyFac.createColumnKey(this.contextType, this.contextProperty); this.contextQueryProperty.setPhysicalNameBytes(colKey); QualifierFilter qualFilter = new QualifierFilter(CompareFilter.CompareOp.EQUAL, new BinaryPrefixComparator(colKey)); qualifierFilterList.addFilter(qualFilter); if (qualifierFilterList.getFilters().size() == 1) // first one this.filterStack.peek().addFilter(qualifierFilterList); super.start(property); } public void start(PredicateOperator operator) { switch (operator.getValue()) { case LIKE: this.contextHBaseCompareOp = CompareFilter.CompareOp.EQUAL; this.contextOpWildcard = true; this.contextWildcardOperator = operator; break; default: throw new GraphFilterException("unknown operator '" + operator.getValue().toString() + "'"); } super.start(operator); } /** * Process the traversal start event for a query * {@link org.plasma.query.model.Literal literal} within an * {@link org.plasma.query.model.Expression expression} creating an HBase * {@link org.apache.hadoop.hbase.filter.RowFilter row filter} and adding it * to the filter hierarchy. Looks at the context under which the literal is * encountered and if a user defined row key token configuration is found, * creates a regular expression based HBase row filter. * * @param literal * the expression literal * @throws GraphFilterException * if no user defined row-key token is configured for the current * literal context. */ @Override public void start(Literal literal) { String content = literal.getValue(); if (this.contextProperty == null) throw new IllegalStateException("expected context property for literal"); if (this.contextQueryProperty == null) throw new IllegalStateException("expected context query property for literal"); if (this.contextType == null) throw new IllegalStateException("expected context type for literal"); if (this.rootType == null) throw new IllegalStateException("expected context type for literal"); if (this.contextHBaseCompareOp == null) throw new IllegalStateException("expected context operator for literal"); byte[] colKey = this.contextQueryProperty.getPhysicalNameBytes(); ValueFilter valueFilter = null; if (!this.contextOpWildcard) { Object valueObj = DataConverter.INSTANCE.fromString(this.contextProperty.getType(), content); byte[] valueBytes = HBaseDataConverter.INSTANCE.toBytes(this.contextProperty, valueObj); valueFilter = new ValueFilter(this.contextHBaseCompareOp, new BinaryComparator(valueBytes)); } else { if (!validateWildcardDataFlavor(this.contextProperty.getDataFlavor())) throw new InvalidOperatorException(this.contextWildcardOperator.getValue().name(), this.contextProperty.getDataFlavor()); String replaceExpr = "\\" + QueryConstants.WILDCARD; String expr = getDataFlavorRegex(this.contextProperty.getDataFlavor()); String contentExpr = content.replaceAll(replaceExpr, expr); valueFilter = new ValueFilter(this.contextHBaseCompareOp, new RegexStringComparator( contentExpr)); } valueFilterList.addFilter(valueFilter); if (valueFilterList.getFilters().size() == 1) // first one this.filterStack.peek().addFilter(valueFilterList); super.start(literal); } private boolean validateWildcardDataFlavor(DataFlavor dataFlavor) { switch (dataFlavor) { case string: return true; case temporal: case integral: case real: case other: default: return false; } } private String getDataFlavorRegex(DataFlavor dataFlavor) { switch (dataFlavor) { case integral: return "[0-9\\-]+?"; case real: return "[0-9\\-\\.]+?"; default: return ".*?"; // any character zero or more times } } /** * (non-Javadoc) * * @see org.plasma.query.visitor.DefaultQueryVisitor#start(org.plasma.query.model.NullLiteral) */ @Override public void start(NullLiteral nullLiteral) { throw new GraphFilterException("null literals for row filters not yet supported"); } /** * Process a {@link org.plasma.query.model.LogicalOperator logical operator} * query traversal start event. If the {@link FilterList filter list} on the * top of the filter stack is not an 'OR' filter, since it's immutable and we * cannot modify its operator, create an 'OR' filter and swaps out the * existing filters into the new 'OR' {@link FilterList filter list}. */ public void start(LogicalOperator operator) { switch (operator.getValue()) { case AND: // FilterList andList = new FilterList( // FilterList.Operator.MUST_PASS_ALL); // if (this.filterStack.size() > 0) { // FilterList top = this.filterStack.peek(); // top.addFilter(andList); // } // else { // this.filterStack.push(andList); // } break; // default filter list oper is must-pass-all (AND) case OR: FilterList top = this.filterStack.peek(); if (top.getOperator().ordinal() != FilterList.Operator.MUST_PASS_ONE.ordinal()) { FilterList orList = new FilterList(FilterList.Operator.MUST_PASS_ONE); for (Filter filter : top.getFilters()) orList.addFilter(filter); top.getFilters().clear(); this.filterStack.pop(); FilterList previous = this.filterStack.peek(); if (!previous.getFilters().remove(top)) throw new IllegalStateException("could not remove filter list"); previous.addFilter(orList); this.filterStack.push(orList); } break; } super.start(operator); } }
3e15837b8d3efdc7b19b184e3b7ecd04f53febb3
2,313
java
Java
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java
yangfancoming/spring-boot-build
3d4b8cbb8fea3e68617490609a68ded8f034bc67
[ "Apache-2.0" ]
null
null
null
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java
yangfancoming/spring-boot-build
3d4b8cbb8fea3e68617490609a68ded8f034bc67
[ "Apache-2.0" ]
8
2020-01-31T18:21:07.000Z
2022-03-08T21:12:35.000Z
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java
yangfancoming/spring-boot-build
3d4b8cbb8fea3e68617490609a68ded8f034bc67
[ "Apache-2.0" ]
null
null
null
30.434211
84
0.765672
9,145
package org.springframework.boot.actuate.metrics.web.reactive.server; import java.util.concurrent.TimeUnit; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; /** * Intercepts incoming HTTP requests handled by Spring WebFlux handlers. * * @author Jon Schneider * @author Brian Clozel * @since 2.0.0 */ @Order(Ordered.HIGHEST_PRECEDENCE + 1) public class MetricsWebFilter implements WebFilter { private final MeterRegistry registry; private final WebFluxTagsProvider tagsProvider; private final String metricName; public MetricsWebFilter(MeterRegistry registry, WebFluxTagsProvider tagsProvider, String metricName) { this.registry = registry; this.tagsProvider = tagsProvider; this.metricName = metricName; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange).compose((call) -> filter(exchange, call)); } private Publisher<Void> filter(ServerWebExchange exchange, Mono<Void> call) { long start = System.nanoTime(); ServerHttpResponse response = exchange.getResponse(); return call.doOnSuccess((done) -> success(exchange, start)).doOnError((cause) -> { if (response.isCommitted()) { error(exchange, start, cause); } else { response.beforeCommit(() -> { error(exchange, start, cause); return Mono.empty(); }); } }); } private void success(ServerWebExchange exchange, long start) { Iterable<Tag> tags = this.tagsProvider.httpRequestTags(exchange, null); this.registry.timer(this.metricName, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } private void error(ServerWebExchange exchange, long start, Throwable cause) { Iterable<Tag> tags = this.tagsProvider.httpRequestTags(exchange, cause); this.registry.timer(this.metricName, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }
3e158429f8c6a5c5aa7574e1439f7c5a10cca434
9,345
java
Java
rhm-webapp/src/edu/ucar/dls/harvest/tools/XMLDocumentValidator.java
rhuan080/dls-repository-stack
8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3
[ "ECL-2.0", "Apache-2.0" ]
2
2017-06-16T10:03:46.000Z
2017-07-05T11:15:10.000Z
rhm-webapp/src/edu/ucar/dls/harvest/tools/XMLDocumentValidator.java
rhuan080/dls-repository-stack
8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
rhm-webapp/src/edu/ucar/dls/harvest/tools/XMLDocumentValidator.java
rhuan080/dls-repository-stack
8e19d6a9a3390ce3e3e1031ea8d0f4c5db6eb7d3
[ "ECL-2.0", "Apache-2.0" ]
1
2019-12-03T17:18:43.000Z
2019-12-03T17:18:43.000Z
35
130
0.734082
9,146
/* Copyright 2017 Digital Learning Sciences (DLS) at the University Corporation for Atmospheric Research (UCAR), P.O. Box 3000, Boulder, CO 80307 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.ucar.dls.harvest.tools; /** * This class is based off the one from DLESE tools except that it uses pools * for caching the .xsd and can validate Strings. */ //Imported JAXP classes import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; //SAX import import org.dlese.dpc.xml.Dom4jUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import java.io.StringReader; public class XMLDocumentValidator{ // Grammar pool for this instance: private Object grammarPool = null; public StringBuffer outputBuffer = null; // returned result values public static final int VALID_RESULT = 1; public static final int VALID_W_WARNINGS_RESULT = 2; public static final int NOT_VALID_RESULT = 3; public static final int NOT_WELL_FORMED_RESULT = 4; // default settings protected final static String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces"; /** Namespace prefixes feature id (http://xml.org/sax/features/namespace-prefixes). */ protected final static String NAMESPACE_PREFIXES_FEATURE_ID = "http://xml.org/sax/features/namespace-prefixes"; /** Validation feature id (http://xml.org/sax/features/validation). */ protected final static String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation"; /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */ protected final static String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema"; /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ protected final static String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; /** Dynamic validation feature id (http://apache.org/xml/features/validation/dynamic). */ protected final static String DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic"; /** Default parser name. */ protected final static String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser"; /** Default namespaces support (true). */ protected final static boolean DEFAULT_NAMESPACES = true; /** Default namespace prefixes (false). */ protected final static boolean DEFAULT_NAMESPACE_PREFIXES = false; /** Default validation support (false). */ protected final static boolean DEFAULT_VALIDATION = true; /** Default Schema validation support (false). */ protected final static boolean DEFAULT_SCHEMA_VALIDATION = true; /** Default Schema full checking support (false). */ protected final static boolean DEFAULT_SCHEMA_FULL_CHECKING = true; /** Default dynamic validation support (false). */ protected final static boolean DEFAULT_DYNAMIC_VALIDATION = false; /** Default memory usage report (false). */ protected final static boolean DEFAULT_MEMORY_USAGE = false; /** Default "tagginess" report (false). */ protected final static boolean DEFAULT_TAGGINESS = false; public int validateString(String s, boolean showWarnings, boolean enableSchemaCaching) throws DocumentException { int index = 0; while(index<10) { try{ InputSource input = new InputSource(new StringReader(s)); return this.parseAndValidate(input, showWarnings, enableSchemaCaching); } catch(java.lang.StackOverflowError e) { Document document = Dom4jUtils.getXmlDocument(s); Element rootElement = document.getRootElement(); Element longestElement = this.findLongestTextElement(rootElement); int longestElementDesiredLength = longestElement.getText().length() / 2; String newText = longestElement.getText().substring(0, longestElementDesiredLength); longestElement.setText(newText); s = rootElement.asXML(); index = index + 1; } } return NOT_VALID_RESULT; } private Element findLongestTextElement(Element element) { Element longestElement = null; Element elementToCompare = null; for(Object childElementObj: element.elements()) { Element childElement = (Element)childElementObj; if(childElement.elements().size()>0) { elementToCompare = findLongestTextElement(childElement); } else { elementToCompare = childElement; } // compare the text if(longestElement==null || elementToCompare.getText().length() > longestElement.getText().length()) { longestElement = elementToCompare; } } return longestElement; } protected int parseAndValidate(InputSource input, boolean showWarnings, boolean enableSchemaCaching) { try { //prtln("parse: dir = " + dir + " filename = " + filename ); //prtln("parse: f.getAbsolutePath(): " + f.getAbsolutePath()); StringBuffer errorBuff = new StringBuffer(); //prtln("parse: f.getAbsolutePath(): " + f.getAbsolutePath()); StringBuffer warningBuff = new StringBuffer(); outputBuffer = new StringBuffer(); boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; SAXParserFactory spfact = SAXParserFactory.newInstance(); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); // Turn on schema/grammar caching (see http://www.ibm.com/developerworks/xml/library/x-perfap3/index.html for details): if (enableSchemaCaching) { try { if (this.grammarPool == null) { Class poolClass = Class.forName("org.apache.xerces.util.XMLGrammarPoolImpl"); this.grammarPool = poolClass.newInstance(); } parser.setProperty("http://apache.org/xml/properties/internal/grammar-pool", this.grammarPool); } catch (Throwable e) { //prtlnErr("Not able to cache schemas/grammars while validating: " + e); } } //reader.setFeature("http://xml.org/sax/features/validation", true); //reader.setFeature("http://apache.org/xml/features/validation/schema", true); //reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true); // set parser features try { reader.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { reader.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { reader.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { reader.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { reader.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { reader.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } SimpleErrorHandler handler = new SimpleErrorHandler(errorBuff, warningBuff); // Do the parse and capture validation errors in the handler parser.parse(input, handler); if (handler.hasErrors()) { // not valid outputBuffer.append("NOT VALID: \n"); outputBuffer.append(errorBuff.toString()); return NOT_VALID_RESULT; } if (handler.hasWarnings()) { outputBuffer.append("Warning: \n"); outputBuffer.append(warningBuff.toString()); return VALID_W_WARNINGS_RESULT; } return VALID_RESULT; } catch (Exception e) { // Serious problem! outputBuffer.append("NOT WELL-FORMED: \n " + e.getMessage() + "\n"); return NOT_WELL_FORMED_RESULT; } } }
3e1584f84868211fd0876e017f811152c08e81e8
3,269
java
Java
juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/args/RequestBeanArg.java
apache/juneau
9af6b8a3c96a544aeba3f98114c57e79478a92ba
[ "Apache-2.0" ]
65
2017-11-01T00:59:36.000Z
2021-11-06T22:04:06.000Z
juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/args/RequestBeanArg.java
apache/juneau
9af6b8a3c96a544aeba3f98114c57e79478a92ba
[ "Apache-2.0" ]
43
2018-01-11T23:36:18.000Z
2021-03-06T15:00:05.000Z
juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/args/RequestBeanArg.java
apache/juneau
9af6b8a3c96a544aeba3f98114c57e79478a92ba
[ "Apache-2.0" ]
34
2017-11-01T00:59:38.000Z
2021-11-06T22:03:57.000Z
54.483333
199
0.588253
9,147
// *************************************************************************************************************************** // * 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.apache.juneau.rest.args; import org.apache.juneau.*; import org.apache.juneau.http.annotation.*; import org.apache.juneau.httppart.bean.*; import org.apache.juneau.reflect.*; import org.apache.juneau.rest.*; import org.apache.juneau.rest.annotation.*; /** * Resolves method parameters annotated with {@link Request} on {@link RestOp}-annotated Java methods. * * <p> * The parameter value is resolved using <c><jv>opSession</jv>.{@link RestOpSession#getRequest() getRequest}().{@link RestRequest#getRequest(RequestBeanMeta) getRequest}(<jv>requestBeanMeta</jv>)</c> * with a {@link RequestBeanMeta meta} derived from the {@link Request} annotation and context configuration. */ public class RequestBeanArg implements RestOpArg { private final RequestBeanMeta meta; /** * Static creator. * * @param paramInfo The Java method parameter being resolved. * @param annotations The annotations to apply to any new part parsers. * @return A new {@link RequestBeanArg}, or <jk>null</jk> if the parameter is not annotated with {@link Request}. */ public static RequestBeanArg create(ParamInfo paramInfo, AnnotationWorkList annotations) { if (paramInfo.hasAnnotation(Request.class)) return new RequestBeanArg(paramInfo, annotations); return null; } /** * Constructor. * * @param paramInfo The Java method parameter being resolved. * @param annotations The annotations to apply to any new part parsers. */ protected RequestBeanArg(ParamInfo paramInfo, AnnotationWorkList annotations) { this.meta = RequestBeanMeta.create(paramInfo, annotations); } @Override /* RestOpArg */ public Object resolve(RestOpSession opSession) throws Exception { return opSession.getRequest().getRequest(meta); } }
3e1585a658ee436e5c108b70e50485a7a4f4ae51
23,516
java
Java
google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java
MShaffar19/java-spanner
c99294beb43ce1bd67cc3d12e4104641efab6710
[ "Apache-2.0" ]
null
null
null
google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java
MShaffar19/java-spanner
c99294beb43ce1bd67cc3d12e4104641efab6710
[ "Apache-2.0" ]
null
null
null
google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java
MShaffar19/java-spanner
c99294beb43ce1bd67cc3d12e4104641efab6710
[ "Apache-2.0" ]
2
2020-10-04T11:25:16.000Z
2020-10-04T11:25:28.000Z
42.447653
117
0.658403
9,148
/* * Copyright 2019 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 * * https://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.cloud.spanner.spi.v1; import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import com.google.api.core.ApiFunction; import com.google.api.gax.rpc.ApiCallContext; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.OAuth2Credentials; import com.google.cloud.spanner.DatabaseAdminClient; import com.google.cloud.spanner.DatabaseClient; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.ErrorCode; import com.google.cloud.spanner.InstanceAdminClient; import com.google.cloud.spanner.MockSpannerServiceImpl; import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime; import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; import com.google.cloud.spanner.ResultSet; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.SpannerOptions.CallContextConfigurator; import com.google.cloud.spanner.SpannerOptions.CallCredentialsProvider; import com.google.cloud.spanner.Statement; import com.google.cloud.spanner.TransactionContext; import com.google.cloud.spanner.TransactionRunner.TransactionCallable; import com.google.cloud.spanner.admin.database.v1.MockDatabaseAdminImpl; import com.google.cloud.spanner.admin.instance.v1.MockInstanceAdminImpl; import com.google.cloud.spanner.spi.v1.SpannerRpc.Option; import com.google.common.base.Stopwatch; import com.google.protobuf.ListValue; import com.google.spanner.admin.database.v1.Database; import com.google.spanner.admin.database.v1.DatabaseName; import com.google.spanner.admin.instance.v1.Instance; import com.google.spanner.admin.instance.v1.InstanceConfigName; import com.google.spanner.admin.instance.v1.InstanceName; import com.google.spanner.v1.ExecuteSqlRequest; import com.google.spanner.v1.GetSessionRequest; import com.google.spanner.v1.ResultSetMetadata; import com.google.spanner.v1.SpannerGrpc; import com.google.spanner.v1.StructType; import com.google.spanner.v1.StructType.Field; import com.google.spanner.v1.TypeCode; import io.grpc.CallCredentials; import io.grpc.Context; import io.grpc.Contexts; import io.grpc.ManagedChannelBuilder; import io.grpc.Metadata; import io.grpc.Metadata.Key; import io.grpc.MethodDescriptor; import io.grpc.Server; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.auth.MoreCallCredentials; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.threeten.bp.Duration; /** Tests that opening and closing multiple Spanner instances does not leak any threads. */ @RunWith(JUnit4.class) public class GapicSpannerRpcTest { private static final Statement SELECT1AND2 = Statement.of("SELECT 1 AS COL1 UNION ALL SELECT 2 AS COL1"); private static final ResultSetMetadata SELECT1AND2_METADATA = ResultSetMetadata.newBuilder() .setRowType( StructType.newBuilder() .addFields( Field.newBuilder() .setName("COL1") .setType( com.google.spanner.v1.Type.newBuilder() .setCode(TypeCode.INT64) .build()) .build()) .build()) .build(); private static final com.google.spanner.v1.ResultSet SELECT1_RESULTSET = com.google.spanner.v1.ResultSet.newBuilder() .addRows( ListValue.newBuilder() .addValues(com.google.protobuf.Value.newBuilder().setStringValue("1").build()) .build()) .addRows( ListValue.newBuilder() .addValues(com.google.protobuf.Value.newBuilder().setStringValue("2").build()) .build()) .setMetadata(SELECT1AND2_METADATA) .build(); private static final Statement UPDATE_FOO_STATEMENT = Statement.of("UPDATE FOO SET BAR=1 WHERE BAZ=2"); private static final String STATIC_OAUTH_TOKEN = "STATIC_TEST_OAUTH_TOKEN"; private static final String VARIABLE_OAUTH_TOKEN = "VARIABLE_TEST_OAUTH_TOKEN"; private static final OAuth2Credentials STATIC_CREDENTIALS = OAuth2Credentials.create( new AccessToken( STATIC_OAUTH_TOKEN, new java.util.Date( System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(1L, TimeUnit.DAYS)))); private static final OAuth2Credentials VARIABLE_CREDENTIALS = OAuth2Credentials.create( new AccessToken( VARIABLE_OAUTH_TOKEN, new java.util.Date( System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(1L, TimeUnit.DAYS)))); private MockSpannerServiceImpl mockSpanner; private MockInstanceAdminImpl mockInstanceAdmin; private MockDatabaseAdminImpl mockDatabaseAdmin; private Server server; private InetSocketAddress address; private final Map<SpannerRpc.Option, Object> optionsMap = new HashMap<>(); @BeforeClass public static void checkNotEmulator() { assumeTrue( "Skip tests when emulator is enabled as this test interferes with the check whether the emulator is running", System.getenv("SPANNER_EMULATOR_HOST") == null); } @Before public void startServer() throws IOException { mockSpanner = new MockSpannerServiceImpl(); mockSpanner.setAbortProbability(0.0D); // We don't want any unpredictable aborted transactions. mockSpanner.putStatementResult(StatementResult.query(SELECT1AND2, SELECT1_RESULTSET)); mockSpanner.putStatementResult(StatementResult.update(UPDATE_FOO_STATEMENT, 1L)); mockInstanceAdmin = new MockInstanceAdminImpl(); mockDatabaseAdmin = new MockDatabaseAdminImpl(); address = new InetSocketAddress("localhost", 0); server = NettyServerBuilder.forAddress(address) .addService(mockSpanner) .addService(mockInstanceAdmin) .addService(mockDatabaseAdmin) // Add a server interceptor that will check that we receive the variable OAuth token // from the CallCredentials, and not the one set as static credentials. .intercept( new ServerInterceptor() { @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { String auth = headers.get(Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER)); assertThat(auth).isEqualTo("Bearer " + VARIABLE_OAUTH_TOKEN); return Contexts.interceptCall(Context.current(), call, headers, next); } }) .build() .start(); optionsMap.put(Option.CHANNEL_HINT, Long.valueOf(1L)); } @After public void stopServer() throws InterruptedException { server.shutdown(); server.awaitTermination(); } private static final int NUMBER_OF_TEST_RUNS = 2; private static final int NUM_THREADS_PER_CHANNEL = 4; private static final String SPANNER_THREAD_NAME = "Cloud-Spanner-TransportChannel"; private static final String THREAD_PATTERN = "%s-[0-9]+"; @Test public void testCloseAllThreadsWhenClosingSpanner() throws InterruptedException { for (int i = 0; i < NUMBER_OF_TEST_RUNS; i++) { assertThat(getNumberOfThreadsWithName(SPANNER_THREAD_NAME, true), is(equalTo(0))); // Create Spanner instance. SpannerOptions options = createSpannerOptions(); Spanner spanner = options.getService(); // Get a database client and do a query. This should initiate threads for the Spanner service. DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of("[PROJECT]", "[INSTANCE]", "[DATABASE]")); List<ResultSet> resultSets = new ArrayList<>(); // SpannerStub affiliates a channel with a session, so we need to use multiple sessions // to ensure we also hit multiple channels. for (int i2 = 0; i2 < options.getSessionPoolOptions().getMaxSessions(); i2++) { ResultSet rs = client.singleUse().executeQuery(SELECT1AND2); // Execute ResultSet#next() to send the query to Spanner. rs.next(); // Delay closing the result set in order to force the use of multiple sessions. // As each session is linked to one transport channel, using multiple different // sessions should initialize multiple transport channels. resultSets.add(rs); // Check whether the number of expected threads has been reached. if (getNumberOfThreadsWithName(SPANNER_THREAD_NAME, false) == options.getNumChannels() * NUM_THREADS_PER_CHANNEL) { break; } } for (ResultSet rs : resultSets) { rs.close(); } // Then do a request to the InstanceAdmin service and check the number of threads. // Doing a request should initialize a thread pool for the underlying InstanceAdminClient. for (int i2 = 0; i2 < options.getNumChannels() * 2; i2++) { mockGetInstanceResponse(); InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient(); instanceAdminClient.getInstance("projects/[PROJECT]/instances/[INSTANCE]"); } // Then do a request to the DatabaseAdmin service and check the number of threads. // Doing a request should initialize a thread pool for the underlying DatabaseAdminClient. for (int i2 = 0; i2 < options.getNumChannels() * 2; i2++) { mockGetDatabaseResponse(); DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient(); databaseAdminClient.getDatabase("projects/[PROJECT]/instances/[INSTANCE]", "[DATABASE]"); } // Now close the Spanner instance and check whether the threads are shutdown or not. spanner.close(); // Wait for up to two seconds to allow the threads to actually shutdown. Stopwatch watch = Stopwatch.createStarted(); while (getNumberOfThreadsWithName(SPANNER_THREAD_NAME, false) > 0 && watch.elapsed(TimeUnit.SECONDS) < 2) { Thread.sleep(10L); } assertThat(getNumberOfThreadsWithName(SPANNER_THREAD_NAME, true), is(equalTo(0))); } } /** * Tests that multiple open {@link Spanner} objects at the same time does not share any executors * or worker threads, and that all of them are shutdown when the {@link Spanner} object is closed. */ @Test public void testMultipleOpenSpanners() throws InterruptedException { List<Spanner> spanners = new ArrayList<>(); assertThat(getNumberOfThreadsWithName(SPANNER_THREAD_NAME, true), is(equalTo(0))); for (int openSpanners = 1; openSpanners <= 3; openSpanners++) { // Create Spanner instance. SpannerOptions options = createSpannerOptions(); Spanner spanner = options.getService(); spanners.add(spanner); // Get a database client and do a query. This should initiate threads for the Spanner service. DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of("[PROJECT]", "[INSTANCE]", "[DATABASE]")); List<ResultSet> resultSets = new ArrayList<>(); // SpannerStub affiliates a channel with a session, so we need to use multiple sessions // to ensure we also hit multiple channels. for (int sessionCount = 0; sessionCount < options.getSessionPoolOptions().getMaxSessions() && getNumberOfThreadsWithName(SPANNER_THREAD_NAME, false) < options.getNumChannels() * NUM_THREADS_PER_CHANNEL * openSpanners; sessionCount++) { ResultSet rs = client.singleUse().executeQuery(SELECT1AND2); // Execute ResultSet#next() to send the query to Spanner. rs.next(); // Delay closing the result set in order to force the use of multiple sessions. // As each session is linked to one transport channel, using multiple different // sessions should initialize multiple transport channels. resultSets.add(rs); } for (ResultSet rs : resultSets) { rs.close(); } } for (Spanner spanner : spanners) { spanner.close(); } // Wait a little to allow the threads to actually shutdown. Stopwatch watch = Stopwatch.createStarted(); while (getNumberOfThreadsWithName(SPANNER_THREAD_NAME, false) > 0 && watch.elapsed(TimeUnit.SECONDS) < 2) { Thread.sleep(10L); } assertThat(getNumberOfThreadsWithName(SPANNER_THREAD_NAME, true), is(equalTo(0))); } @Test public void testCallCredentialsProviderPreferenceAboveCredentials() { SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(STATIC_CREDENTIALS) .setCallCredentialsProvider( new CallCredentialsProvider() { @Override public CallCredentials getCallCredentials() { return MoreCallCredentials.from(VARIABLE_CREDENTIALS); } }) .build(); GapicSpannerRpc rpc = new GapicSpannerRpc(options); // GoogleAuthLibraryCallCredentials doesn't implement equals, so we can only check for the // existence. assertThat( rpc.newCallContext( optionsMap, "/some/resource", GetSessionRequest.getDefaultInstance(), SpannerGrpc.getGetSessionMethod()) .getCallOptions() .getCredentials()) .isNotNull(); rpc.shutdown(); } @Test public void testCallCredentialsProviderReturnsNull() { SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(STATIC_CREDENTIALS) .setCallCredentialsProvider( new CallCredentialsProvider() { @Override public CallCredentials getCallCredentials() { return null; } }) .build(); GapicSpannerRpc rpc = new GapicSpannerRpc(options); assertThat( rpc.newCallContext( optionsMap, "/some/resource", GetSessionRequest.getDefaultInstance(), SpannerGrpc.getGetSessionMethod()) .getCallOptions() .getCredentials()) .isNull(); rpc.shutdown(); } @Test public void testNoCallCredentials() { SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("some-project") .setCredentials(STATIC_CREDENTIALS) .build(); GapicSpannerRpc rpc = new GapicSpannerRpc(options); assertThat( rpc.newCallContext( optionsMap, "/some/resource", GetSessionRequest.getDefaultInstance(), SpannerGrpc.getGetSessionMethod()) .getCallOptions() .getCredentials()) .isNull(); rpc.shutdown(); } private static final class TimeoutHolder { private Duration timeout; } @Test public void testCallContextTimeout() { // Create a CallContextConfigurator that uses a variable timeout value. final TimeoutHolder timeoutHolder = new TimeoutHolder(); CallContextConfigurator configurator = new CallContextConfigurator() { @Override public <ReqT, RespT> ApiCallContext configure( ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) { // Only configure a timeout for the ExecuteSql method as this method is used for // executing DML statements. if (request instanceof ExecuteSqlRequest && method.equals(SpannerGrpc.getExecuteSqlMethod())) { ExecuteSqlRequest sqlRequest = (ExecuteSqlRequest) request; // Sequence numbers are only assigned for DML statements, which means that // this is an update statement. if (sqlRequest.getSeqno() > 0L) { return context.withTimeout(timeoutHolder.timeout); } } return null; } }; mockSpanner.setExecuteSqlExecutionTime(SimulatedExecutionTime.ofMinimumAndRandomTime(10, 0)); SpannerOptions options = createSpannerOptions(); try (Spanner spanner = options.getService()) { final DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of("[PROJECT]", "[INSTANCE]", "[DATABASE]")); Context context = Context.current().withValue(SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY, configurator); context.run( new Runnable() { @Override public void run() { try { // First try with a 1ns timeout. This should always cause a DEADLINE_EXCEEDED // exception. timeoutHolder.timeout = Duration.ofNanos(1L); client .readWriteTransaction() .run( new TransactionCallable<Long>() { @Override public Long run(TransactionContext transaction) throws Exception { return transaction.executeUpdate(UPDATE_FOO_STATEMENT); } }); fail("missing expected timeout exception"); } catch (SpannerException e) { assertThat(e.getErrorCode()).isEqualTo(ErrorCode.DEADLINE_EXCEEDED); } // Then try with a longer timeout. This should now succeed. timeoutHolder.timeout = Duration.ofMinutes(1L); Long updateCount = client .readWriteTransaction() .run( new TransactionCallable<Long>() { @Override public Long run(TransactionContext transaction) throws Exception { return transaction.executeUpdate(UPDATE_FOO_STATEMENT); } }); assertThat(updateCount).isEqualTo(1L); } }); } } @Test public void testNewCallContextWithNullRequestAndNullMethod() { SpannerOptions options = SpannerOptions.newBuilder().setProjectId("some-project").build(); GapicSpannerRpc rpc = new GapicSpannerRpc(options); assertThat(rpc.newCallContext(optionsMap, "/some/resource", null, null)).isNotNull(); rpc.shutdown(); } @SuppressWarnings("rawtypes") private SpannerOptions createSpannerOptions() { String endpoint = address.getHostString() + ":" + server.getPort(); return SpannerOptions.newBuilder() .setProjectId("[PROJECT]") // Set a custom channel configurator to allow http instead of https. .setChannelConfigurator( new ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder>() { @Override public ManagedChannelBuilder apply(ManagedChannelBuilder input) { input.usePlaintext(); return input; } }) .setHost("http://" + endpoint) // Set static credentials that will return the static OAuth test token. .setCredentials(STATIC_CREDENTIALS) // Also set a CallCredentialsProvider. These credentials should take precedence above // the static credentials. .setCallCredentialsProvider( new CallCredentialsProvider() { @Override public CallCredentials getCallCredentials() { return MoreCallCredentials.from(VARIABLE_CREDENTIALS); } }) .build(); } private int getNumberOfThreadsWithName(String serviceName, boolean dumpStack) { Pattern pattern = Pattern.compile(String.format(THREAD_PATTERN, serviceName)); ThreadGroup group = Thread.currentThread().getThreadGroup(); while (group.getParent() != null) { group = group.getParent(); } Thread[] threads = new Thread[100 * NUMBER_OF_TEST_RUNS]; int numberOfThreads = group.enumerate(threads); int res = 0; for (int i = 0; i < numberOfThreads; i++) { if (pattern.matcher(threads[i].getName()).matches()) { if (dumpStack) { dumpThread(threads[i]); } res++; } } return res; } private void dumpThread(Thread thread) { StringBuilder dump = new StringBuilder(); dump.append('"'); dump.append(thread.getName()); dump.append("\" "); final Thread.State state = thread.getState(); dump.append("\n java.lang.Thread.State: "); dump.append(state); final StackTraceElement[] stackTraceElements = thread.getStackTrace(); for (final StackTraceElement stackTraceElement : stackTraceElements) { dump.append("\n at "); dump.append(stackTraceElement); } dump.append("\n\n"); System.out.print(dump.toString()); } private void mockGetInstanceResponse() { InstanceName name2 = InstanceName.of("[PROJECT]", "[INSTANCE]"); InstanceConfigName config = InstanceConfigName.of("[PROJECT]", "[INSTANCE_CONFIG]"); String displayName = "displayName1615086568"; int nodeCount = 1539922066; Instance expectedResponse = Instance.newBuilder() .setName(name2.toString()) .setConfig(config.toString()) .setDisplayName(displayName) .setNodeCount(nodeCount) .build(); mockInstanceAdmin.addResponse(expectedResponse); } private void mockGetDatabaseResponse() { DatabaseName name2 = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]"); Database expectedResponse = Database.newBuilder().setName(name2.toString()).build(); mockDatabaseAdmin.addResponse(expectedResponse); } }
3e1585dc01d99ebecc5c7f21628099a5526e206e
1,653
java
Java
vividus-plugin-web-app/src/main/java/org/vividus/ui/web/action/search/FieldNameSearch.java
veranikaChyrun/vividus
630ba535345f92d7e613129f84e4712cbb734c68
[ "Apache-2.0" ]
null
null
null
vividus-plugin-web-app/src/main/java/org/vividus/ui/web/action/search/FieldNameSearch.java
veranikaChyrun/vividus
630ba535345f92d7e613129f84e4712cbb734c68
[ "Apache-2.0" ]
197
2021-10-06T14:21:59.000Z
2022-03-27T02:13:43.000Z
vividus-plugin-web-app/src/main/java/org/vividus/ui/web/action/search/FieldNameSearch.java
veranikaChyrun/vividus
630ba535345f92d7e613129f84e4712cbb734c68
[ "Apache-2.0" ]
null
null
null
37.568182
119
0.729583
9,149
/* * Copyright 2019-2020 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 * * https://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.vividus.ui.web.action.search; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; import org.vividus.ui.action.search.IElementSearchAction; import org.vividus.ui.action.search.SearchParameters; import org.vividus.ui.web.util.LocatorUtil; public class FieldNameSearch extends AbstractWebElementSearchAction implements IElementSearchAction { public FieldNameSearch() { super(WebLocatorType.FIELD_NAME); } @Override public List<WebElement> search(SearchContext searchContext, SearchParameters parameters) { // due to firefox bug, we can't use name() and must use local-name() as workaround 'body' represents CKE editor By locator = LocatorUtil.getXPathLocator(".//*[(local-name() = 'input' or local-name() = 'textarea' or " + "local-name()='body') and ((@* | text())=%s)]", parameters.getValue()); return findElements(searchContext, locator, parameters); } }
3e158680ed335decc8ade322e3976a93e28f6bfe
975
java
Java
thirdparty/pasco2/src/isi/pasco2/parser/DateTime.java
RANDCorporation/autopsy-jar
f571f512bc71940c10f6929f5df5ac93512f639c
[ "Apache-2.0" ]
1,473
2015-01-02T06:13:10.000Z
2022-03-30T09:45:34.000Z
thirdparty/pasco2/src/isi/pasco2/parser/DateTime.java
manuelh2410/autopsy
10a6bc5c159b4af60d93412e739ce9469acbeb71
[ "Apache-2.0" ]
1,068
2015-02-04T14:33:38.000Z
2022-03-31T03:49:28.000Z
thirdparty/pasco2/src/isi/pasco2/parser/DateTime.java
manuelh2410/autopsy
10a6bc5c159b4af60d93412e739ce9469acbeb71
[ "Apache-2.0" ]
510
2015-01-09T19:46:08.000Z
2022-03-23T13:25:34.000Z
31.451613
75
0.74359
9,150
/* * Copyright 2006 Bradley Schatz. All rights reserved. * * This file is part of pasco2, the next generation Internet Explorer cache * and history record parser. * * pasco2 is free software; you can redistribute it and/or modify * 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. * * pasco2 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 pasco2; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package isi.pasco2.parser; import java.util.Date; public interface DateTime { public Date asDate(); }
3e15874b711ae6c3718626b1a75722655b16c9da
4,269
java
Java
src/com/netease/nim/uikit/common/media/imagepicker/adapter/ImageSectionAdapter.java
ckchenkai/uikit
5cf09ee955697c049f5d708a6e7f72f88a37953c
[ "MIT" ]
623
2015-09-08T07:35:36.000Z
2021-06-01T09:57:32.000Z
src/com/netease/nim/uikit/common/media/imagepicker/adapter/ImageSectionAdapter.java
ckchenkai/uikit
5cf09ee955697c049f5d708a6e7f72f88a37953c
[ "MIT" ]
60
2016-09-09T04:54:01.000Z
2021-04-14T00:54:11.000Z
src/com/netease/nim/uikit/common/media/imagepicker/adapter/ImageSectionAdapter.java
ckchenkai/uikit
5cf09ee955697c049f5d708a6e7f72f88a37953c
[ "MIT" ]
116
2015-10-16T03:25:27.000Z
2021-05-07T16:32:57.000Z
37.121739
108
0.628953
9,151
package com.netease.nim.uikit.common.media.imagepicker.adapter; import android.view.View; import android.view.ViewGroup; import com.netease.nim.uikit.common.adapter.AdvancedAdapter; import com.netease.nim.uikit.common.adapter.AdvancedDelegate; import com.netease.nim.uikit.common.adapter.BaseViewHolder; import com.netease.nim.uikit.common.media.imagepicker.Constants; import com.netease.nim.uikit.common.media.imagepicker.ImagePicker; import com.netease.nim.uikit.common.media.imagepicker.adapter.vh.CameraViewHolder; import com.netease.nim.uikit.common.media.imagepicker.adapter.vh.ImageItemViewHolder; import com.netease.nim.uikit.common.media.imagepicker.adapter.vh.SectionModel; import com.netease.nim.uikit.common.media.imagepicker.adapter.vh.SectionViewHolder; import com.netease.nim.uikit.common.media.imagepicker.adapter.vh.VideoItemViewHolder; import com.netease.nim.uikit.common.media.imagepicker.ui.ImageBaseActivity; import com.netease.nim.uikit.common.media.model.GLImage; import com.netease.nim.uikit.common.util.media.MediaUtil; import java.util.List; import java.util.Map; /** */ public class ImageSectionAdapter extends AdvancedAdapter { private ImageBaseActivity activity; private ImagePicker imagePicker; private static final int sTypeItemImage = 0; private static final int sTypeItemVideo = 1; private static final int sTypeItemTitle = 2; private static final int sTypeItemCamera = 3; public ImageSectionAdapter(ImageBaseActivity activity) { this.activity = activity; imagePicker = ImagePicker.getInstance(); setDelegate(new AdvancedDelegate() { @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case sTypeItemImage: return new ImageItemViewHolder(parent, imagePicker, ImageSectionAdapter.this); case sTypeItemVideo: return new VideoItemViewHolder(parent, imagePicker, ImageSectionAdapter.this); case sTypeItemTitle: return new SectionViewHolder(parent, imagePicker, ImageSectionAdapter.this); case sTypeItemCamera: return new CameraViewHolder(parent, ImageSectionAdapter.this.activity, imagePicker); } return null; } }); } public void refreshData(List<GLImage> images) { clear(); if (images != null && images.size() > 0) { Map<String, List<GLImage>> groupedImages = MediaUtil.divideMedias(images); int offset = 0; for (int i = 0; i < groupedImages.keySet().size(); i++) { String key = (String) groupedImages.keySet().toArray()[i]; List<GLImage> items = groupedImages.get(key); SectionModel begin = SectionModel.begin(key, items, offset, listener); // as section? if (imagePicker.isShowSection()) { add(sTypeItemTitle, begin); } int index = 0; for (GLImage item : items) { SectionModel model = SectionModel.wrap(index, begin); if (item.isVideo()) { add(sTypeItemVideo, model); } else { add(sTypeItemImage, model); } index++; } offset += items.size(); } } if (imagePicker.isShowCamera()) { add(sTypeItemCamera, null, 0); } notifyDataSetChanged(); } private OnImageClickListener listener; //图片被点击的监听 public void setOnImageItemClickListener(OnImageClickListener listener) { this.listener = listener; } public interface OnImageClickListener { void onImageItemClick(View view, GLImage GLImage, int position); } public int getSpanSize(int position) { int type = getItemViewType(position); switch (type) { case sTypeItemTitle: return Constants.GRIDVIEW_COLUMN; default: return 1; } } }
3e1587d61327654fb31e99c462625e61276f7b61
19,071
java
Java
src/wrapper/expressionFilter/Parser.java
fabio-gomes/xml-inference
8e81fdcd651e11fecb780820a8d87e5b4457309f
[ "MIT" ]
null
null
null
src/wrapper/expressionFilter/Parser.java
fabio-gomes/xml-inference
8e81fdcd651e11fecb780820a8d87e5b4457309f
[ "MIT" ]
null
null
null
src/wrapper/expressionFilter/Parser.java
fabio-gomes/xml-inference
8e81fdcd651e11fecb780820a8d87e5b4457309f
[ "MIT" ]
1
2019-01-10T01:30:56.000Z
2019-01-10T01:30:56.000Z
30.5136
130
0.50957
9,152
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package wrapper.expressionFilter; import java.util.ArrayList; import java.util.List; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import wrapper.Pair; /** * * @author rpinheiro * @author lmachado */ public class Parser implements IExpression { private IExpression syntaxTree; public IExpression getTreeExpression(){ return syntaxTree; } private boolean isNumber(String token){ boolean bNumber = false; try { int val = Integer.parseInt(token); if ( val > 0 ) bNumber = true; } catch (NumberFormatException nfe) { // bad data - set to sentinel bNumber = false; } return bNumber; } private boolean isElement(String token){ boolean bElement = false; if ( isNumber(token) || token.indexOf("'") > -1) bElement = true; return bElement; } private boolean isOperator(String token){ boolean bOperator = false; if ( token.equals("=") || token.equals(">") || token.equals(">=") || token.equals("<") || token.equals("<=") || token.toUpperCase().equals("AND") || token.toUpperCase().equals("OR") ) bOperator = true; return bOperator; } private IExpression createOperator(String strOperator, IExpression left, IExpression right){ IExpression operator = null; if ( strOperator.equals("=") ){ operator = new OperatorEqual(left, right); } else if ( strOperator.equals(">") ){ operator = new OperatorGreaterThan(left, right); } else if ( strOperator.equals(">=")){ operator = new OperatorGreaterEqualThan(left, right); } else if ( strOperator.equals("<") ){ operator = new OperatorLessThan(left, right); } else if ( strOperator.equals("<=") ){ operator = new OperatorLessEqualThan(left, right); } else if ( strOperator.toUpperCase().equals("AND") ){ operator = new OperatorAnd(left, right); } else if ( strOperator.toUpperCase().equals("OR") ){ operator = new OperatorOr(left, right); } return operator; } public Parser(String expression) { String tempElementText = ""; int nCountPlic = 0; Stack<IExpression> expressionStack = new Stack<IExpression>(); Stack<String> tempStack = new Stack<String>(); boolean bContinueParse = true; String[] listToken = expression.split(" "); if((expression.indexOf("(") != -1 && expression.indexOf("(") !=0) || expression.indexOf("namespace::") != -1) { int posToken = expression.indexOf("("); if(posToken ==-1) { posToken = expression.indexOf("namespace::"); posToken = posToken + (new String("namespace::")).length(); String functionName = expression.substring(0,posToken); String [] splitList = expression.split(" "); for (String argument : splitList) { if(argument.contains("namespace::")) { String [] argsList = expression.split("::"); if(argsList.length>1) { ArrayList<IExpression> argumentsList = new ArrayList<IExpression>(); String strArg = argsList[1]; String [] nameSpaceArgs = strArg.split(" "); if(nameSpaceArgs.length > 0) strArg = nameSpaceArgs[0]; Element arg = new Element(strArg); argumentsList.add(arg); IExpression operator = new Function(functionName,argumentsList ); expressionStack.push(operator); int posEndToken = argument.length(); int nEnd = expression.length(); int nBegin = posEndToken; if(posEndToken+1 < nEnd) nBegin = posEndToken+1; String tmpSubstring = expression.substring(nBegin, nEnd); listToken = tmpSubstring.split(" "); break; } } } } else { if(listToken.length < 2 ) { if ( posToken > -1 ) { String functionName = expression.substring(0,posToken); //expressionStack.push(new Variable(functionName)); int posTokenEnd = expression.indexOf(")"); String arguments = expression.substring(posToken+1, posTokenEnd); String[] listArguments = arguments.split(","); ArrayList<IExpression> argumentsList = new ArrayList<IExpression>(); for (String argument : listArguments) { if(!argument.isEmpty()) { Element arg = new Element(argument); argumentsList.add(arg); } } IExpression operator = new Function(functionName, argumentsList); expressionStack.push(operator); bContinueParse = false; } } else { /*String functionName = expression.substring(0,posToken); int posEndToken = expression.indexOf(")"); String arguments = expression.substring(posToken+1, posEndToken); String[] listArguments = arguments.split(","); ArrayList<IExpression> argumentsList = new ArrayList<IExpression>(); for (String argument : listArguments) { if(!argument.isEmpty()) { Element arg = new Element(argument); argumentsList.add(arg); } }*/ String strFunction = expression; List<Pair<Integer,Integer>> pairParenthesisList = mapParenthsis(expression); int nPosEndFunction = expression.lastIndexOf(")"); if(pairParenthesisList.size()>0 && pairParenthesisList.get(pairParenthesisList.size()-1).getValue() > nPosEndFunction) nPosEndFunction = pairParenthesisList.get(pairParenthesisList.size()-1).getValue(); if(nPosEndFunction != -1 && nPosEndFunction+1 <= expression.length()) { strFunction = expression.substring(0,nPosEndFunction+1); } expressionStack.addAll(parseFunction(strFunction)); //IExpression operator = new Function(functionName, argumentsList); //expressionStack.push(operator); if(nPosEndFunction == -1) nPosEndFunction = expression.lastIndexOf(")"); if(expression.length()==nPosEndFunction+1) { String strOperator = ""; if(expression.contains("true") ) strOperator = "true"; if(expression.contains("false")) strOperator = "false"; if(expression.contains("=") ) strOperator = "="; if(!strOperator.isEmpty()) { nPosEndFunction = expression.indexOf(strOperator); nPosEndFunction--; } } String tmpSubstring = expression.substring(nPosEndFunction+1, expression.length()); if(tmpSubstring.startsWith(")")) tmpSubstring = expression.substring(nPosEndFunction+2, expression.length()); listToken = tmpSubstring.split(" "); } } } if(bContinueParse) { for (String token : listToken) { if(token.isEmpty()) continue; if ( isOperator(token) ) { tempStack.push(token); } else { if(isElement(token) && listToken.length == 1) { expressionStack.push(new Variable(token)); } else { if ( !isElement(token) && nCountPlic == 0) { if(token.indexOf("(") != -1 && token.indexOf("(") !=0) { int posTokenEnd = token.indexOf(")"); int posToken = token.indexOf("("); String functionName = token.substring(0,posToken); String arguments = token.substring(posToken+1, posTokenEnd); String[] listArguments = arguments.split(","); ArrayList<IExpression> argumentsList = new ArrayList<IExpression>(); for (String argument : listArguments) { if(!argument.isEmpty()) { Element arg = new Element(argument); argumentsList.add(arg); } } IExpression operator = new Function(functionName, argumentsList); expressionStack.push(operator); } else { if(!(token.compareTo("(")==0) && !(token.compareTo(")")==0)) expressionStack.push(new Variable(token)); } } else { if ( token.indexOf("'") > -1 ) nCountPlic++; if ( nCountPlic > 0 && nCountPlic < 2 ) { tempElementText += token.replace("'", "") + " "; continue; } else if ( nCountPlic == 2 ) { token = tempElementText + token.replace("'", ""); tempElementText = ""; } if(!tempStack.isEmpty()) { String strOperator = tempStack.pop(); IExpression otherExp = expressionStack.pop(); IExpression operator = createOperator(strOperator, otherExp, new Element_(token)); expressionStack.push(operator); } } } } } if ( !tempElementText.isEmpty() ){ String strOperator = tempStack.pop(); IExpression operator = createOperator(strOperator, expressionStack.pop(), new Element_(tempElementText.trim())); expressionStack.push(operator); } if ( !tempStack.isEmpty() ){ while ( !tempStack.isEmpty() ){ IExpression rightOperand = expressionStack.pop(); IExpression leftOperand = expressionStack.pop(); IExpression operator = createOperator(tempStack.pop(), leftOperand, rightOperand); expressionStack.push(operator); } } } syntaxTree = expressionStack.pop(); } public String interpret() { return syntaxTree.interpret(); } private List<IExpression> parseFunction(String function) { List<IExpression> listExpression = new ArrayList<IExpression>(); /*List<Pair<Integer,Integer>> pairList = new ArrayList<Pair<Integer,Integer>>(); boolean bHasPlic = false; int beginPosPlic = function.indexOf("'",0); int endPosPlic = -1; while(beginPosPlic > -1) { endPosPlic = function.indexOf("'",beginPosPlic+1); if(beginPosPlic < endPosPlic) { bHasPlic = true; pairList.add(new Pair<Integer, Integer>(beginPosPlic,endPosPlic)); } beginPosPlic = function.indexOf("'",endPosPlic+1); }*/ int posToken = function.indexOf("("); String functionName = function.substring(0,posToken); String arguments = findFunctionArguments(function); String[] listArguments = arguments.split(",(?![^(]*\\))"); ArrayList<IExpression> argumentsList = new ArrayList<IExpression>(); boolean bContainsLogicalOperators = false; boolean bContainsMathOperators = false; if(listArguments.length > 0) { String argsUpper = listArguments[0].toUpperCase(); bContainsLogicalOperators = argsUpper.contains(" NOT") || argsUpper.contains(" AND"); bContainsMathOperators = argsUpper.contains(" - ") || argsUpper.contains(" +") || argsUpper.contains(" *") || argsUpper.contains(" DIV") || argsUpper.contains(" MOD"); } if(!bContainsLogicalOperators && !bContainsMathOperators) { for (String argument : listArguments) { if(!argument.isEmpty()) { int nArgParentesis = argument.indexOf("("); if(nArgParentesis == 0 && argument.length()>0) nArgParentesis = argument.indexOf("(",1); if(nArgParentesis != -1) { argumentsList.addAll(parseFunction(argument)); } else { Element arg = new Element(argument); argumentsList.add(arg); } } } } else { if(bContainsMathOperators && listArguments.length>0) argumentsList.addAll(parseMathOperation(listArguments[0])); } IExpression functionExp = new Function(functionName, argumentsList); listExpression.add(functionExp); return listExpression; } boolean checkParenthesis(String s, int i, int open, int closed){ if(i == s.length()) { if(open != closed) return false; return true; } if(s.charAt(i) == '(') open = open+1; if(s.charAt(i) == ')'){ if(open > closed) closed = closed+1; else return false; } return checkParenthesis(s, i+1, open, closed); } String findFunctionArguments(String in) { /*Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(in); if(m.find()) return m.group(1); return in;*/ String tmp = in; /*if(!tmp.trim().endsWith(")")) tmp+=")";*/ if(!checkParenthesis(tmp,0,0,0)) tmp+=")"; int nStart = tmp.indexOf("("); if(nStart != -1) { //###int nEnd = tmp.lastIndexOf(")"); int nEnd = tmp.lastIndexOf(")"); if(tmp.contains("true")|| tmp.contains("false")) nEnd = tmp.indexOf(")"); if(nEnd != -1 && nStart < nEnd) return tmp.substring(nStart+1,nEnd); } return tmp; } ArrayList<IExpression> parseMathOperation(String mathSentence) { ArrayList<IExpression> argumentsList = new ArrayList<IExpression>(); /*List<Pair<Integer,Integer>> parenthesisPairList = mapParenthsis(mathSentence); if(parenthesisPairList.size()>0) { List<String> listSentences = new ArrayList<String>(); for(int i = parenthesisPairList.size()-1; i>=0;i--) { String subSentence = mathSentence.substring(parenthesisPairList.get(i).getKey(),parenthesisPairList.get(i).getValue()); for(int j=0;j<listSentences.size();j++) { subSentence = subSentence.replace(listSentences.get(j), ""); } } } else { }*/ //Parser parser = new Parser("( number(current) - number(initial) ) div count(bidder) ) > 8"); String[] listArguments = mathSentence.split(" "); //for (String argument : listArguments) for(int i=0; i<listArguments.length;i++) { String argument = listArguments[i]; if(!argument.isEmpty()) { int nArgParentesis = argument.indexOf("("); if(nArgParentesis == 0 && argument.length()>0) nArgParentesis = argument.indexOf("(",1); if(argument.toUpperCase().trim().compareTo("DIV") == 0) { if(i+1 < listArguments.length) { String nextArg = listArguments[i+1]; if(isFunction(nextArg)) argumentsList.addAll(parseFunction(nextArg)); else { Element arg = new Element(argument); argumentsList.add(arg); } i++; } ArrayList<IExpression> divArgumentsList = new ArrayList<IExpression>(argumentsList); Function divFunction = new Function(Function.FUNCTION_DIV,divArgumentsList); argumentsList.clear(); argumentsList.add(divFunction); continue; } if(nArgParentesis != -1 && nArgParentesis!= 0) { argumentsList.addAll(parseFunction(argument)); } else { Element arg = new Element(argument); argumentsList.add(arg); } } } return argumentsList; } private boolean isFunction(String argument) { int nArgParentesis = argument.indexOf("("); if(nArgParentesis == 0 && argument.length()>0) nArgParentesis = argument.indexOf("(",1); if(nArgParentesis != -1 && nArgParentesis!= 0) return true; return false; } private List<Pair<Integer,Integer>> mapParenthsis(String text) { List<Pair<Integer,Integer>> pairParenthesisList = new ArrayList<Pair<Integer,Integer>>(); Stack<Integer> tmpStack =new Stack<Integer>(); int beginPosParenthesis = text.indexOf("(",0); while(beginPosParenthesis > -1) { tmpStack.add(beginPosParenthesis); beginPosParenthesis = text.indexOf("(",beginPosParenthesis+1); } int endPosParenthesis = -1 ; while(!tmpStack.isEmpty()) { beginPosParenthesis = tmpStack.pop(); if(endPosParenthesis == -1) endPosParenthesis = beginPosParenthesis; endPosParenthesis = text.indexOf(")",endPosParenthesis+1); if(endPosParenthesis >-1) pairParenthesisList.add(new Pair<Integer, Integer>(beginPosParenthesis,endPosParenthesis)); } return pairParenthesisList; } }
3e1587f55fccf331ca24c7db4df6f56fcd52c833
1,093
java
Java
java/bindings/src/main/java/com/automatak/dnp3/mock/package-info.java
bevanweiss/opendnp3
c1dc7165a79cc08edbf4b55d2ff4162efb176f92
[ "Apache-2.0" ]
null
null
null
java/bindings/src/main/java/com/automatak/dnp3/mock/package-info.java
bevanweiss/opendnp3
c1dc7165a79cc08edbf4b55d2ff4162efb176f92
[ "Apache-2.0" ]
null
null
null
java/bindings/src/main/java/com/automatak/dnp3/mock/package-info.java
bevanweiss/opendnp3
c1dc7165a79cc08edbf4b55d2ff4162efb176f92
[ "Apache-2.0" ]
null
null
null
43.72
85
0.752059
9,153
/* * Copyright 2013-2022 Step Function I/O, LLC * * Licensed to Green Energy Corp (www.greenenergycorp.com) and Step Function I/O * LLC (https://stepfunc.io) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Green Energy Corp and Step Function I/O LLC license * 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. */ /** * A package of mock callback implementations. * * Not useful for real world applications, but good for demos. */ package com.automatak.dnp3.mock;
3e1589892f3d41d9992d678a3f1d3f9355c16748
3,407
java
Java
plugins/console/console-core/src/main/java/org/apache/geronimo/console/util/TreeEntry.java
fideoman/geronimo
c78546a9c0e1007e65179da780727de8672f9289
[ "Apache-2.0" ]
21
2015-05-05T04:10:19.000Z
2022-01-07T12:36:17.000Z
plugins/console/console-core/src/main/java/org/apache/geronimo/console/util/TreeEntry.java
fideoman/geronimo
c78546a9c0e1007e65179da780727de8672f9289
[ "Apache-2.0" ]
1
2018-02-23T20:53:31.000Z
2018-02-23T20:53:31.000Z
plugins/console/console-core/src/main/java/org/apache/geronimo/console/util/TreeEntry.java
fideoman/geronimo
c78546a9c0e1007e65179da780727de8672f9289
[ "Apache-2.0" ]
29
2016-01-08T21:08:14.000Z
2022-01-07T12:36:20.000Z
25.237037
122
0.620194
9,154
/** * 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.apache.geronimo.console.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.directwebremoting.annotations.DataTransferObject; /* * DWR data transfer object used by debugviews portlets and openejb portlets */ @DataTransferObject public class TreeEntry { // Always Tree's label = "name" private String name; // We always specify the Tree's identifier = null, because we hope the id can be auto-generated so that keeping unique // But in ClassLoaderViewHelper.java, we have to assign the id of node explicitly private String id; // type private String type; // values is used to record assistant information, private String[] values; // children private List<TreeEntry> children; /* * constructors */ public TreeEntry(){ // Not recommended. } public TreeEntry(String name){ this(name, null, null); } public TreeEntry(String name, String type){ this(name, type, null); } public TreeEntry(String name, String type, String[] values){ this.name = name; this.type = type; this.values = values; this.children = new ArrayList<TreeEntry>(); } /* * getters and setters */ public List<TreeEntry> getChildren() { return children; } public void setChildren(List<TreeEntry> children) { this.children = children; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String[] getValues() { return values; } public void setValues(String[] values) { this.values = values; } /* * methods */ public void addChild(TreeEntry child){ this.children.add(child); } public TreeEntry findEntry(String name) { if (name == null) return null; if (this.name != null && this.name.equals(name)) return this; Iterator<TreeEntry> iter = children.iterator(); while (iter.hasNext()) { TreeEntry entry = iter.next().findEntry(name); if (entry != null) return entry; } return null; } }
3e15899cfd2239aba47436e7a0b3d2f834b0a511
4,005
java
Java
utils/RandomNameGenerator/ProbabilityExtractor.java
evelithgit/Cubyz
74eedd00e977aca1d21e3a3d9e3db2ab199e3786
[ "BSD-3-Clause" ]
null
null
null
utils/RandomNameGenerator/ProbabilityExtractor.java
evelithgit/Cubyz
74eedd00e977aca1d21e3a3d9e3db2ab199e3786
[ "BSD-3-Clause" ]
null
null
null
utils/RandomNameGenerator/ProbabilityExtractor.java
evelithgit/Cubyz
74eedd00e977aca1d21e3a3d9e3db2ab199e3786
[ "BSD-3-Clause" ]
null
null
null
27.244898
114
0.495131
9,155
import java.io.*; // Searches through the mineral names and generates a table of probabilities for every 3 char combination. public class ProbabilityExtractor { static int getIndex(char c) { if(c == ' ') return 0; if('a' <= c && c <= 'z') return 1+c-'a'; if('A' <= c && c <= 'Z') return 1+c-'A'; System.err.println("Unknown \'"+c+"\'"+" "+(int)c); System.exit(1); return 0; } static char getChar(int i) { if(i == 0) return ' '; if(i <= 26) return (char)('a'+i-1); System.err.println("Unknown "+i); System.exit(1); return '0'; } public static void main(String[] args) throws IOException { int[] number = new int[27*27*27*27]; try (BufferedReader br = new BufferedReader(new FileReader("./"+args[0]+".txt"))) { String line; while ((line = br.readLine()) != null) { if(line.charAt(0) == '#') continue; // Comments: char c1 = ' ', c2 = ' ', c3 = ' ', c4 = ' '; for(char c : line.toCharArray()) { c1 = c2; c2 = c3; c3 = c4; c4 = c; number[getIndex(c1)*27*27*27 + getIndex(c2)*27*27 + getIndex(c3)*27 + getIndex(c4)]++; } number[getIndex(c2)*27*27*27 + getIndex(c3)*27*27 + getIndex(c4)*27]++; number[getIndex(c3)*27*27*27 + getIndex(c4)*27*27]++; number[getIndex(c4)*27*27*27]++; } } catch(Exception e) {} DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("./"+args[0]+".dat"))); boolean used; // pre-loop to get the length: byte n = 0; os.writeByte(0); outer: for(byte i = 0; i < 27; i++) { for(byte j = 0; j < 27; j++) { for(byte k = 0; k < 27; k++) { for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { n++; continue outer; } } } } } os.writeByte(n); for(byte i = 0; i < 27; i++) { // pre-loop to see if it is actually used: used = false; outer2: for(byte j = 0; j < 27; j++) { for(byte k = 0; k < 27; k++) { for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { used = true; break outer2; } } } } if(!used) continue; os.writeByte(i); // pre-loop to get the length: n = 0; outer3: for(byte j = 0; j < 27; j++) { for(byte k = 0; k < 27; k++) { for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { n++; continue outer3; } } } } os.writeByte(n); for(byte j = 0; j < 27; j++) { // pre-loop to see if it is actually used: used = false; outer4: for(byte k = 0; k < 27; k++) { for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { used = true; break outer4; } } } if(!used) continue; os.writeByte(j); // pre-loop to get the length: n = 0; outer5: for(byte k = 0; k < 27; k++) { for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { n++; continue outer5; } } } os.writeByte(n); for(byte k = 0; k < 27; k++) { // pre-loop to see if it is actually used: used = false; for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { used = true; break; } } if(!used) continue; os.writeByte(k); // pre-loop to get the length: n = 0; int total = 0; for(byte l = 0; l < 27; l++) { // pre-loop to get the length if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { total += number[i*27*27*27 + j*27*27 + k*27 + l]; n++; } } os.writeByte(n); for(byte l = 0; l < 27; l++) { if(number[i*27*27*27 + j*27*27 + k*27 + l] != 0) { os.writeByte(l); } } } } } os.close(); } }
3e158a60434ef8580c46baa3792376af0799adf6
6,568
java
Java
src/main/java/com/alibaba/auto/doc/handler/RequestBodyHandler.java
alibaba/auto-doc
dc2fba3cacc3ca201364384bd19da3d7f0a70bdf
[ "Apache-2.0" ]
11
2020-10-20T13:10:26.000Z
2021-08-07T17:59:56.000Z
src/main/java/com/alibaba/auto/doc/handler/RequestBodyHandler.java
alibaba/auto-doc
dc2fba3cacc3ca201364384bd19da3d7f0a70bdf
[ "Apache-2.0" ]
null
null
null
src/main/java/com/alibaba/auto/doc/handler/RequestBodyHandler.java
alibaba/auto-doc
dc2fba3cacc3ca201364384bd19da3d7f0a70bdf
[ "Apache-2.0" ]
6
2020-11-04T02:52:30.000Z
2022-03-29T02:36:11.000Z
41.834395
178
0.70067
9,156
package com.alibaba.auto.doc.handler; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.auto.doc.builder.ProjectBuilder; import com.alibaba.auto.doc.cache.GlobalFieldCache; import com.alibaba.auto.doc.constants.Constants; import com.alibaba.auto.doc.constants.SpringAnnotation; import com.alibaba.auto.doc.exception.AutoDocException; import com.alibaba.auto.doc.exception.ErrorCodes; import com.alibaba.auto.doc.model.comment.NoFieldCommentFound; import com.alibaba.auto.doc.model.request.RequestBodyParam; import com.alibaba.auto.doc.utils.JavaAnnotationUtil; import com.alibaba.auto.doc.utils.JavaClassUtil; import com.alibaba.auto.doc.utils.JavaFieldUtil; import com.alibaba.auto.doc.utils.StringUtil; import com.thoughtworks.qdox.model.JavaAnnotation; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaField; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author :杨帆(舲扬) * @date :Created in 2020/10/30 8:17 下午 * @description: */ public class RequestBodyHandler { private static final Logger log = LoggerFactory.getLogger(RequestBodyHandler.class); /** * build request body param from JavaField * * @param javaField * @return */ private static RequestBodyParam buildRequestBodyParam(final JavaField javaField) { RequestBodyParam requestBodyParam = new RequestBodyParam(); requestBodyParam.setName(javaField.getName()); requestBodyParam.setType(javaField.getType().getGenericFullyQualifiedName()); requestBodyParam.setComment(javaField.getComment()); if (StringUtils.isBlank(javaField.getComment())) { NoFieldCommentFound noFieldCommentFound = new NoFieldCommentFound(javaField.getDeclaringClass().getCanonicalName(), javaField.getLineNumber(), javaField.getName()); if(!GlobalFieldCache.notExist(javaField)) { log.warn(noFieldCommentFound.toString()); } if(ProjectBuilder.getApiConfig().isStrict()) { throw new AutoDocException(ErrorCodes.AD_MISSING_COMMENT, noFieldCommentFound.toString()); } } requestBodyParam.setIsEnum(javaField.getType().isEnum()); requestBodyParam.setIsCollection(JavaClassUtil.isCollection(javaField.getType())); if (StringUtils.isNotBlank(JavaFieldUtil.getSince(javaField))) { requestBodyParam.setSince(JavaFieldUtil.getSince(javaField)); } requestBodyParam.setRequired(JavaFieldUtil.isRequired(javaField)); String defaultValue = javaField.getInitializationExpression(); defaultValue = StringUtil.removeQuotes(defaultValue); if (StringUtils.isNotBlank(defaultValue)) { requestBodyParam.setDefaultValue(defaultValue); } requestBodyParam.setLineNumber(javaField.getLineNumber()); // set cache GlobalFieldCache.put(javaField); return requestBodyParam; } /** * recursion build * * @param javaClass * @param deep * @return */ private static List<RequestBodyParam> recursionBuild(final JavaClass javaClass, int deep, boolean checkSetMethod, boolean checkGetMethod) { deep++; if (deep > Constants.REQUEST_BODY_PARAM_DEEP) { log.warn("param deep size over {}, current class is {}", Constants.REQUEST_BODY_PARAM_DEEP, javaClass.getCanonicalName()); return null; } List<RequestBodyParam> paramList = new ArrayList<>(); List<JavaField> fieldList = JavaFieldUtil.getFields(javaClass, null, checkSetMethod, checkGetMethod); for (JavaField field : fieldList) { RequestBodyParam requestBodyParam = buildRequestBodyParam(field); JavaClass realJavaClass = JavaClassUtil.getCollectionGenericJavaClass(field.getType(), JavaClassUtil.getGenericType(javaClass)); if (JavaClassUtil.isCustomClass(realJavaClass)) { if(!realJavaClass.getCanonicalName().equals(javaClass.getCanonicalName())) { List<RequestBodyParam> childParams = recursionBuild(realJavaClass, deep, checkSetMethod, checkGetMethod); if (childParams != null && childParams.size() > 0) { requestBodyParam.setChilds(childParams); } } } paramList.add(requestBodyParam); } return paramList; } /** * build request body param from JavaClass * * @param javaClass * @param name * @param comment * @return */ public static RequestBodyParam buildRequestBodyParam(final JavaClass javaClass, String name, String comment, boolean checkSetMethod, boolean checkGetMethod) { RequestBodyParam requestBodyParam = new RequestBodyParam(); requestBodyParam.setName(name); requestBodyParam.setType(javaClass.getGenericFullyQualifiedName()); requestBodyParam.setIsEnum(javaClass.isEnum()); requestBodyParam.setIsCollection(JavaClassUtil.isCollection(javaClass)); requestBodyParam.setComment(comment); requestBodyParam.setChilds(recursionBuild(JavaClassUtil.getCollectionGenericJavaClass(javaClass, null), 0, checkSetMethod, checkGetMethod)); return requestBodyParam; } /** * build request body param * * @param javaParameter * @return */ private RequestBodyParam buildRequestBodyParam(final JavaParameter javaParameter, final Map<String, String> paramCommentMap, boolean checkSetMethod, boolean checkGetMethod) { String comment = paramCommentMap.get(javaParameter.getName()); return buildRequestBodyParam(javaParameter.getJavaClass(), javaParameter.getName(), comment, checkSetMethod, checkGetMethod); } /** * handle * * @param javaMethod * @return */ public RequestBodyParam handle(final JavaMethod javaMethod, Map<String, String> paramCommentMap) { for (JavaParameter parameter : javaMethod.getParameters()) { for (JavaAnnotation annotation : parameter.getAnnotations()) { if (JavaAnnotationUtil.isMatch(annotation, SpringAnnotation.REQUEST_BODY_FULLY)) { return buildRequestBodyParam(parameter, paramCommentMap, true, false); } } } return null; } }
3e158abaa186e56c51bbf36a006f467e9cf63c91
4,395
java
Java
app/src/main/java/com/nntc/escapefromcastilla/ui/GameActivity.java
F1uctus/escape-from-castilla
b3cd17d57c5b4b19a4854eb2dd3e0ec4360dba82
[ "Unlicense" ]
null
null
null
app/src/main/java/com/nntc/escapefromcastilla/ui/GameActivity.java
F1uctus/escape-from-castilla
b3cd17d57c5b4b19a4854eb2dd3e0ec4360dba82
[ "Unlicense" ]
null
null
null
app/src/main/java/com/nntc/escapefromcastilla/ui/GameActivity.java
F1uctus/escape-from-castilla
b3cd17d57c5b4b19a4854eb2dd3e0ec4360dba82
[ "Unlicense" ]
null
null
null
34.606299
97
0.593857
9,157
package com.nntc.escapefromcastilla.ui; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import androidx.preference.PreferenceManager; import com.crown.i18n.I18n; import com.crown.i18n.ITemplate; import com.crown.items.InventoryItem; import com.crown.time.Timeline; import com.crown.time.VirtualClock; import com.nntc.escapefromcastilla.Actor; import com.nntc.escapefromcastilla.GameState; import com.nntc.escapefromcastilla.R; import com.nntc.escapefromcastilla.creatures.Human; import com.nntc.escapefromcastilla.maps.GlobalMap; import com.nntc.escapefromcastilla.maps.MapLevel; import com.nntc.escapefromcastilla.objects.items.Score; import io.github.controlwear.virtual.joystick.android.JoystickView; import static com.nntc.escapefromcastilla.ui.MainActivity.locale; public class GameActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] controllers = getResources().getStringArray(R.array.moveControls); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String moveController = sharedPref.getString("moveController", controllers[0]); if (moveController.equals(controllers[0])) { setContentView(R.layout.activity_game_joystick); ((JoystickView) findViewById(R.id.joystick)).setOnMoveListener((angle, strength) -> { if (strength > 40) { ITemplate result; if (angle <= 225 && angle >= 135) { // left result = Actor.get().moveBy(-1, 0); } else if (angle < 135 && angle >= 45) { // up result = Actor.get().moveBy(0, -1); } else if (angle <= 315 && angle > 225) { // down result = Actor.get().moveBy(0, 1); } else { // right result = Actor.get().moveBy(1, 0); } setStatusMessage(result); } }, 150); } else if (moveController.equals(controllers[1])) { setContentView(R.layout.activity_game_arrows); } Log.d("Global map", "Initializing..."); int mapSize = getMapSize(); GlobalMap map = new GlobalMap("Global map", mapSize, mapSize, MapLevel.height); Log.d("Global map", "OK"); Log.d("Game state", "Initializing..."); GameState gameState = new GameState(this, map); Log.d("Game state", "OK"); Log.d("Main timeline", "Initializing..."); Timeline.init( new VirtualClock(1000, () -> { }).startAtRnd(), gameState ); Log.d("Main timeline", "OK"); gameState.addPlayer("Runner"); Actor.pick("Runner"); } public void setStatusMessage(ITemplate message) { if (message == I18n.okMessage) { message = I18n.empty; } if (Actor.get() != null) { Human player = Actor.get(); int count = 0; for (InventoryItem item : player.getInventory()) { if (item instanceof Score) { count++; } } ((TextView) findViewById(R.id.coins_counter)).setText(String.valueOf(count)); } ((TextView) findViewById(R.id.status)).setText(message.getLocalized(locale)); } public int getMapSize() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); return prefs.getInt("mapSize", 21); } public void onUpClick(View view) { ITemplate result = Actor.get().moveBy(0, -1); setStatusMessage(result); } public void onLeftClick(View view) { ITemplate result = Actor.get().moveBy(-1, 0); setStatusMessage(result); } public void onRightClick(View view) { ITemplate result = Actor.get().moveBy(1, 0); setStatusMessage(result); } public void onDownClick(View view) { ITemplate result = Actor.get().moveBy(0, 1); setStatusMessage(result); } }
3e158b4d467013019557306f951471aee2b4956b
4,434
java
Java
src/main/java/org/jboss/threads/JBossScheduledThreadPoolExecutor.java
Sanne/jboss-threads
2609ba1e7b557f0e469c0cc85d2be5dcef98b8ca
[ "Apache-2.0" ]
11
2017-04-05T19:15:32.000Z
2022-02-14T23:56:11.000Z
src/main/java/org/jboss/threads/JBossScheduledThreadPoolExecutor.java
Sanne/jboss-threads
2609ba1e7b557f0e469c0cc85d2be5dcef98b8ca
[ "Apache-2.0" ]
44
2015-09-23T09:57:53.000Z
2022-03-07T09:41:36.000Z
src/main/java/org/jboss/threads/JBossScheduledThreadPoolExecutor.java
Sanne/jboss-threads
2609ba1e7b557f0e469c0cc85d2be5dcef98b8ca
[ "Apache-2.0" ]
32
2015-04-14T20:07:02.000Z
2022-03-07T09:39:08.000Z
34.640625
158
0.723951
9,158
/* * JBoss, Home of Professional Open Source. * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.threads; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public final class JBossScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor { private final AtomicInteger rejectCount = new AtomicInteger(); private final Runnable terminationTask; public JBossScheduledThreadPoolExecutor(int corePoolSize, final Runnable terminationTask) { super(corePoolSize); this.terminationTask = terminationTask; setRejectedExecutionHandler(super.getRejectedExecutionHandler()); } public JBossScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, final Runnable terminationTask) { super(corePoolSize, threadFactory); this.terminationTask = terminationTask; setRejectedExecutionHandler(super.getRejectedExecutionHandler()); } public JBossScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler, final Runnable terminationTask) { super(corePoolSize); this.terminationTask = terminationTask; setRejectedExecutionHandler(handler); } public JBossScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler, final Runnable terminationTask) { super(corePoolSize, threadFactory); this.terminationTask = terminationTask; setRejectedExecutionHandler(handler); } public long getKeepAliveTime() { return getKeepAliveTime(TimeUnit.MILLISECONDS); } public void setKeepAliveTime(final long milliseconds) { super.setKeepAliveTime(milliseconds, TimeUnit.MILLISECONDS); super.allowCoreThreadTimeOut(milliseconds < Long.MAX_VALUE); } public void setKeepAliveTime(final long time, final TimeUnit unit) { super.setKeepAliveTime(time, unit); super.allowCoreThreadTimeOut(time < Long.MAX_VALUE); } public int getRejectedCount() { return rejectCount.get(); } public int getCurrentThreadCount() { return getActiveCount(); } public int getLargestThreadCount() { return getLargestPoolSize(); } public int getMaxThreads() { return getCorePoolSize(); } public void setMaxThreads(final int newSize) { setCorePoolSize(newSize); } public RejectedExecutionHandler getRejectedExecutionHandler() { return ((CountingRejectHandler)super.getRejectedExecutionHandler()).getDelegate(); } public void setRejectedExecutionHandler(final RejectedExecutionHandler handler) { super.setRejectedExecutionHandler(new CountingRejectHandler(handler)); } /** {@inheritDoc} */ public int getQueueSize() { return this.getQueue().size(); } protected void terminated() { terminationTask.run(); } private final class CountingRejectHandler implements RejectedExecutionHandler { private final RejectedExecutionHandler delegate; public CountingRejectHandler(final RejectedExecutionHandler delegate) { this.delegate = delegate; } public RejectedExecutionHandler getDelegate() { return delegate; } public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) { rejectCount.incrementAndGet(); if (isShutdown()) { throw Messages.msg.shutDownInitiated(); } delegate.rejectedExecution(r, executor); } } }
3e158d5da266859529bc00d04d9dfad8675dc13b
3,378
java
Java
aa-service/src/main/java/com/boe/service/PunchCardService.java
zx4ever/happyCode
2f36f210265f468a46809e618c9b674a860b64f6
[ "Apache-2.0" ]
null
null
null
aa-service/src/main/java/com/boe/service/PunchCardService.java
zx4ever/happyCode
2f36f210265f468a46809e618c9b674a860b64f6
[ "Apache-2.0" ]
null
null
null
aa-service/src/main/java/com/boe/service/PunchCardService.java
zx4ever/happyCode
2f36f210265f468a46809e618c9b674a860b64f6
[ "Apache-2.0" ]
null
null
null
29.373913
117
0.66489
9,159
package com.boe.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.boe.dao.AdjustingDao; import com.boe.dao.PunchCardDao; import com.boe.entity.Adjusting; import com.boe.entity.PunchCard; import com.boe.util.ContinueTime; import com.boe.util.MathRandom; import com.boe.util.TimeFormat; @Service public class PunchCardService{ @Autowired private PunchCardDao punchCardDao; @Autowired private AdjustingDao adjustingDao; public List<PunchCard> getData(long userId) { List<PunchCard> list = punchCardDao.selectData(userId); return list; } public String punch(PunchCard params,Date time) { String now = TimeFormat.format(new Date()); List<Date> dateList = new ArrayList<Date>(); Map<String,String> term = punchCardDao.getWords(1); Map<String, Integer> map = punchCardDao.getXY(params.getUserId()); int flag= punchCardDao.getObj(params.getUserId(), params.getDate());//判断是否有数据 int counts = 0 ; String word1 = term.get("word1"); String word2 = term.get("word2"); String[] strs = word1.split(";"); String[] str2 = word2.split(";"); if(flag == 1) { punchCardDao.updateData(params); }else { params.setState("1"); punchCardDao.insterData(params); } List<PunchCard> punchData = punchCardDao.selectData(params.getUserId()); int days = punchData.size(); for (PunchCard punchCard : punchData) { counts+=punchCard.getCount(); dateList.add(punchCard.getDate()); } double r = counts/(8*days); Adjusting adjusting = adjustingDao.selectData(params.getUserId()); int n1 = adjustingDao.getFrequency(params.getUserId(),r); int n2 = adjustingDao.getSum(params.getUserId()); int z =n1/(n2)*100; if(adjusting==null) { adjusting.setState("1"); adjusting.setR(r); adjusting.setUserId(params.getUserId()); adjusting.setTimes(counts); adjustingDao.insertData(adjusting); }else { adjusting.setR(r); adjusting.setTimes(counts); adjustingDao.updateDate(adjusting); } String newWords =strs[0].replaceAll("X", days+"")+strs[0].replaceAll("Y", counts+"")+strs[0].replaceAll("Z",z+""); //连续时间 int continueTimes = ContinueTime.getContinueTime(dateList); if(0 <= days && days <= 15) { if(continueTimes>=3) { int random = MathRandom.random(0,1); return newWords+str2[random]; }else { int random = MathRandom.random(2,4); return newWords+str2[random]; } } if(15 < days && days <= 30) { if(continueTimes>=3) { int random = MathRandom.random(5,6); return newWords+str2[random]; }else { int random = MathRandom.random(7,8); return newWords+str2[random]; } } if(30 < days && days <= 60) { return newWords+strs[strs.length]; } if(60 < days ) { return strs[1]; } //判断时间是否为当前时间 if(now.equals(time)) { //判断是添加还是修改 if(map != null) { Map<String,String> term2 = punchCardDao.getWords(2); String str3 = term2.get("word1"); String newWords2 =str3.replaceAll("X", days+"")+str3.replaceAll("Y", counts+"")+str3.replaceAll("Z",z+""); return newWords2; }else { punchCardDao.insterData(params); } } return null; } }
3e158d97ae09fe977bec23cf19bce3defa5b40e9
826
java
Java
archive/FILE/Compiler/bpwj-java-phrase/code/sjm/imperative/NullCommand.java
nileshpatelksy/hello-pod-cast
a2efa652735687ece13fd4297ceb0891289dc10b
[ "Apache-2.0" ]
null
null
null
archive/FILE/Compiler/bpwj-java-phrase/code/sjm/imperative/NullCommand.java
nileshpatelksy/hello-pod-cast
a2efa652735687ece13fd4297ceb0891289dc10b
[ "Apache-2.0" ]
null
null
null
archive/FILE/Compiler/bpwj-java-phrase/code/sjm/imperative/NullCommand.java
nileshpatelksy/hello-pod-cast
a2efa652735687ece13fd4297ceb0891289dc10b
[ "Apache-2.0" ]
null
null
null
22.944444
62
0.668281
9,160
package sjm.imperative; /* * Copyright (c) 2000 Steven J. Metsker. All Rights Reserved. * * Steve Metsker makes no representations or warranties about * the fitness of this software for any particular purpose, * including the implied warranty of merchantability. */ /** * This command does nothing, which can simplify coding * in some cases. For example, an "if" command with no * given "else" uses a <code>NullCommand</code> for its else * command. * * @author Steven J. Metsker * * @version 1.0 */ public class NullCommand extends Command { /** * Does nothing. */ public void execute() { } /** * Returns a string description of this null command. * * @return a string description of this null command */ public String toString() { return "NullCommand"; } }
3e158ea5522f13b180e22a07366bd66864ceed8f
2,375
java
Java
src/main/java/uk/ac/ed/epcc/webapp/model/data/forms/CheckboxSelector.java
spbooth/SAFE-WEBAPP
2b8fec968df4f5b9146e3f856a52e2393f5be2d1
[ "Apache-2.0" ]
3
2017-03-02T14:05:51.000Z
2021-07-15T09:14:48.000Z
src/main/java/uk/ac/ed/epcc/webapp/model/data/forms/CheckboxSelector.java
spbooth/SAFE-WEBAPP
2b8fec968df4f5b9146e3f856a52e2393f5be2d1
[ "Apache-2.0" ]
null
null
null
src/main/java/uk/ac/ed/epcc/webapp/model/data/forms/CheckboxSelector.java
spbooth/SAFE-WEBAPP
2b8fec968df4f5b9146e3f856a52e2393f5be2d1
[ "Apache-2.0" ]
null
null
null
32.986111
81
0.541053
9,161
//| Copyright - The University of Edinburgh 2011 | //| | //| 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. | /******************************************************************************* * Copyright (c) - The University of Edinburgh 2010 *******************************************************************************/ /* * Created on Nov 3, 2004 by spb * */ package uk.ac.ed.epcc.webapp.model.data.forms; import uk.ac.ed.epcc.webapp.forms.inputs.CheckBoxInput; import uk.ac.ed.epcc.webapp.forms.inputs.Input; /** * CheckboxSelector Generates a checkbox selector for DataObject edit forms * * @author spb * */ public class CheckboxSelector implements Selector<CheckBoxInput> { String checked_tag; String unchecked_tag; /** * Default constructor for Y/N tags * * */ public CheckboxSelector() { this("Y", "N"); } /** * create a selector with customised tags. * * Note this can only be used to represent a boolean if the checked tag * auto-converts to boolean true * * @param checked_tag * the String value corresponding to a checked box * @param unchecked_tag * the String value corresponding to a unchecked box * * */ public CheckboxSelector(String checked_tag, String unchecked_tag) { super(); this.checked_tag = checked_tag; this.unchecked_tag = unchecked_tag; } @Override public CheckBoxInput getInput() { return new CheckBoxInput(checked_tag, unchecked_tag); } }
3e158fb41da962cde68add22efc5526cc4a9de9a
300
java
Java
config-wrapper/src/main/java/com/u6f6o/apps/cfgw/ConfigLogger.java
u6f6o/config-mgmt-eval
e801d1fa0cd51e23cd44932c7677a559079dcddf
[ "MIT" ]
null
null
null
config-wrapper/src/main/java/com/u6f6o/apps/cfgw/ConfigLogger.java
u6f6o/config-mgmt-eval
e801d1fa0cd51e23cd44932c7677a559079dcddf
[ "MIT" ]
null
null
null
config-wrapper/src/main/java/com/u6f6o/apps/cfgw/ConfigLogger.java
u6f6o/config-mgmt-eval
e801d1fa0cd51e23cd44932c7677a559079dcddf
[ "MIT" ]
null
null
null
27.272727
100
0.79
9,162
package com.u6f6o.apps.cfgw; import com.google.common.collect.ImmutableMap; import java.util.Map; public interface ConfigLogger { void logOnUpdate(ImmutableMap<String, String> cachedConfig, Map<String, String> upToDateConfig); void logOnInit(ImmutableMap<String, String> initialConfig); }
3e15900c5a9369fee27520e0af194ed10a383e31
10,702
java
Java
presto-redis/src/main/java/com/facebook/presto/redis/RedisMetadata.java
ahouzheng/presto
c2ac1469eea9da9c6e29c8c4d43e00b851400c8b
[ "Apache-2.0" ]
9,782
2016-03-18T15:16:19.000Z
2022-03-31T07:49:41.000Z
presto-redis/src/main/java/com/facebook/presto/redis/RedisMetadata.java
ahouzheng/presto
c2ac1469eea9da9c6e29c8c4d43e00b851400c8b
[ "Apache-2.0" ]
10,310
2016-03-18T01:03:00.000Z
2022-03-31T23:54:08.000Z
presto-redis/src/main/java/com/facebook/presto/redis/RedisMetadata.java
ahouzheng/presto
c2ac1469eea9da9c6e29c8c4d43e00b851400c8b
[ "Apache-2.0" ]
3,803
2016-03-18T22:54:24.000Z
2022-03-31T07:49:46.000Z
38.496403
130
0.697346
9,163
/* * 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.facebook.presto.redis; import com.facebook.airlift.log.Logger; import com.facebook.presto.decoder.dummy.DummyRowDecoder; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableLayout; import com.facebook.presto.spi.ConnectorTableLayoutHandle; import com.facebook.presto.spi.ConnectorTableLayoutResult; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.TableNotFoundException; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import javax.inject.Inject; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import static com.facebook.presto.redis.RedisHandleResolver.convertColumnHandle; import static com.facebook.presto.redis.RedisHandleResolver.convertLayout; import static com.facebook.presto.redis.RedisHandleResolver.convertTableHandle; import static java.util.Objects.requireNonNull; /** * Manages the Redis connector specific metadata information. The Connector provides an additional set of columns * for each table that are created as hidden columns. See {@link RedisInternalFieldDescription} for a list * of additional columns. */ public class RedisMetadata implements ConnectorMetadata { private static final Logger log = Logger.get(RedisMetadata.class); private final String connectorId; private final boolean hideInternalColumns; private final Supplier<Map<SchemaTableName, RedisTableDescription>> redisTableDescriptionSupplier; @Inject RedisMetadata( RedisConnectorId connectorId, RedisConnectorConfig redisConnectorConfig, Supplier<Map<SchemaTableName, RedisTableDescription>> redisTableDescriptionSupplier) { this.connectorId = requireNonNull(connectorId, "connectorId is null").toString(); requireNonNull(redisConnectorConfig, "redisConfig is null"); hideInternalColumns = redisConnectorConfig.isHideInternalColumns(); log.debug("Loading redis table definitions from %s", redisConnectorConfig.getTableDescriptionDir().getAbsolutePath()); this.redisTableDescriptionSupplier = Suppliers.memoize(redisTableDescriptionSupplier::get)::get; } @Override public List<String> listSchemaNames(ConnectorSession session) { Set<String> schemas = getDefinedTables().keySet().stream() .map(SchemaTableName::getSchemaName) .collect(Collectors.toCollection(LinkedHashSet::new)); return ImmutableList.copyOf(schemas); } @Override public RedisTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName) { RedisTableDescription table = getDefinedTables().get(schemaTableName); if (table == null) { return null; } // check if keys are supplied in a zset // via the table description doc String keyName = null; if (table.getKey() != null) { keyName = table.getKey().getName(); } return new RedisTableHandle( connectorId, schemaTableName.getSchemaName(), schemaTableName.getTableName(), getDataFormat(table.getKey()), getDataFormat(table.getValue()), keyName); } private static String getDataFormat(RedisTableFieldGroup fieldGroup) { return (fieldGroup == null) ? DummyRowDecoder.NAME : fieldGroup.getDataFormat(); } @Override public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle tableHandle) { return getTableMetadata(convertTableHandle(tableHandle).toSchemaTableName()); } @Override public List<ConnectorTableLayoutResult> getTableLayouts( ConnectorSession session, ConnectorTableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { RedisTableHandle tableHandle = convertTableHandle(table); ConnectorTableLayout layout = new ConnectorTableLayout(new RedisTableLayoutHandle(tableHandle)); return ImmutableList.of(new ConnectorTableLayoutResult(layout, constraint.getSummary())); } @Override public ConnectorTableLayout getTableLayout(ConnectorSession session, ConnectorTableLayoutHandle handle) { RedisTableLayoutHandle layout = convertLayout(handle); // tables in this connector have a single layout return getTableLayouts(session, layout.getTable(), Constraint.alwaysTrue(), Optional.empty()) .get(0) .getTableLayout(); } @Override public List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull) { ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder(); for (SchemaTableName tableName : getDefinedTables().keySet()) { if (schemaNameOrNull == null || tableName.getSchemaName().equals(schemaNameOrNull)) { builder.add(tableName); } } return builder.build(); } @Override public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) { RedisTableHandle redisTableHandle = convertTableHandle(tableHandle); RedisTableDescription redisTableDescription = getDefinedTables().get(redisTableHandle.toSchemaTableName()); if (redisTableDescription == null) { throw new TableNotFoundException(redisTableHandle.toSchemaTableName()); } ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder(); int index = 0; RedisTableFieldGroup key = redisTableDescription.getKey(); if (key != null) { List<RedisTableFieldDescription> fields = key.getFields(); if (fields != null) { for (RedisTableFieldDescription field : fields) { columnHandles.put(field.getName(), field.getColumnHandle(connectorId, true, index)); index++; } } } RedisTableFieldGroup value = redisTableDescription.getValue(); if (value != null) { List<RedisTableFieldDescription> fields = value.getFields(); if (fields != null) { for (RedisTableFieldDescription field : fields) { columnHandles.put(field.getName(), field.getColumnHandle(connectorId, false, index)); index++; } } } for (RedisInternalFieldDescription field : RedisInternalFieldDescription.values()) { columnHandles.put(field.getColumnName(), field.getColumnHandle(connectorId, index, hideInternalColumns)); index++; } return columnHandles.build(); } @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { requireNonNull(prefix, "prefix is null"); ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); List<SchemaTableName> tableNames; if (prefix.getTableName() == null) { tableNames = listTables(session, prefix.getSchemaName()); } else { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } for (SchemaTableName tableName : tableNames) { ConnectorTableMetadata tableMetadata = getTableMetadata(tableName); // table can disappear during listing operation if (tableMetadata != null) { columns.put(tableName, tableMetadata.getColumns()); } } return columns.build(); } @Override public ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle) { convertTableHandle(tableHandle); return convertColumnHandle(columnHandle).getColumnMetadata(); } @VisibleForTesting Map<SchemaTableName, RedisTableDescription> getDefinedTables() { return redisTableDescriptionSupplier.get(); } @SuppressWarnings("ValueOfIncrementOrDecrementUsed") private ConnectorTableMetadata getTableMetadata(SchemaTableName schemaTableName) { RedisTableDescription table = getDefinedTables().get(schemaTableName); if (table == null) { throw new TableNotFoundException(schemaTableName); } ImmutableList.Builder<ColumnMetadata> builder = ImmutableList.builder(); appendFields(builder, table.getKey()); appendFields(builder, table.getValue()); for (RedisInternalFieldDescription fieldDescription : RedisInternalFieldDescription.values()) { builder.add(fieldDescription.getColumnMetadata(hideInternalColumns)); } return new ConnectorTableMetadata(schemaTableName, builder.build()); } private static void appendFields(ImmutableList.Builder<ColumnMetadata> builder, RedisTableFieldGroup group) { if (group != null) { List<RedisTableFieldDescription> fields = group.getFields(); if (fields != null) { for (RedisTableFieldDescription fieldDescription : fields) { builder.add(fieldDescription.getColumnMetadata()); } } } } }
3e15900f91914d1718ed8ae618437d3cd1ad17ee
3,959
java
Java
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/CopyExecutionStateStep.java
findohsset/elasticsearch
a0662399c7ea855165ffdfab7864a16a5207e0db
[ "Apache-2.0" ]
1
2020-03-31T20:15:40.000Z
2020-03-31T20:15:40.000Z
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/CopyExecutionStateStep.java
findohsset/elasticsearch
a0662399c7ea855165ffdfab7864a16a5207e0db
[ "Apache-2.0" ]
1
2020-04-03T13:52:30.000Z
2020-04-03T13:52:30.000Z
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/CopyExecutionStateStep.java
findohsset/elasticsearch
a0662399c7ea855165ffdfab7864a16a5207e0db
[ "Apache-2.0" ]
1
2017-10-07T20:54:39.000Z
2017-10-07T20:54:39.000Z
42.117021
140
0.713817
9,164
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.ilm; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.index.Index; import java.util.Objects; import static org.elasticsearch.xpack.core.ilm.LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY; /** * Copies the execution state data from one index to another, typically after a * new index has been created. Useful for actions such as shrink. */ public class CopyExecutionStateStep extends ClusterStateActionStep { public static final String NAME = "copy-execution-state"; private static final Logger logger = LogManager.getLogger(CopyExecutionStateStep.class); private String shrunkIndexPrefix; public CopyExecutionStateStep(StepKey key, StepKey nextStepKey, String shrunkIndexPrefix) { super(key, nextStepKey); this.shrunkIndexPrefix = shrunkIndexPrefix; } String getShrunkIndexPrefix() { return shrunkIndexPrefix; } @Override public ClusterState performAction(Index index, ClusterState clusterState) { IndexMetadata indexMetadata = clusterState.metadata().index(index); if (indexMetadata == null) { // Index must have been since deleted, ignore it logger.debug("[{}] lifecycle action for index [{}] executed but index no longer exists", getKey().getAction(), index.getName()); return clusterState; } // get source index String indexName = indexMetadata.getIndex().getName(); // get target shrink index String targetIndexName = shrunkIndexPrefix + indexName; IndexMetadata targetIndexMetadata = clusterState.metadata().index(targetIndexName); if (targetIndexMetadata == null) { logger.warn("[{}] index [{}] unable to copy execution state to target index [{}] as target index does not exist", getKey().getAction(), index.getName(), targetIndexName); throw new IllegalStateException("unable to copy execution state from [" + index.getName() + "] to [" + targetIndexName + "] as target index does not exist"); } LifecycleExecutionState lifecycleState = LifecycleExecutionState.fromIndexMetadata(indexMetadata); String phase = lifecycleState.getPhase(); String action = lifecycleState.getAction(); long lifecycleDate = lifecycleState.getLifecycleDate(); LifecycleExecutionState.Builder relevantTargetCustomData = LifecycleExecutionState.builder(); relevantTargetCustomData.setIndexCreationDate(lifecycleDate); relevantTargetCustomData.setPhase(phase); relevantTargetCustomData.setAction(action); relevantTargetCustomData.setStep(ShrunkenIndexCheckStep.NAME); Metadata.Builder newMetadata = Metadata.builder(clusterState.getMetadata()) .put(IndexMetadata.builder(targetIndexMetadata) .putCustom(ILM_CUSTOM_METADATA_KEY, relevantTargetCustomData.build().asMap())); return ClusterState.builder(clusterState).metadata(newMetadata).build(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; CopyExecutionStateStep that = (CopyExecutionStateStep) o; return Objects.equals(shrunkIndexPrefix, that.shrunkIndexPrefix); } @Override public int hashCode() { return Objects.hash(super.hashCode(), shrunkIndexPrefix); } }
3e1590c2bb69bd9069243471ca26920596322c18
1,828
java
Java
sabot/kernel/src/main/java/com/dremio/aws/SharedInstanceProfileCredentialsProvider.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
1,085
2017-07-19T15:08:38.000Z
2022-03-29T13:35:07.000Z
sabot/kernel/src/main/java/com/dremio/aws/SharedInstanceProfileCredentialsProvider.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
20
2017-07-19T20:16:27.000Z
2021-12-02T10:56:25.000Z
sabot/kernel/src/main/java/com/dremio/aws/SharedInstanceProfileCredentialsProvider.java
geetek/dremio-oss
812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2
[ "Apache-2.0" ]
398
2017-07-19T18:12:58.000Z
2022-03-30T09:37:40.000Z
41.545455
103
0.78337
9,165
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.aws; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider; /** * A shared instance of {@link InstanceProfileCredentialsProvider} to avoid creating too * many instances at once and sending too many queries to the metadata server. */ public class SharedInstanceProfileCredentialsProvider implements AwsCredentialsProvider { // Internal instance holder to lazy create the singleton // Singleton pattern was chosen as InstanceProfileCredentialsProvider automatically handles periodic // refresh of credentials so the number of HTTP requests to the metadata server are quite limited private static final class Holder { // This instance should be closed once unused but since its lifetime is bound to the jvm, nothing // special is done. private static final AwsCredentialsProvider INSTANCE = InstanceProfileCredentialsProvider.create(); } public SharedInstanceProfileCredentialsProvider() { } @Override public AwsCredentials resolveCredentials() { return Holder.INSTANCE.resolveCredentials(); } }
3e1592c53c304ea7a69a04ddba768a3f01417ca3
1,600
java
Java
src/test/java/AppTest.java
SummerBr/restaurant-ranking
febb4047d09eb740fa6a6c524769f8d1863e5942
[ "MIT", "Unlicense" ]
null
null
null
src/test/java/AppTest.java
SummerBr/restaurant-ranking
febb4047d09eb740fa6a6c524769f8d1863e5942
[ "MIT", "Unlicense" ]
null
null
null
src/test/java/AppTest.java
SummerBr/restaurant-ranking
febb4047d09eb740fa6a6c524769f8d1863e5942
[ "MIT", "Unlicense" ]
null
null
null
30.188679
90
0.72375
9,166
import org.fluentlenium.adapter.FluentTest; import static org.junit.Assert.*; import org.junit.*; import org.junit.ClassRule; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static org.fluentlenium.core.filter.FilterConstructor.*; import static org.assertj.core.api.Assertions.assertThat; public class AppTest extends FluentTest { public WebDriver webDriver = new HtmlUnitDriver(); @Override public WebDriver getDefaultDriver() { return webDriver; } @ClassRule public static ServerRule server = new ServerRule(); @Test public void rootTest() { goTo("http://localhost:4567/"); assertThat(pageSource()).contains("Discover Portland's Food Carts"); } @Test public void newRestaurantAddedToMainPage() { Cuisine japanese = new Cuisine("Japanese"); japanese.save(); Restaurant newRestaurant = new Restaurant ("Momo", japanese.getCuisineId(), "$$$"); newRestaurant.save(); String path = "http://localhost:4567/restaurants"; goTo(path); assertThat(pageSource()).contains("Momo"); } @Test public void deleteRestaurantById_removesRestaurant() { Cuisine american = new Cuisine("American"); american.save(); Restaurant newRestaurant = new Restaurant("Summer", american.getCuisineId(), "$"); newRestaurant.save(); newRestaurant.deleteRestaurantById(newRestaurant.getId()); String path = String.format("http://localhost:4567/delete/%d", newRestaurant.getId()); goTo(path); assertEquals(false, pageSource().contains("Summer")); } }
3e159307fcdf3879338d2bbf3ee3f21e5429a377
14,460
java
Java
exporters/otlp/common/src/main/java/io/opentelemetry/exporter/otlp/internal/MetricAdapter.java
chenyi19851209/opentelemetry-java
9fa98de1cbf0a5bfca139ad0cf347e808058bf35
[ "Apache-2.0" ]
null
null
null
exporters/otlp/common/src/main/java/io/opentelemetry/exporter/otlp/internal/MetricAdapter.java
chenyi19851209/opentelemetry-java
9fa98de1cbf0a5bfca139ad0cf347e808058bf35
[ "Apache-2.0" ]
null
null
null
exporters/otlp/common/src/main/java/io/opentelemetry/exporter/otlp/internal/MetricAdapter.java
chenyi19851209/opentelemetry-java
9fa98de1cbf0a5bfca139ad0cf347e808058bf35
[ "Apache-2.0" ]
null
null
null
43.423423
107
0.710373
9,167
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.exporter.otlp.internal; import static io.opentelemetry.proto.metrics.v1.AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE; import static io.opentelemetry.proto.metrics.v1.AggregationTemporality.AGGREGATION_TEMPORALITY_DELTA; import static io.opentelemetry.proto.metrics.v1.AggregationTemporality.AGGREGATION_TEMPORALITY_UNSPECIFIED; import com.google.protobuf.ByteString; import com.google.protobuf.UnsafeByteOperations; import io.opentelemetry.api.internal.OtelEncodingUtils; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.proto.metrics.v1.AggregationTemporality; import io.opentelemetry.proto.metrics.v1.Exemplar; import io.opentelemetry.proto.metrics.v1.Gauge; import io.opentelemetry.proto.metrics.v1.Histogram; import io.opentelemetry.proto.metrics.v1.HistogramDataPoint; import io.opentelemetry.proto.metrics.v1.InstrumentationLibraryMetrics; import io.opentelemetry.proto.metrics.v1.Metric; import io.opentelemetry.proto.metrics.v1.NumberDataPoint; import io.opentelemetry.proto.metrics.v1.ResourceMetrics; import io.opentelemetry.proto.metrics.v1.Sum; import io.opentelemetry.proto.metrics.v1.Summary; import io.opentelemetry.proto.metrics.v1.SummaryDataPoint; import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.data.DoubleExemplar; import io.opentelemetry.sdk.metrics.data.DoubleGaugeData; import io.opentelemetry.sdk.metrics.data.DoubleHistogramData; import io.opentelemetry.sdk.metrics.data.DoubleHistogramPointData; import io.opentelemetry.sdk.metrics.data.DoublePointData; import io.opentelemetry.sdk.metrics.data.DoubleSumData; import io.opentelemetry.sdk.metrics.data.DoubleSummaryData; import io.opentelemetry.sdk.metrics.data.DoubleSummaryPointData; import io.opentelemetry.sdk.metrics.data.LongExemplar; import io.opentelemetry.sdk.metrics.data.LongGaugeData; import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.LongSumData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.data.ValueAtPercentile; import io.opentelemetry.sdk.resources.Resource; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** Converter from SDK {@link MetricData} to OTLP {@link ResourceMetrics}. */ public final class MetricAdapter { private static final ThrottlingLogger logger = new ThrottlingLogger(Logger.getLogger(MetricAdapter.class.getName())); /** Converts the provided {@link MetricData} to {@link ResourceMetrics}. */ public static List<ResourceMetrics> toProtoResourceMetrics(Collection<MetricData> metricData) { Map<Resource, Map<InstrumentationLibraryInfo, List<Metric>>> resourceAndLibraryMap = groupByResourceAndLibrary(metricData); List<ResourceMetrics> resourceMetrics = new ArrayList<>(resourceAndLibraryMap.size()); for (Map.Entry<Resource, Map<InstrumentationLibraryInfo, List<Metric>>> entryResource : resourceAndLibraryMap.entrySet()) { List<InstrumentationLibraryMetrics> instrumentationLibraryMetrics = new ArrayList<>(entryResource.getValue().size()); for (Map.Entry<InstrumentationLibraryInfo, List<Metric>> entryLibrary : entryResource.getValue().entrySet()) { instrumentationLibraryMetrics.add(buildInstrumentationLibraryMetrics(entryLibrary)); } resourceMetrics.add( buildResourceMetrics(entryResource.getKey(), instrumentationLibraryMetrics)); } return resourceMetrics; } private static ResourceMetrics buildResourceMetrics( Resource resource, List<InstrumentationLibraryMetrics> instrumentationLibraryMetrics) { ResourceMetrics.Builder resourceMetricsBuilder = ResourceMetrics.newBuilder() .setResource(ResourceAdapter.toProtoResource(resource)) .addAllInstrumentationLibraryMetrics(instrumentationLibraryMetrics); String schemaUrl = resource.getSchemaUrl(); if (schemaUrl != null) { resourceMetricsBuilder.setSchemaUrl(schemaUrl); } return resourceMetricsBuilder.build(); } private static InstrumentationLibraryMetrics buildInstrumentationLibraryMetrics( Map.Entry<InstrumentationLibraryInfo, List<Metric>> entryLibrary) { InstrumentationLibraryMetrics.Builder metricsBuilder = InstrumentationLibraryMetrics.newBuilder() .setInstrumentationLibrary( CommonAdapter.toProtoInstrumentationLibrary(entryLibrary.getKey())) .addAllMetrics(entryLibrary.getValue()); if (entryLibrary.getKey().getSchemaUrl() != null) { metricsBuilder.setSchemaUrl(entryLibrary.getKey().getSchemaUrl()); } return metricsBuilder.build(); } private static Map<Resource, Map<InstrumentationLibraryInfo, List<Metric>>> groupByResourceAndLibrary(Collection<MetricData> metricDataList) { Map<Resource, Map<InstrumentationLibraryInfo, List<Metric>>> result = new HashMap<>(); for (MetricData metricData : metricDataList) { if (metricData.isEmpty()) { // If no points available then ignore. continue; } Resource resource = metricData.getResource(); Map<InstrumentationLibraryInfo, List<Metric>> libraryInfoListMap = result.get(metricData.getResource()); if (libraryInfoListMap == null) { libraryInfoListMap = new HashMap<>(); result.put(resource, libraryInfoListMap); } List<Metric> metricList = libraryInfoListMap.computeIfAbsent( metricData.getInstrumentationLibraryInfo(), k -> new ArrayList<>()); metricList.add(toProtoMetric(metricData)); } return result; } // fall through comment isn't working for some reason. @SuppressWarnings("fallthrough") static Metric toProtoMetric(MetricData metricData) { Metric.Builder builder = Metric.newBuilder() .setName(metricData.getName()) .setDescription(metricData.getDescription()) .setUnit(metricData.getUnit()); switch (metricData.getType()) { case LONG_SUM: LongSumData longSumData = metricData.getLongSumData(); builder.setSum( Sum.newBuilder() .setIsMonotonic(longSumData.isMonotonic()) .setAggregationTemporality( mapToTemporality(longSumData.getAggregationTemporality())) .addAllDataPoints(toIntDataPoints(longSumData.getPoints())) .build()); break; case DOUBLE_SUM: DoubleSumData doubleSumData = metricData.getDoubleSumData(); builder.setSum( Sum.newBuilder() .setIsMonotonic(doubleSumData.isMonotonic()) .setAggregationTemporality( mapToTemporality(doubleSumData.getAggregationTemporality())) .addAllDataPoints(toDoubleDataPoints(doubleSumData.getPoints())) .build()); break; case SUMMARY: DoubleSummaryData doubleSummaryData = metricData.getDoubleSummaryData(); builder.setSummary( Summary.newBuilder() .addAllDataPoints(toSummaryDataPoints(doubleSummaryData.getPoints())) .build()); break; case LONG_GAUGE: LongGaugeData longGaugeData = metricData.getLongGaugeData(); builder.setGauge( Gauge.newBuilder() .addAllDataPoints(toIntDataPoints(longGaugeData.getPoints())) .build()); break; case DOUBLE_GAUGE: DoubleGaugeData doubleGaugeData = metricData.getDoubleGaugeData(); builder.setGauge( Gauge.newBuilder() .addAllDataPoints(toDoubleDataPoints(doubleGaugeData.getPoints())) .build()); break; case HISTOGRAM: DoubleHistogramData doubleHistogramData = metricData.getDoubleHistogramData(); builder.setHistogram( Histogram.newBuilder() .setAggregationTemporality( mapToTemporality(doubleHistogramData.getAggregationTemporality())) .addAllDataPoints(toHistogramDataPoints(doubleHistogramData.getPoints())) .build()); break; } return builder.build(); } private static AggregationTemporality mapToTemporality( io.opentelemetry.sdk.metrics.data.AggregationTemporality temporality) { switch (temporality) { case CUMULATIVE: return AGGREGATION_TEMPORALITY_CUMULATIVE; case DELTA: return AGGREGATION_TEMPORALITY_DELTA; } return AGGREGATION_TEMPORALITY_UNSPECIFIED; } static List<NumberDataPoint> toIntDataPoints(Collection<LongPointData> points) { List<NumberDataPoint> result = new ArrayList<>(points.size()); for (LongPointData longPoint : points) { NumberDataPoint.Builder builder = NumberDataPoint.newBuilder() .setStartTimeUnixNano(longPoint.getStartEpochNanos()) .setTimeUnixNano(longPoint.getEpochNanos()) .setAsInt(longPoint.getValue()); longPoint .getAttributes() .forEach( (key, value) -> builder.addAttributes(CommonAdapter.toProtoAttribute(key, value))); longPoint.getExemplars().forEach(e -> builder.addExemplars(toExemplar(e))); result.add(builder.build()); } return result; } static Collection<NumberDataPoint> toDoubleDataPoints(Collection<DoublePointData> points) { List<NumberDataPoint> result = new ArrayList<>(points.size()); for (DoublePointData doublePoint : points) { NumberDataPoint.Builder builder = NumberDataPoint.newBuilder() .setStartTimeUnixNano(doublePoint.getStartEpochNanos()) .setTimeUnixNano(doublePoint.getEpochNanos()) .setAsDouble(doublePoint.getValue()); doublePoint .getAttributes() .forEach( (key, value) -> builder.addAttributes(CommonAdapter.toProtoAttribute(key, value))); doublePoint.getExemplars().forEach(e -> builder.addExemplars(toExemplar(e))); result.add(builder.build()); } return result; } static List<SummaryDataPoint> toSummaryDataPoints(Collection<DoubleSummaryPointData> points) { List<SummaryDataPoint> result = new ArrayList<>(points.size()); for (DoubleSummaryPointData doubleSummaryPoint : points) { SummaryDataPoint.Builder builder = SummaryDataPoint.newBuilder() .setStartTimeUnixNano(doubleSummaryPoint.getStartEpochNanos()) .setTimeUnixNano(doubleSummaryPoint.getEpochNanos()) .setCount(doubleSummaryPoint.getCount()) .setSum(doubleSummaryPoint.getSum()); doubleSummaryPoint .getAttributes() .forEach( (key, value) -> builder.addAttributes(CommonAdapter.toProtoAttribute(key, value))); // Not calling directly addAllQuantileValues because that generates couple of unnecessary // allocations if empty list. if (!doubleSummaryPoint.getPercentileValues().isEmpty()) { for (ValueAtPercentile valueAtPercentile : doubleSummaryPoint.getPercentileValues()) { builder.addQuantileValues( SummaryDataPoint.ValueAtQuantile.newBuilder() .setQuantile(valueAtPercentile.getPercentile() / 100.0) .setValue(valueAtPercentile.getValue()) .build()); } } result.add(builder.build()); } return result; } static Collection<HistogramDataPoint> toHistogramDataPoints( Collection<DoubleHistogramPointData> points) { List<HistogramDataPoint> result = new ArrayList<>(points.size()); for (DoubleHistogramPointData doubleHistogramPoint : points) { HistogramDataPoint.Builder builder = HistogramDataPoint.newBuilder() .setStartTimeUnixNano(doubleHistogramPoint.getStartEpochNanos()) .setTimeUnixNano(doubleHistogramPoint.getEpochNanos()) .setCount(doubleHistogramPoint.getCount()) .setSum(doubleHistogramPoint.getSum()) .addAllBucketCounts(doubleHistogramPoint.getCounts()); List<Double> boundaries = doubleHistogramPoint.getBoundaries(); if (!boundaries.isEmpty()) { builder.addAllExplicitBounds(boundaries); } doubleHistogramPoint .getAttributes() .forEach( (key, value) -> builder.addAttributes(CommonAdapter.toProtoAttribute(key, value))); doubleHistogramPoint.getExemplars().forEach(e -> builder.addExemplars(toExemplar(e))); result.add(builder.build()); } return result; } static Exemplar toExemplar(io.opentelemetry.sdk.metrics.data.Exemplar exemplar) { // TODO - Use a thread local cache for spanid/traceid -> byte conversion. Exemplar.Builder builder = Exemplar.newBuilder(); builder.setTimeUnixNano(exemplar.getEpochNanos()); if (exemplar.getSpanId() != null) { builder.setSpanId(convertSpanId(exemplar.getSpanId())); } if (exemplar.getTraceId() != null) { builder.setTraceId(convertTraceId(exemplar.getTraceId())); } exemplar .getFilteredAttributes() .forEach( (key, value) -> builder.addFilteredAttributes(CommonAdapter.toProtoAttribute(key, value))); if (exemplar instanceof LongExemplar) { builder.setAsInt(((LongExemplar) exemplar).getValue()); } else if (exemplar instanceof DoubleExemplar) { builder.setAsDouble(((DoubleExemplar) exemplar).getValue()); } else { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Unable to convert unknown exemplar type: " + exemplar); } } return builder.build(); } private static ByteString convertTraceId(String id) { return UnsafeByteOperations.unsafeWrap( OtelEncodingUtils.bytesFromBase16(id, TraceId.getLength())); } private static ByteString convertSpanId(String id) { return UnsafeByteOperations.unsafeWrap( OtelEncodingUtils.bytesFromBase16(id, SpanId.getLength())); } private MetricAdapter() {} }
3e159369018061cd7ec650e2096eb3eed69775a5
1,454
java
Java
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/security/resource/CustomTrustManager.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
841
2015-01-01T10:13:52.000Z
2021-09-17T03:41:49.000Z
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/security/resource/CustomTrustManager.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
974
2015-01-23T02:42:23.000Z
2021-09-17T03:35:22.000Z
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/security/resource/CustomTrustManager.java
iweiss/Resteasy
254e74f84806534f8a2b57cc73693428a2a9fcca
[ "Apache-2.0" ]
747
2015-01-08T22:48:05.000Z
2021-09-02T15:56:08.000Z
34.619048
123
0.777166
9,168
package org.jboss.resteasy.test.security.resource; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.security.KeyStore; import java.security.cert.CertificateException; public class CustomTrustManager implements X509TrustManager { private X509TrustManager defaultTrustManager; public CustomTrustManager(final KeyStore truststore) throws NoSuchAlgorithmException, KeyStoreException { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(truststore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); for (TrustManager trustManager : trustManagers) { if (trustManager instanceof X509TrustManager) { defaultTrustManager = (X509TrustManager) trustManager; return; } } } @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) { } public void checkServerTrusted(X509Certificate[]chain, String authType) throws CertificateException { defaultTrustManager.checkServerTrusted(chain, authType); } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
3e1593b0f5097e5247d3d10b1200f222348e44d0
1,530
java
Java
core-components/src/main/java/net/techreadiness/batch/device/DeviceJobCompletionListener.java
SmarterApp/TechnologyReadinessTool
9cac501050fe849be5348b6a45921ce5c3ae4e00
[ "Apache-2.0" ]
4
2015-05-25T18:00:23.000Z
2017-08-21T10:48:44.000Z
core-components/src/main/java/net/techreadiness/batch/device/DeviceJobCompletionListener.java
SmarterApp/TechnologyReadinessTool
9cac501050fe849be5348b6a45921ce5c3ae4e00
[ "Apache-2.0" ]
1
2015-06-09T18:31:21.000Z
2015-06-09T18:31:21.000Z
core-components/src/main/java/net/techreadiness/batch/device/DeviceJobCompletionListener.java
SmarterApp/TechnologyReadinessTool
9cac501050fe849be5348b6a45921ce5c3ae4e00
[ "Apache-2.0" ]
6
2015-02-20T19:07:32.000Z
2017-01-11T07:12:19.000Z
33.26087
112
0.771895
9,169
package net.techreadiness.batch.device; import java.util.Locale; import javax.inject.Inject; import net.techreadiness.batch.listener.JobCompletionListener; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.context.MessageSource; public class DeviceJobCompletionListener extends JobCompletionListener { @Inject private MessageSource messageSource; @Override protected String getStatusMessage(JobExecution execution) { return getMessage(execution); } @Override protected String getFailedMessage(JobExecution execution) { return getMessage(execution); } private String getMessage(JobExecution execution) { int orgCount = execution.getExecutionContext().getInt("device.org.delete.count", 0); int writeCount = execution.getExecutionContext().getInt("file.status.write.count"); int errorCount = execution.getExecutionContext().getInt("file.status.error.count"); int totalRecordCount = writeCount + errorCount; StringBuilder sb = new StringBuilder(); for (StepExecution step : execution.getStepExecutions()) { if (step.getStepName().equalsIgnoreCase("deviceItemEraser")) { sb.append(messageSource.getMessage("ready.device.file.final.status.delete", new Object[] { orgCount }, Locale.getDefault())); sb.append(" "); break; } } sb.append(messageSource.getMessage("file.generic.write.status", new Object[] { totalRecordCount, errorCount }, Locale.getDefault())); return sb.toString(); } }
3e1594b65eb1102fcdc187ca333eadf8966477a9
705
java
Java
console-adapter/src/main/java/io/github/bharatmane/hexagonalthis/console/UserResource.java
bharatmane/hexagonal-this
d1fa979bf94fcaf8cfdc9bd565cfa0e5e82d93d2
[ "MIT" ]
null
null
null
console-adapter/src/main/java/io/github/bharatmane/hexagonalthis/console/UserResource.java
bharatmane/hexagonal-this
d1fa979bf94fcaf8cfdc9bd565cfa0e5e82d93d2
[ "MIT" ]
null
null
null
console-adapter/src/main/java/io/github/bharatmane/hexagonalthis/console/UserResource.java
bharatmane/hexagonal-this
d1fa979bf94fcaf8cfdc9bd565cfa0e5e82d93d2
[ "MIT" ]
null
null
null
32.045455
111
0.75461
9,170
package io.github.bharatmane.hexagonalthis.console; import io.github.bharatmane.hexagonalthis.domainapi.model.User; import io.github.bharatmane.hexagonalthis.domainapi.model.port.RequestUser; import java.util.List; public class UserResource { private final RequestUser requestUser; public UserResource(RequestUser requestUser) { this.requestUser = requestUser; } public List<User> getAllUsers(){return this.requestUser.getAllUsers();} public void addUser(int userId,String firstName,String lastName, String email) { User user = User.builder().userId(userId).firstName(firstName).lastName(lastName).email(email).build(); requestUser.addUser(user); } }
3e159553897cfb6e0cc31af29d93a311ac25c54f
2,507
java
Java
src/main/java/com/liuming/eshop/utils/IDUtils.java
GitHub-LiuMing/E-Shop
8f051ecc1bc1e82afc84b194a18f91c4df11668d
[ "MIT" ]
null
null
null
src/main/java/com/liuming/eshop/utils/IDUtils.java
GitHub-LiuMing/E-Shop
8f051ecc1bc1e82afc84b194a18f91c4df11668d
[ "MIT" ]
1
2021-09-20T20:54:32.000Z
2021-09-20T20:54:32.000Z
src/main/java/com/liuming/eshop/utils/IDUtils.java
GitHub-LiuMing/E-Shop
8f051ecc1bc1e82afc84b194a18f91c4df11668d
[ "MIT" ]
null
null
null
23.212963
67
0.669326
9,171
package com.liuming.eshop.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * @Description ID生成工具类 * @ClassName IDUtils * @author 鲸落 * @date 2018.03.01 10:47:38 */ public class IDUtils { /** * @Description 图片名生成 yyyyMMddHHmmssSSS + 4位随机数 * @Title getImageName * @return String * @author 鲸落 * @date 2018.03.02 10:49:40 */ public static String getImageName() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String date = sdf.format(new Date()); // 加上三位随机数 Random random = new Random(); int end3 = random.nextInt(999); // 如果不足三位前面补0 String str = date + String.format("%03d", end3); return str; } /** * @Description ID生成 * @Title getDataId * @return long * @author 鲸落 * @date 2018.03.02 10:49:59 */ public static long getDataId() { // 取当前时间的长整形值包含毫秒 long millis = System.currentTimeMillis(); // long millis = System.nanoTime(); // 加上两位随机数 Random random = new Random(); int end4 = random.nextInt(9999); // 如果不足两位前面补0 String str = millis + String.format("%04d", end4); long id = new Long(str); return id; } public static long getTimestamp() { // 取当前时间的长整形值包含毫秒 long millis = System.currentTimeMillis(); // long millis = System.nanoTime(); // 加上两位随机数 Random random = new Random(); int end4 = random.nextInt(9999); // 如果不足两位前面补0 String str = millis + String.format("%04d", end4); long id = new Long(str); return id; } /** * @Description ID生成 yyyyMMddHHmmssSSS+4位随机数 * @Title getId * @return String * @author 鲸落 * @date 2018.03.02 10:50:29 */ public static String getId() { // 取当前时间包含毫秒 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String date = sdf.format(new Date()); // 加上4位随机数 Random random = new Random(); int end4 = random.nextInt(9999); // 如果不足两位前面补0 return date + String.format("%04d", end4); } public static String getDateId() { // 取当前时间包含毫秒 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String date = sdf.format(new Date()); // 加上4位随机数 Random random = new Random(); int end2 = random.nextInt(99); // 如果不足两位前面补0 return date + String.format("%02d", end2); } public static String getBatchNo() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String date = sdf.format(new Date()); return date+""; } public static void main(String[] args) { // 取当前时间包含毫秒 String batchNo = getBatchNo(); System.out.println(batchNo); } }
3e159569b070782df751211bd92940691758a25a
1,393
java
Java
network/src/main/java/com/github/kuangcp/bio/onechatone/ChatMaps.java
Kuangcp/JavaBase
398b05ce0269b20d8ed3854e737ee8e54d74ead2
[ "MIT" ]
16
2017-07-11T14:11:48.000Z
2021-03-31T08:50:55.000Z
network/src/main/java/com/github/kuangcp/bio/onechatone/ChatMaps.java
Kuangcp/JavaBase
398b05ce0269b20d8ed3854e737ee8e54d74ead2
[ "MIT" ]
1
2017-07-03T06:50:53.000Z
2019-03-06T18:05:18.000Z
network/src/main/java/com/github/kuangcp/bio/onechatone/ChatMaps.java
Kuangcp/JavaBase
398b05ce0269b20d8ed3854e737ee8e54d74ead2
[ "MIT" ]
13
2018-01-10T05:03:50.000Z
2020-11-24T09:58:27.000Z
26.788462
75
0.553482
9,172
package com.github.kuangcp.bio.onechatone; import java.util.*; /** * Created by Myth on 2017/4/2 * */ public class ChatMaps<K,V> { //创建一个线程安全的HashMap public Map<K,V> map = Collections.synchronizedMap(new HashMap<K, V>()); //根据Value来删除指定项 public synchronized void removeByValue(Object value){ for(Object key:map.keySet()){ if(map.get(key) == value){ map.remove(key); break; } } } //获取所有Value组成的set集合中 public synchronized Set<V> valueSet(){ Set <V> result = new HashSet<V>(); //将Map中所有Value添加到result集合中 //java8表达式: map.forEach((key,value)->result.add(value)); return result; } //根据value查找key public synchronized K getKeyByValue(V val){ //遍历所有key组成的集合 for (K key:map.keySet()){ //如果指定key对应的value与被搜索的value相同,则返回相同的key if(map.get(key) == val || map.get(key).equals(val)){ return key; } } return null; } //实现put方法,该方法不允许value重复 public synchronized V put(K key,V value){ for(V val:valueSet()){ //如果放入的value是有重复的,就抛出异常 if(val.equals(value) && val.hashCode() == value.hashCode()){ throw new RuntimeException("MyMap实例中不允许有重复value!"); } } return map.put(key,value); } }
3e15959ba87a005237622d2aec19af28ef6845f6
619
java
Java
src/Test.java
tarunbod/derivative-calculator
9379740b0d36f6d005eeb893b04912233a8be6a5
[ "MIT" ]
null
null
null
src/Test.java
tarunbod/derivative-calculator
9379740b0d36f6d005eeb893b04912233a8be6a5
[ "MIT" ]
null
null
null
src/Test.java
tarunbod/derivative-calculator
9379740b0d36f6d005eeb893b04912233a8be6a5
[ "MIT" ]
null
null
null
30.95
65
0.463651
9,173
public class Test { public static void main(String[] args) { String[] inputs = { "5x^4 + 6x^3 - x^2 + 25x", "5x^4 + 6x^2 -& 42x * sin(5x / 6)", "4x^3 + 6(2x + 7)" }; // List<Token> tokens = Tokenizer.processInput(inputs[0]); // for (Token t : tokens) { // if (t.type() != TokenType.WHITESPACE) { // System.out.println(t); // } // } Parser p = new Parser(inputs[0]); System.out.println(p.getExpression()); System.out.println(p.getExpression().getDerivative()); } }
3e15965485d624430356d1930608ec0550710960
2,007
java
Java
EvoSuiteTests/evosuite_4/evosuite-tests/org/mozilla/javascript/v8dtoa/DiyFp_ESTest.java
LASER-UMASS/Swami
feaa5e091b7c2514db5106eba39f7ffbfa6ed408
[ "MIT" ]
9
2019-02-25T16:12:31.000Z
2022-01-18T02:39:50.000Z
EvoSuiteTests/evosuite_4/evosuite-tests/org/mozilla/javascript/v8dtoa/DiyFp_ESTest.java
sophiatong/Swami-Additional
feaa5e091b7c2514db5106eba39f7ffbfa6ed408
[ "MIT" ]
null
null
null
EvoSuiteTests/evosuite_4/evosuite-tests/org/mozilla/javascript/v8dtoa/DiyFp_ESTest.java
sophiatong/Swami-Additional
feaa5e091b7c2514db5106eba39f7ffbfa6ed408
[ "MIT" ]
5
2019-11-21T06:51:40.000Z
2022-01-18T02:40:08.000Z
27.875
176
0.663179
9,174
/* * This file was automatically generated by EvoSuite * Wed Aug 01 17:58:51 GMT 2018 */ package org.mozilla.javascript.v8dtoa; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; import org.mozilla.javascript.v8dtoa.DiyFp; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class DiyFp_ESTest extends DiyFp_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { DiyFp diyFp0 = new DiyFp(); String string0 = diyFp0.toString(); assertEquals("[DiyFp f:0, e:0]", string0); } @Test(timeout = 4000) public void test1() throws Throwable { DiyFp diyFp0 = new DiyFp(0L, 0); diyFp0.setF(0); } @Test(timeout = 4000) public void test2() throws Throwable { DiyFp diyFp0 = new DiyFp(578, 578); DiyFp diyFp1 = DiyFp.normalize(diyFp0); assertNotSame(diyFp1, diyFp0); } @Test(timeout = 4000) public void test3() throws Throwable { DiyFp diyFp0 = new DiyFp(1L, 2010); DiyFp diyFp1 = DiyFp.times(diyFp0, diyFp0); assertNotSame(diyFp1, diyFp0); } @Test(timeout = 4000) public void test4() throws Throwable { DiyFp diyFp0 = new DiyFp(1L, 2010); long long0 = diyFp0.f(); assertEquals(1L, long0); } @Test(timeout = 4000) public void test5() throws Throwable { DiyFp diyFp0 = new DiyFp((-1L), 0); int int0 = diyFp0.e(); assertEquals(0, int0); } @Test(timeout = 4000) public void test6() throws Throwable { DiyFp diyFp0 = new DiyFp((-619), (-619)); DiyFp diyFp1 = DiyFp.minus(diyFp0, diyFp0); assertNotSame(diyFp1, diyFp0); } @Test(timeout = 4000) public void test7() throws Throwable { DiyFp diyFp0 = new DiyFp(); diyFp0.setE(0); } }
3e1598c971a01338878aeff8451c544a399f4dd2
6,429
java
Java
src/main/java/org/conscrypt/OpenSSLMac.java
Keneral/aeconscrypt
ee785d9d21736e1e8b5e8dd2de13afe0a9145ca5
[ "Unlicense" ]
null
null
null
src/main/java/org/conscrypt/OpenSSLMac.java
Keneral/aeconscrypt
ee785d9d21736e1e8b5e8dd2de13afe0a9145ca5
[ "Unlicense" ]
null
null
null
src/main/java/org/conscrypt/OpenSSLMac.java
Keneral/aeconscrypt
ee785d9d21736e1e8b5e8dd2de13afe0a9145ca5
[ "Unlicense" ]
null
null
null
30.760766
99
0.647379
9,175
/* * Copyright (C) 2012 The Android Open Source Project * * 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.conscrypt; import java.nio.ByteBuffer; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.MacSpi; import javax.crypto.SecretKey; public abstract class OpenSSLMac extends MacSpi { private NativeRef.HMAC_CTX ctx; /** * Holds the EVP_MD for the hashing algorithm, e.g. * EVP_get_digestbyname("sha1"); */ private final long evp_md; /** * The secret key used in this keyed MAC. */ private byte[] keyBytes; /** * Holds the output size of the message digest. */ private final int size; /** * Holds a dummy buffer for writing single bytes to the digest. */ private final byte[] singleByte = new byte[1]; private OpenSSLMac(long evp_md, int size) { this.evp_md = evp_md; this.size = size; } @Override protected int engineGetMacLength() { return size; } @Override protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException { if (!(key instanceof SecretKey)) { throw new InvalidKeyException("key must be a SecretKey"); } if (params != null) { throw new InvalidAlgorithmParameterException("unknown parameter type"); } keyBytes = key.getEncoded(); if (keyBytes == null) { throw new InvalidKeyException("key cannot be encoded"); } resetContext(); } private final void resetContext() { NativeRef.HMAC_CTX ctxLocal = new NativeRef.HMAC_CTX(NativeCrypto.HMAC_CTX_new()); if (keyBytes != null) { NativeCrypto.HMAC_Init_ex(ctxLocal, keyBytes, evp_md); } this.ctx = ctxLocal; } @Override protected void engineUpdate(byte input) { singleByte[0] = input; engineUpdate(singleByte, 0, 1); } @Override protected void engineUpdate(byte[] input, int offset, int len) { final NativeRef.HMAC_CTX ctxLocal = ctx; NativeCrypto.HMAC_Update(ctxLocal, input, offset, len); } @Override protected void engineUpdate(ByteBuffer input) { // Optimization: Avoid copying/allocation for direct buffers because their contents are // stored as a contiguous region in memory and thus can be efficiently accessed from native // code. if (!input.hasRemaining()) { return; } if (!input.isDirect()) { super.engineUpdate(input); return; } long baseAddress = NativeCrypto.getDirectBufferAddress(input); if (baseAddress == 0) { // Direct buffer's contents can't be accessed from JNI -- superclass's implementation // is good enough to handle this. super.engineUpdate(input); return; } // MAC the contents between Buffer's position and limit (remaining() number of bytes) int position = input.position(); if (position < 0) { throw new RuntimeException("Negative position"); } long ptr = baseAddress + position; int len = input.remaining(); if (len < 0) { throw new RuntimeException("Negative remaining amount"); } final NativeRef.HMAC_CTX ctxLocal = ctx; NativeCrypto.HMAC_UpdateDirect(ctxLocal, ptr, len); input.position(position + len); } @Override protected byte[] engineDoFinal() { final NativeRef.HMAC_CTX ctxLocal = ctx; final byte[] output = NativeCrypto.HMAC_Final(ctxLocal); resetContext(); return output; } @Override protected void engineReset() { resetContext(); } public static class HmacMD5 extends OpenSSLMac { private static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("md5"); private static final int SIZE = NativeCrypto.EVP_MD_size(EVP_MD); public HmacMD5() { super(EVP_MD, SIZE); } } public static class HmacSHA1 extends OpenSSLMac { private static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("sha1"); private static final int SIZE = NativeCrypto.EVP_MD_size(EVP_MD); public HmacSHA1() { super(EVP_MD, SIZE); } } public static class HmacSHA224 extends OpenSSLMac { private static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("sha224"); private static final int SIZE = NativeCrypto.EVP_MD_size(EVP_MD); public HmacSHA224() throws NoSuchAlgorithmException { super(EVP_MD, SIZE); } } public static class HmacSHA256 extends OpenSSLMac { private static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("sha256"); private static final int SIZE = NativeCrypto.EVP_MD_size(EVP_MD); public HmacSHA256() throws NoSuchAlgorithmException { super(EVP_MD, SIZE); } } public static class HmacSHA384 extends OpenSSLMac { private static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("sha384"); private static final int SIZE = NativeCrypto.EVP_MD_size(EVP_MD); public HmacSHA384() throws NoSuchAlgorithmException { super(EVP_MD, SIZE); } } public static class HmacSHA512 extends OpenSSLMac { private static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("sha512"); private static final int SIZE = NativeCrypto.EVP_MD_size(EVP_MD); public HmacSHA512() { super(EVP_MD, SIZE); } } }
3e159ab2f4ab6dfc45a068784b83bd4e259721c8
8,870
java
Java
tools/clients/src/main/java/com/tigergraph/v3_0_5/client/util/RetryableHttpConnection.java
carlboudreau007/ecosys
d415143837a85ceb6213a0f0588128a86a4a3984
[ "Apache-2.0" ]
245
2018-04-07T00:14:56.000Z
2022-03-28T05:51:35.000Z
tools/clients/src/main/java/com/tigergraph/v3_0_5/client/util/RetryableHttpConnection.java
carlboudreau007/ecosys
d415143837a85ceb6213a0f0588128a86a4a3984
[ "Apache-2.0" ]
47
2018-04-02T16:41:22.000Z
2022-03-24T01:40:46.000Z
tools/clients/src/main/java/com/tigergraph/v3_0_5/client/util/RetryableHttpConnection.java
carlboudreau007/ecosys
d415143837a85ceb6213a0f0588128a86a4a3984
[ "Apache-2.0" ]
140
2018-08-09T15:54:47.000Z
2022-03-30T12:44:48.000Z
34.247104
100
0.645772
9,176
package com.tigergraph.v3_0_5.client.util; import org.apache.http.client.utils.URIBuilder; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.*; import java.net.*; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static com.tigergraph.v3_0_5.client.util.SystemUtils.logger; /** * A RetryableHttpConnection that takes a list of IPs and ports, * tries to set up connection to one of them, and retry if it can't * connect successfully. * It will try each ip/port up to {@code maxRetry} times. */ public class RetryableHttpConnection { private static final String LOCAL_HOST = "127.0.0.1"; private static final int DEFAULT_CONNECTION_TIMEOUT = 300000; // 5 min // Interval (seconds) of retry to connect to GSQL server. private static final int RETRY_INTERVAL = 1; private List<String> ips; private List<Integer> ports; // max retry per ip/port private int maxRetry = 1; // rotation index for ip/port, so we can use the one succeed last time // to save some time. private int index = 0; // for SSL private SSLContext sslContext = null; // default port private int defaultPrivatePort = 8123; // Path to CA Certificate. {@code null} if not given. public RetryableHttpConnection(boolean ssl, String cert, int defaultPort) throws Exception { if (ssl) { sslContext = cert != null ? getSSLContext(cert) : javax.net.ssl.SSLContext.getDefault(); } ips = new ArrayList<>(); ports = new ArrayList<>(); defaultPrivatePort = defaultPort; } public void setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; } @Override public int hashCode() { return ips.hashCode(); } public void addIpPort(String ip, int port) { try { buildUrl(null, ip, port); ips.add(ip); ports.add(port); } catch (URISyntaxException e) { logger.error(e); SystemUtils.exit(SystemUtils.ExitStatus.WRONG_ARGUMENT_ERROR, "Invalid URL: " + e.getInput()); } catch (MalformedURLException e) { // this does not validate URL and only detects unknown protocol logger.error(e); SystemUtils.exit(SystemUtils.ExitStatus.RUNTIME_ERROR, "Unknown protocol:%s", e.getMessage()); } } public void addLocalHost(int port) { addIpPort(LOCAL_HOST, port); } public boolean isLocal() { return ports.size() == 1 && ips.size() == 1 && ips.get(0).equals(LOCAL_HOST) && ports.get(0).equals(defaultPrivatePort); } public URI getCurrentURI() throws MalformedURLException, URISyntaxException { URL url = buildUrl(null, ips.get(index), ports.get(index)); return url.toURI(); } /** * Build the endpoint URL to GSQL server. * e.g. http://127.0.0.1:8123/gsql (local) * http://127.0.0.1:8123/gsql/endpoint (local) * https://192.168.0.10:14240/gsqlserver/gsql (remote) * @param endpoint the endpoint, null if no endpoint just test gsql-server url is correct * @param ip the ip address * @param port the port of gsql-server * @return the URL to gsql-server with given inputs * @throws URISyntaxException, MalformedURLException if given input can't build a valid URL */ private URL buildUrl(String endpoint, String ip, int port) throws URISyntaxException, MalformedURLException { String baseEndpoint = ip.equals(LOCAL_HOST) && port == defaultPrivatePort ? "gsql" : "gsqlserver/gsql"; String path = endpoint != null ? String.join("/", "", baseEndpoint, endpoint) : String.join("/", "", baseEndpoint); URI uri = new URIBuilder() .setScheme(sslContext != null ? "https" : "http") .setHost(ip) .setPort(port) .setPath(path) .build(); return uri.toURL(); } /** * Open a http or https connection with given {@code url} * @param url the url to open connection with * @return the HttpURLConnection or HttpsURLConnection * @throws Exception */ private HttpURLConnection openConnection(URL url) throws Exception { if (sslContext != null) { // open HttpsURLConnection when CA Certificate is given HttpsURLConnection connSecured = (HttpsURLConnection) url.openConnection(); connSecured.setSSLSocketFactory(sslContext.getSocketFactory()); return connSecured; } else { return (HttpURLConnection) url.openConnection(); } } /** * Build the http connection by given inputs with {@code ips} and {@code ports}. * Try the {@code ips} and {@code ports} one by one until success. * Each ip and port will retry up to {@code maxRetry} times. * @param endpoint the gsql-server endpoint * @param method GET/POST/PUT * @param data the payload, null if no payload * @param headers the map of headers, null if no headers * @return the HttpURLConnection * @throws Exception */ public HttpURLConnection connect(String endpoint, String method, String data, Map<String, String> headers) throws Exception { logger.info("RetryableHttpConnection: endpoint: %s, data.len: %d, method: %s", endpoint, data.length(), method); // try all ips for (int i = 0; i < ips.size() && !ips.isEmpty(); ++i, ++index) { if (index >= ips.size()) { index = 0; } try { // 1. build URL URL url = buildUrl(endpoint, ips.get(index), ports.get(index)); // 2. open connection HttpURLConnection conn = openConnection(url); conn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT); // set headers, e.g. user auth token if (headers != null) { headers.forEach((k, v) -> conn.setRequestProperty(k, v)); } conn.setRequestMethod(method); conn.setUseCaches(false); conn.setDoInput(true); // retry up to maxRetry times for (int j = 0; j < maxRetry; ++j) { if (j > 0) { TimeUnit.SECONDS.sleep(RETRY_INTERVAL); } try { //2. write data to the connection if needed if (data != null) { conn.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); } //3. get response // gsql-server will only return 200 or 401 (unauthorized) int code = conn.getResponseCode(); if (code == 200 || code == 401) { return conn; } logger.error("code: %d, msg: %s", code, conn.getResponseMessage()); // retry when there's server error HTTP 5xx if (code / 500 == 1) { continue; } // get something else, try next ip/port break; } catch (IOException e) { // silently retry to connect this ip/port } } } catch (URISyntaxException | IOException | InterruptedException e) { // got non-retryable exception for an ip/port, log and try next logger.error(e); } } logger.error("Unable to connect to all IPs"); throw new ConnectException(); } /** * load the CA and use it in the https connection * @param filename the CA filename * @return the SSL context */ private SSLContext getSSLContext(String filename) throws Exception { try { // Load CAs from an InputStream // (could be from a resource or ByteArrayInputStream or ...) // X.509 is a standard that defines the format of public key certificates, used in TLS/SSL. CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream(new FileInputStream(filename)); Certificate ca = cf.generateCertificate(caInput); // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); return context; } catch (Exception e) { throw new Exception("Failed to load the CA file: " + e.getMessage(), e); } } }
3e159b834372e4359384ce33cb3a4052a9325a3f
2,845
java
Java
Source/AgentSlang/src/org/agent/slang/dm/template/DialogueUnit.java
AgentSlang/AgentSlangSrc
6a508f79360b2301561d8d7093fb195f47de6837
[ "CECILL-B", "Unlicense" ]
null
null
null
Source/AgentSlang/src/org/agent/slang/dm/template/DialogueUnit.java
AgentSlang/AgentSlangSrc
6a508f79360b2301561d8d7093fb195f47de6837
[ "CECILL-B", "Unlicense" ]
null
null
null
Source/AgentSlang/src/org/agent/slang/dm/template/DialogueUnit.java
AgentSlang/AgentSlangSrc
6a508f79360b2301561d8d7093fb195f47de6837
[ "CECILL-B", "Unlicense" ]
null
null
null
30.98913
79
0.670291
9,177
/* * Copyright (c) Ovidiu Serban, dycjh@example.com * web:http://ovidiu.roboslang.org/ * All Rights Reserved. Use is subject to license terms. * * This file is part of AgentSlang Project (http://agent.roboslang.org/). * * AgentSlang is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License and CECILL-B. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The CECILL-B license file should be a part of this project. If not, * it could be obtained at <http://www.cecill.info/>. * * The usage of this project makes mandatory the authors citation in * any scientific publication or technical reports. For websites or * research projects the AgentSlang website and logo needs to be linked * in a visible area. */ package org.agent.slang.dm.template; /** * A data type for displaying dialogues. * OS Compatibility: Windows and Linux * @author Ovidiu Serban, dycjh@example.com * @version 1, 1/5/13 */ public class DialogueUnit { public static final String TAG_DIALOGUE_UNITS = "dialogue-units"; public static final String TAG_DIALOGUE_UNIT = "du"; public static final String TAG_DIALOGUE_GENERATORS = "dialogue-generators"; public static final String TAG_DIALOGUE_GENERATOR = "dg"; public static final String PROP_ID = "id"; public static final String PROP_PATTERN = "pattern"; public static final String PROP_REPLY_TEXT = "response"; private String id; private String replyText; public DialogueUnit(String id, String replyText) { this.id = id; this.replyText = replyText; } /** * Gets dialogue id * @return dialogue id */ public String getId() { return id; } /** * Gets machine response in terms of text to a child action * @return response text */ public String getReplyText() { return replyText; } /** * Checks if an object is a dialogue unit * @return boolean */ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DialogueUnit that = (DialogueUnit) o; return id != null ? id.equals(that.id) : that.id == null; } /** * gets hash code of the id */ public int hashCode() { return id != null ? id.hashCode() : 0; } }
3e159bb45af80a79037b734887684ed5174c7f7d
5,201
java
Java
src/main/java/mrriegel/playerstorage/registry/TileKeeper.java
KidsDontPlay/PlayerStorage
16c8a6d09d00267ac5b4f6c7ce9e1897e34e89c6
[ "MIT" ]
1
2019-04-12T17:51:06.000Z
2019-04-12T17:51:06.000Z
src/main/java/mrriegel/playerstorage/registry/TileKeeper.java
KidsDontPlay/PlayerStorage
16c8a6d09d00267ac5b4f6c7ce9e1897e34e89c6
[ "MIT" ]
6
2019-03-27T19:54:55.000Z
2019-06-13T22:23:10.000Z
src/main/java/mrriegel/playerstorage/registry/TileKeeper.java
KidsDontPlay/PlayerStorage
16c8a6d09d00267ac5b4f6c7ce9e1897e34e89c6
[ "MIT" ]
2
2019-06-15T01:58:39.000Z
2020-10-25T08:42:05.000Z
37.15
230
0.716593
9,178
package mrriegel.playerstorage.registry; import java.util.ArrayList; import java.util.Collections; import java.util.List; import mrriegel.limelib.helper.NBTHelper; import mrriegel.limelib.tile.CommonTile; import mrriegel.limelib.tile.IHUDProvider; import mrriegel.limelib.util.StackWrapper; import mrriegel.playerstorage.ExInventory; import net.minecraft.block.Block; import net.minecraft.entity.EntityTracker; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.network.play.server.SPacketCollectItem; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fluids.FluidStack; public class TileKeeper extends CommonTile implements IHUDProvider { private List<StackWrapper> items = new ArrayList<>(); private List<FluidStack> fluids = new ArrayList<>(); private String name; public void create(ExInventory exi) { items = new ArrayList<>(exi.items); exi.items.clear(); fluids = new ArrayList<>(exi.fluids); exi.fluids.clear(); exi.markForSync(); name = exi.player.getName(); if (items.isEmpty() && fluids.isEmpty()) world.destroyBlock(pos, false); else { ItemStack paper = new ItemStack(Items.PAPER); NBTTagCompound nbt = new NBTTagCompound(); NBTTagCompound dis = new NBTTagCompound(); NBTHelper.set(dis, "Name", TextFormatting.RESET + "" + TextFormatting.BOLD + "You died!"); NBTTagList l = new NBTTagList(); for (String s : new String[] { name, // TextFormatting.GOLD + "Dimension: " + TextFormatting.GRAY + DimensionManager.getProviderType(world.provider.getDimension()).getName() + " (" + world.provider.getDimension() + ")", // TextFormatting.GOLD + "Position:" + TextFormatting.GRAY + " x: " + TextFormatting.AQUA + getX() + TextFormatting.GRAY + ", y: " + TextFormatting.AQUA + getY() + TextFormatting.GRAY + ", z: " + TextFormatting.AQUA + getZ(), // TextFormatting.ITALIC + "You should retrieve your items and fluids there." }) l.appendTag(new NBTTagString(TextFormatting.RESET + "" + TextFormatting.GRAY + s)); dis.setTag("Lore", l); NBTHelper.set(nbt, "display", dis); paper.setTagCompound(nbt); exi.insertItem(paper, false); } markForSync(); } public void destroy(EntityPlayerMP player) { if (player.getName().equals(name)) { ExInventory exi = ExInventory.getInventory(player); for (StackWrapper sw : items) { for (ItemStack s : StackWrapper.toStackList(sw)) { ItemStack rest = exi.insertItem(s, false); if (rest.isEmpty()) { EntityTracker entitytracker = ((WorldServer) world).getEntityTracker(); Vec3d vec = player.getLookVec().normalize(); Vec3d vecP = new Vec3d(player.posX, player.posY, player.posZ); EntityItem ei = new EntityItem(world, vecP.add(vec).x, player.posY + .3, vecP.add(vec).z, s); entitytracker.sendToTracking(ei, new SPacketCollectItem(ei.getEntityId(), player.getEntityId(), 1)); } Block.spawnAsEntity(world, pos.up(), rest); } } for (FluidStack fs : fluids) { exi.insertFluid(fs, false); } world.destroyBlock(pos, false); } } @Override public boolean openGUI(EntityPlayerMP player) { destroy(player); return super.openGUI(player); } @Override public void readFromNBT(NBTTagCompound compound) { int size = NBTHelper.get(compound, "itemsize", Integer.class); items.clear(); for (int i = 0; i < size; i++) { StackWrapper sw = StackWrapper.loadStackWrapperFromNBT(NBTHelper.get(compound, "item" + i, NBTTagCompound.class)); if (sw != null) items.add(sw); } size = NBTHelper.get(compound, "fluidsize", Integer.class); fluids.clear(); for (int i = 0; i < size; i++) { FluidStack fs = FluidStack.loadFluidStackFromNBT(NBTHelper.get(compound, "fluid" + i, NBTTagCompound.class)); if (fs != null) fluids.add(fs); } name = NBTHelper.get(compound, "name", String.class); super.readFromNBT(compound); } @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { NBTHelper.set(compound, "itemsize", items.size()); for (int i = 0; i < items.size(); i++) NBTHelper.set(compound, "item" + i, items.get(i).writeToNBT(new NBTTagCompound())); NBTHelper.set(compound, "fluidsize", fluids.size()); for (int i = 0; i < fluids.size(); i++) NBTHelper.set(compound, "fluid" + i, fluids.get(i).writeToNBT(new NBTTagCompound())); NBTHelper.set(compound, "name", name); return super.writeToNBT(compound); } @Override public List<String> getData(boolean sneak, EnumFacing facing) { return Collections.singletonList(TextFormatting.GOLD + "Owner: " + (name == null ? TextFormatting.RED : TextFormatting.GREEN) + name); } @Override public double scale(boolean sneak, EnumFacing facing) { return 1.; } @Override public boolean lineBreak(boolean sneak, EnumFacing facing) { return false; } }
3e159c5b0468e8aeb4d048740640bfbf491efdbf
3,884
java
Java
src/test/java/ru/moskalets/controller/CarControllerTest.java
Igor85342/carsplatform
2ac80b160304c5bac47f5fa21456f082db289110
[ "Apache-2.0" ]
1
2019-09-12T03:47:59.000Z
2019-09-12T03:47:59.000Z
src/test/java/ru/moskalets/controller/CarControllerTest.java
Igor85342/carsplatform
2ac80b160304c5bac47f5fa21456f082db289110
[ "Apache-2.0" ]
null
null
null
src/test/java/ru/moskalets/controller/CarControllerTest.java
Igor85342/carsplatform
2ac80b160304c5bac47f5fa21456f082db289110
[ "Apache-2.0" ]
null
null
null
33.482759
104
0.677652
9,179
package ru.moskalets.controller; 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.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.web.multipart.MultipartResolver; import ru.moskalets.repository.*; import ru.moskalets.service.CarService; import ru.moskalets.service.UserService; import javax.sql.DataSource; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(CarController.class) public class CarControllerTest { @Autowired private MockMvc mvc; @MockBean private CarService service; @MockBean private UserService userService; @MockBean private DataSource dataSource; @MockBean private BrandRepository brandRepository; @MockBean private MotorRepository motorRepository; @MockBean private CarbodyRepository carbodyRepository; @MockBean private CategoryRepository categoryRepository; @MockBean private TransmissionRepository transmissionRepository; @MockBean private UserRepository userRepository; @MockBean private CarRepository carRepository; @MockBean private MultipartResolver multipartResolver; @Test @WithMockUser(username = "1", roles = {"User"}) public void testShowAllCars() throws Exception { this.mvc.perform(get("/cars/").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()) .andExpect(view().name("CarsView")); } @Test @WithMockUser(username = "1", roles = {"User"}) public void testShowCarsWithImage() throws Exception { this.mvc.perform(get("/cars/showCarsWithImage").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()) .andExpect(view().name("CarsView")); } @Test @WithMockUser(username = "1", roles = {"User"}) public void testShowCarsLastDay() throws Exception { this.mvc.perform(get("/cars/showCarsLastDay").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()) .andExpect(view().name("CarsView")); } @Test @WithMockUser(username = "1", roles = {"User"}) public void testShowCarsWithBrand() throws Exception { this.mvc.perform(get("/cars/showCarsWithBrand").accept(MediaType.TEXT_HTML).param("brand", "0")) .andExpect(status().isOk()) .andExpect(view().name("CarsView")); } @Test @WithMockUser(username = "1", roles = {"User"}) public void testCreateCarGet() throws Exception { this.mvc.perform(get("/cars/createCar").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()) .andExpect(view().name("CarCreateView")); } @Test @WithMockUser(username = "1", roles = {"User"}) public void testCreateCarPost() throws Exception { MockHttpServletRequestBuilder multipart = multipart("/cars/createCar") .file("file", "123".getBytes()) .param("category", "0") .param("brand", "0") .param("carbody", "0") .param("motor", "0") .param("transmission", "0"); this.mvc.perform(multipart) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/cars/")); } }
3e159d345127628f2be6a0532fe101b6815dba79
230
java
Java
src/main/java/com/iminit/common/model/Num.java
iminit/memo
9ef401ba6dee8526638672d618dff57b9e2e9f6a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/iminit/common/model/Num.java
iminit/memo
9ef401ba6dee8526638672d618dff57b9e2e9f6a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/iminit/common/model/Num.java
iminit/memo
9ef401ba6dee8526638672d618dff57b9e2e9f6a
[ "Apache-2.0" ]
null
null
null
19.166667
47
0.721739
9,180
package com.iminit.common.model; import com.iminit.common.model.base.BaseNum; /** * Generated by JFinal. */ @SuppressWarnings("serial") public class Num extends BaseNum<Num> { public static final Num dao = new Num().dao(); }
3e159d8879c5404acf4d1d98b0a85ee0c3c599cd
5,332
java
Java
core/server/project/shine/src/main/java/com/home/shine/control/BytesControl.java
hw233/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
8
2020-08-17T09:54:20.000Z
2021-02-08T05:25:02.000Z
core/server/project/shine/src/main/java/com/home/shine/control/BytesControl.java
shineTeam7/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
null
null
null
core/server/project/shine/src/main/java/com/home/shine/control/BytesControl.java
shineTeam7/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
5
2020-07-24T03:07:08.000Z
2021-11-17T14:20:15.000Z
21.942387
90
0.65904
9,181
package com.home.shine.control; import com.home.shine.constlist.generate.ShineRequestType; import com.home.shine.ctrl.Ctrl; import com.home.shine.data.BaseData; import com.home.shine.global.ShineSetting; import com.home.shine.net.base.BaseResponse; import com.home.shine.support.collection.IntObjectMap; import com.home.shine.support.collection.IntSet; import com.home.shine.thread.AbstractThread; import com.home.shine.tool.CreateDataFunc; import com.home.shine.tool.DataMaker; import com.home.shine.tool.generate.ShineDataMaker; import java.lang.reflect.Field; /** 字节控制(包括Data序列化/反序列化)(compress部分没封装完) */ public class BytesControl { /** 数据Maker(包括Response) */ private static DataMaker _dataMaker=new DataMaker(); /** 发送消息(只Request) */ private static DataMaker _requestMaker=new DataMaker(); /** 发送名字组 */ private static IntObjectMap<String> _requestNames=new IntObjectMap<>(); /** 接收名字组 */ private static IntObjectMap<String> _responseNames=new IntObjectMap<>(); /** 协议忽略mid */ private static IntSet _messageIgnoreSet=new IntSet(); /** 添加数据构造器 */ public static void addDataMaker(DataMaker maker) { _dataMaker.addDic(maker); } /** 添加消息maker */ public static void addRequestMaker(DataMaker maker) { _requestMaker.addDic(maker); } /** 初始化 */ public static void init() { addDataMaker(new ShineDataMaker()); //添加shine消息 for(int i=ShineRequestType.off;i<ShineRequestType.count;i++) { addIgnoreMessage(i); } } /** 添加消息名字注册 */ public static void addMessageConst(Class<?> cls,boolean isRequest,boolean isServer) { Field[] fields=cls.getFields(); try { String name; for(Field v:fields) { name=v.getName(); //排除 if(!name.equals("off") && !name.equals("count")) { int id=v.getInt(cls); if(isRequest) { _requestNames.put(id,isServer ? name+"ServerRequest" : name+"Request"); } else { _responseNames.put(id,isServer ? name+"ServerResponse" : name+"Response"); } } } } catch(Exception e) { Ctrl.errorLog(e); } } //---Data---// /** 通过id取得Data类型 */ public static BaseData getDataByID(int dataID) { if(dataID==-1) { return null; } BaseData re=_dataMaker.getDataByID(dataID); if(re==null) { Ctrl.throwError("找不到Data类型" + dataID); return null; } return re; } /** 通过id取得Request类型 */ public static BaseData getRequestByID(int dataID) { if(dataID==-1) { return null; } BaseData re=_requestMaker.getDataByID(dataID); if(re==null) { Ctrl.throwError("找不到Request类型" + dataID); return null; } return re; } ///** 通过其他数据创建数据(只创建) */ //public static BaseData createData(BaseData data) //{ // return getDataByID(data.getDataID()); //} ///** 获取某数据ID的名字 */ //public static String getDataName(int dataID) //{ // return _dataNames[dataID]; //} /** 数组拷贝 */ public static byte[] byteArrCopy(byte[] src) { byte[] re=new byte[src.length]; System.arraycopy(src,0,re,0,src.length); return re; } /** 数组拷贝(从src拷贝到des) */ public static void arrayCopy(Object src,Object des,int length) { System.arraycopy(src,0,des,0,length); } /** 获取request名字 */ public static String getRequestName(int mid) { return _requestNames.get(mid); } /** 获取response名字 */ public static String getResponseName(int mid) { return _responseNames.get(mid); } /** 添加要被忽略的消息mid */ public static void addIgnoreMessage(int mid) { _messageIgnoreSet.add(mid); } /** 是否shine消息 */ public static boolean isIgnoreMessage(int mid) { return _messageIgnoreSet.contains(mid); } /** 创建data */ public static BaseData createData(int dataID) { AbstractThread thread; if(ShineSetting.messageUsePool && (thread=ThreadControl.getCurrentShineThread())!=null) { BaseData data=thread.pool.createData(dataID); //data.createThreadInstance=thread.instanceIndex; return data; } else { return getDataByID(dataID); } } /** 创建Request消息 */ public static BaseData createRequest(int dataID) { AbstractThread thread; if(ShineSetting.messageUsePool && (thread=ThreadControl.getCurrentShineThread())!=null) { BaseData request=thread.pool.createRequest(dataID); //request.createThreadInstance=thread.instanceIndex; return request; } else { return getRequestByID(dataID); } } /** 创建Request消息 */ public static BaseResponse createResponse(int dataID) { AbstractThread thread; if(ShineSetting.messageUsePool && (thread=ThreadControl.getCurrentShineThread())!=null) { BaseResponse response=(BaseResponse)thread.pool.createData(dataID); response.createThreadInstance=thread.instanceIndex; return response; } else { return (BaseResponse)getDataByID(dataID); } } /** 预备回收response */ public static void preReleaseResponse(BaseResponse response) { if(!response.needRelease()) return; AbstractThread thread; if(ShineSetting.messageUsePool && (thread=ThreadControl.getCurrentShineThread())!=null) { //析构 response.dispose(); thread.dataCache.cacheData(response); } } }
3e159dcd0315bed24bfcb19d66ae9be90236c2e8
207
java
Java
bundle/edu.gemini.ui.workspace/src/main/java/edu/gemini/ui/gface/GSubElementDecorator.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
13
2015-02-04T21:33:56.000Z
2020-04-10T01:37:41.000Z
bundle/edu.gemini.ui.workspace/src/main/java/edu/gemini/ui/gface/GSubElementDecorator.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
1,169
2015-01-02T13:20:50.000Z
2022-03-21T12:01:59.000Z
bundle/edu.gemini.ui.workspace/src/main/java/edu/gemini/ui/gface/GSubElementDecorator.java
jocelynferrara/ocs
446c8a8e03d86bd341ac024fae6811ecb643e185
[ "BSD-3-Clause" ]
13
2015-04-07T18:01:55.000Z
2021-02-03T12:57:58.000Z
18.818182
73
0.748792
9,182
package edu.gemini.ui.gface; import javax.swing.JLabel; public interface GSubElementDecorator<M, E, S> extends GDecorator<M, E> { void decorate(JLabel label, E element, S subElement, Object value); }
3e159df264093ae1757778aefa2f48e689a99df3
1,131
java
Java
documents/javaFiles/dataStructures/currencyproject/Currency.java
KeyMaker13/portfolio
a6c02fe09af4f9a86caf4cd7b74e215751977f88
[ "Zlib", "Apache-2.0" ]
null
null
null
documents/javaFiles/dataStructures/currencyproject/Currency.java
KeyMaker13/portfolio
a6c02fe09af4f9a86caf4cd7b74e215751977f88
[ "Zlib", "Apache-2.0" ]
null
null
null
documents/javaFiles/dataStructures/currencyproject/Currency.java
KeyMaker13/portfolio
a6c02fe09af4f9a86caf4cd7b74e215751977f88
[ "Zlib", "Apache-2.0" ]
null
null
null
14.316456
103
0.548187
9,183
package currency; public class Currency { private int value; private String name; private String countryCode; public Currency() { value = 0; name = ""; countryCode = ""; } public Currency(int v, String n, String cc){ value = v; name = n; countryCode = cc; } public void setValue (int v){ value = v; } public void setName (String s){ name = s; } public void setCountryCode (String cc){ countryCode = cc; } public int getValue() { return value; } public String getName() { return name; } public String getCountryCode() { return countryCode; } public String toString() { String s = "Value : " + getValue() + "\nName: " + getName() + "\nCountry Code: " + getCountryCode(); return s; } public boolean equals (Currency c) { int comp = 0; comp = this.getValue() - c.getValue(); if (comp == 0) { if (this.getName().equals(c.getName())) { if (this.countryCode.equals(c.countryCode)) { return true; } } } return false; } }
3e159e3cff8fa842efe48c5fc5e1642e7149512a
3,835
java
Java
hbase-server/src/main/java/org/apache/hadoop/hbase/quotas/NoOpRegionSizeStore.java
sho25/hbase
3e8689245d8307143722d3f14e451ef265cfa369
[ "Apache-2.0" ]
null
null
null
hbase-server/src/main/java/org/apache/hadoop/hbase/quotas/NoOpRegionSizeStore.java
sho25/hbase
3e8689245d8307143722d3f14e451ef265cfa369
[ "Apache-2.0" ]
null
null
null
hbase-server/src/main/java/org/apache/hadoop/hbase/quotas/NoOpRegionSizeStore.java
sho25/hbase
3e8689245d8307143722d3f14e451ef265cfa369
[ "Apache-2.0" ]
null
null
null
16.673913
805
0.804172
9,184
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|quotas package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map operator|. name|Entry import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|RegionInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|yetus operator|. name|audience operator|. name|InterfaceAudience import|; end_import begin_comment comment|/** * A {@link RegionSizeStore} implementation that stores nothing. */ end_comment begin_class annotation|@ name|InterfaceAudience operator|. name|Private specifier|public specifier|final class|class name|NoOpRegionSizeStore implements|implements name|RegionSizeStore block|{ specifier|private specifier|static specifier|final name|NoOpRegionSizeStore name|INSTANCE init|= operator|new name|NoOpRegionSizeStore argument_list|() decl_stmt|; specifier|private name|NoOpRegionSizeStore parameter_list|() block|{} specifier|public specifier|static name|NoOpRegionSizeStore name|getInstance parameter_list|() block|{ return|return name|INSTANCE return|; block|} annotation|@ name|Override specifier|public name|Iterator argument_list|< name|Entry argument_list|< name|RegionInfo argument_list|, name|RegionSize argument_list|> argument_list|> name|iterator parameter_list|() block|{ return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|long name|heapSize parameter_list|() block|{ return|return literal|0 return|; block|} annotation|@ name|Override specifier|public name|RegionSize name|getRegionSize parameter_list|( name|RegionInfo name|regionInfo parameter_list|) block|{ return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|void name|put parameter_list|( name|RegionInfo name|regionInfo parameter_list|, name|long name|size parameter_list|) block|{} annotation|@ name|Override specifier|public name|void name|incrementRegionSize parameter_list|( name|RegionInfo name|regionInfo parameter_list|, name|long name|delta parameter_list|) block|{} annotation|@ name|Override specifier|public name|RegionSize name|remove parameter_list|( name|RegionInfo name|regionInfo parameter_list|) block|{ return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|int name|size parameter_list|() block|{ return|return literal|0 return|; block|} annotation|@ name|Override specifier|public name|boolean name|isEmpty parameter_list|() block|{ return|return literal|true return|; block|} annotation|@ name|Override specifier|public name|void name|clear parameter_list|() block|{} block|} end_class end_unit
3e159f1c2a0f1cf7382eed9acdfca78b55c2792f
1,475
java
Java
code/com/jivesoftware/os/hwal/permit/src/main/java/com/jivesoftware/os/hwal/permit/PermitProvider.java
jivesoftware/hwal
66f791d2456b1229cdf895d8f4761530a3cb1a7f
[ "Apache-2.0" ]
null
null
null
code/com/jivesoftware/os/hwal/permit/src/main/java/com/jivesoftware/os/hwal/permit/PermitProvider.java
jivesoftware/hwal
66f791d2456b1229cdf895d8f4761530a3cb1a7f
[ "Apache-2.0" ]
null
null
null
code/com/jivesoftware/os/hwal/permit/src/main/java/com/jivesoftware/os/hwal/permit/PermitProvider.java
jivesoftware/hwal
66f791d2456b1229cdf895d8f4761530a3cb1a7f
[ "Apache-2.0" ]
null
null
null
27.830189
127
0.665085
9,185
package com.jivesoftware.os.hwal.permit; import com.google.common.base.Optional; import java.util.Collection; import java.util.List; public interface PermitProvider { /** * @param tenant * @param permitGroup * @param config * @param count * @return a new permit from the pool of expired or not-yet-issued permits or an empty collection if all permits are taken. */ List<Permit> requestPermit(String tenant, String permitGroup, PermitConfig config, int count); /** * Attempts to renew a permit. * * The original permit should not be used after calling this method. * * @param oldPermits * @return a renewed Permit, or nothing in the case that the Permit was already expired */ List<Optional<Permit>> renewPermit(List<Permit> oldPermits); /** * Releases the provided permit if it is still valid * * @param permits */ void releasePermit(Collection<Permit> permits); /** * Returns the number of distinct permit holders * * @param tenant * @param permitGroup * @param permitConfig * @return */ List<Permit> getAllIssuedPermits(String tenant, String permitGroup, PermitConfig permitConfig); /** * * @param permit if permit is null you will get an Optional.absent(); * @return Optional absent if expired else return provided or a renewed permit. */ Optional<Permit> isExpired(Permit permit); }
3e159f71c0fd7276de48fdfabbedfe54ac900c6e
10,487
java
Java
src/main/java/com/mhschmieder/epstoolkit/dsc/EpsDscUtilities.java
mhschmieder/epstoolkit
ad9b8cf3db9d5f1f45773a9505af4d4108b788ea
[ "MIT" ]
3
2020-08-27T19:02:35.000Z
2022-02-28T07:47:03.000Z
src/main/java/com/mhschmieder/epstoolkit/dsc/EpsDscUtilities.java
mhschmieder/epstoolkit
ad9b8cf3db9d5f1f45773a9505af4d4108b788ea
[ "MIT" ]
null
null
null
src/main/java/com/mhschmieder/epstoolkit/dsc/EpsDscUtilities.java
mhschmieder/epstoolkit
ad9b8cf3db9d5f1f45773a9505af4d4108b788ea
[ "MIT" ]
null
null
null
50.177033
141
0.616859
9,186
/** * MIT License * * Copyright (c) 2020 Mark Schmieder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * This file is part of the EpsToolkit Library * * You should have received a copy of the MIT License along with the * EpsToolkit Library. If not, see <https://opensource.org/licenses/MIT>. * * Project: https://github.com/mhschmieder/epstoolkit */ package com.mhschmieder.epstoolkit.dsc; import java.time.LocalDate; import com.mhschmieder.epstoolkit.EpsVersionInfo; /** * {@code EpsDscUtilities} is a utility class for methods related to Adobe's * Document Structuring Conventions (DSC) Specification, which apply not just to * EPS but also to PDF and related PostScript-derived formats. As such, these * conventions continue to evolve, but have a minimal subset that must be * support by every EPS Document. Specifically, the EPS Document Identification * Comment, and the (older, low-resolution integer-based) Bounding Box Comment. * <p> * Visit the web address below, for the PDF version of the DSC specifications: * <p> * https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/5001.DSC_Spec.pdf * * @version 1.0 * * @author Mark Schmieder */ public final class EpsDscUtilities { /** * The default constructor is disabled, as this is a static utilities class. */ private EpsDscUtilities() {} /** * Static declaration of the specification-compliant EPS Document * Identification Comment for the DSC Header, to avoid programmer error * leading to EPS documents that won't load in downstream applications. */ @SuppressWarnings("nls") public static final String EPS_DOCUMENT_IDENTIFICATION_COMMENT = "%!PS-Adobe-" + EpsDscConstants.DSC_CONFORMANCE_LEVEL + " " + "EPSF-" + EpsDscConstants.EPSF_CONFORMANCE_LEVEL; /** * Static declaration of a default specification-compliant EPS Document * Creator Comment for the DSC Header, to avoid programmer error leading to * EPS documents that won't load in downstream applications. */ @SuppressWarnings("nls") public static final String DEFAULT_DOCUMENT_CREATOR = EpsVersionInfo.LIBRARY_RELEASE_NAME + ", " + EpsVersionInfo.LIBRARY_REPOSITORY_LOCATION; /** * Writes the DSC Header to the specified {@link StringBuilder}. * <p> * Although DSC is also used for PDF and other formats (with significantly * enhanced header options), the only two required fields for EPS are the * line confirming that the file conforms to Version 3 of the EPS format, * and the Bounding Box comment. It is in fact often safer to leave out many * of the other header comments, as not all clients and readers support * them, or do so properly. The ones that are deemed safe are included here. * <p> * We specify 8-Bit Document Data (vs. 7-Bit), because there may be issues * otherwise with Titles and other fields specified in languages other than * English. This of course does not cover 16-Bit and beyond, for Unicode. * <p> * It is up to the caller to ensure that the Bounding Box is positive. * * @param stringBuilder * The {@link StringBuilder} for appending the DSC Header * @param title * The {@link String} to use as the EPS Document's title * @param creator * The {@link String} to use as the EPS Document's creator * @param boundingBoxMinX * The lower left x-coordinate of the bounding box * @param boundingBoxMinY * The lower left y-coordinate of the bounding box * @param boundingBoxMaxX * The upper right x-coordinate of the bounding box * @param boundingBoxMaxY * The upper right y-coordinate of the bounding box * * @since 1.0 */ @SuppressWarnings("nls") public static void writeDscHeader( final StringBuilder stringBuilder, final String title, final String creator, final int boundingBoxMinX, final int boundingBoxMinY, final int boundingBoxMaxX, final int boundingBoxMaxY ) { // Make a default Title if none was provided, or if empty. final String titleVerified = ( ( title == null ) || title.isEmpty() ) ? "The EPS Document" : title; // In case no creator was provided, use this library as the default. // // The Creator comment usually indicates the name of the document // composition software, which must be provided by clients of this // library, but if none is provided, stating this library as the // document's creator is a good fallback vs. leaving it blank. final String creatorVerified = ( ( creator == null ) || creator.isEmpty() ) ? DEFAULT_DOCUMENT_CREATOR : creator; // Grab the current date and time in ISO format so we can extract an // ISO-compatible locale-sensitive date at the level of resolution we // care about, which is probably just to the year/month/day. final LocalDate localDate = LocalDate.now(); final String timeStamp = localDate.toString(); // Convert the Bounding Box to a string representation for the header. final StringBuilder boundingBoxDescriptor = new StringBuilder(); boundingBoxDescriptor.append( Integer.toString( boundingBoxMinX ) ); boundingBoxDescriptor.append( " " ); boundingBoxDescriptor.append( Integer.toString( boundingBoxMinY ) ); boundingBoxDescriptor.append( " " ); boundingBoxDescriptor.append( Integer.toString( boundingBoxMaxX ) ); boundingBoxDescriptor.append( " " ); boundingBoxDescriptor.append( Integer.toString( boundingBoxMaxY ) ); final String boundingBoxLabel = boundingBoxDescriptor.toString(); // Compose the DSC-compliant EPS Header (i.e., with Adobe PostScript // Document Structuring Comments), set to 8-bit characters for UTF-8. // // Not every reader, viewer, or editor client application handles the // Origin comment, but some require it, so it is safest to include the // Origin and to set it to zero vs. allowing the caller to specify a // preferred Page Origin for EPS. Due to low adoption rates however, the // new High Resolution Bounding Box comment is excluded, as EPS requires // the older low resolution integer-based bounding box regardless. // // Although the specifications say to take line width into account and // to adjust the bounding box accordingly, in the context of a generic // toolkit this isn't practical so it is instead advised to be careful // with GUI elements and graphical components that didn't use any insets // or other gaps, as line width won't necessarily be a constant value. final StringBuilder header = new StringBuilder(); header.append( EPS_DOCUMENT_IDENTIFICATION_COMMENT + "\n" ); header.append( "%%Title: " + titleVerified + "\n" ); header.append( "%%Creator: " + creatorVerified + "\n" ); header.append( "%%CreationDate: " + timeStamp + "\n" ); header.append( "%%DocumentData: Clean8Bit\n" ); header.append( "%%DocumentProcessColors: Black\n" ); header.append( "%%ColorUsage: Color\n" ); header.append( "%%LanguageLevel: 2\n" ); header.append( "%%Origin: 0 0\n" ); header.append( "%%Pages: 1\n" ); header.append( "%%Page: 1 1\n" ); header.append( "%%BoundingBox: " + boundingBoxLabel + "\n" ); header.append( "%%EndComments\n" ); header.append( "\n" ); // It is more efficient to compose smaller sections independently before // appending to the main content wrapper. stringBuilder.append( header ); } /** * Writes the DSC Footer to the specified {@link StringBuilder}. * * @param stringBuilder * The {@link StringBuilder} for appending the DSC Footer * * @since 1.0 */ @SuppressWarnings("nls") public static void writeDscFooter( final StringBuilder stringBuilder ) { // Write the DSC-compliant EPS footer (i.e., with Adobe PostScript // Document Structuring Comments); this is mostly just an "EOF" Comment, // as the EPS format is single-page only. stringBuilder.append( "\n" ); stringBuilder.append( "%%EOF" ); } }
3e159f7e490a92f967f091c54c1d8e16400bad67
3,571
java
Java
src/main/java/tools/gcs/PhotoSet.java
gangareddynachu/PhotoPostAdvisior
2bc1b308cdd5d6942422e76883aa3d684728b244
[ "MIT" ]
null
null
null
src/main/java/tools/gcs/PhotoSet.java
gangareddynachu/PhotoPostAdvisior
2bc1b308cdd5d6942422e76883aa3d684728b244
[ "MIT" ]
null
null
null
src/main/java/tools/gcs/PhotoSet.java
gangareddynachu/PhotoPostAdvisior
2bc1b308cdd5d6942422e76883aa3d684728b244
[ "MIT" ]
1
2021-04-30T21:33:29.000Z
2021-04-30T21:33:29.000Z
25.225352
110
0.670296
9,187
package tools.gcs; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; /** * The class of a set of photos, providing some collective information. * * @author Su Yeh-Tarn, upchh@example.com * @since 1.0 */ public class PhotoSet implements Serializable { private static final long serialVersionUID = 8204618349102673081L; private ArrayList<Photo> photos; private HashMap<String, Integer> labelCounts; private HashSet<Label> labelPool; /** * Initiate a photo set with provided photo objects. * * @param photos The photos provided for the set. */ public PhotoSet (ArrayList<Photo> photos) { this.photos = photos; this.labelPool = new HashSet<Label>(); this.labelCounts = new HashMap<String, Integer>(); for (Photo photo : photos) { labelPool.addAll(photo.getLabels()); for (Label label : photo.getLabels()) { String name = label.getName(); Integer count = this.labelCounts.get(name); if (count == null) { this.labelCounts.put(name, 1); } else { this.labelCounts.put(name, count + 1); } } } } /** * Get the label counting results. * * @return The label counting results. */ public Map<String, Integer> getLabelCounts() { return labelCounts; } /** * Return the suggested labels for categorizing. A label is suggested when it has the most common appearance. * * @return An array list of labels. */ public ArrayList<String> suggestedLabels() { HashMap<Integer, ArrayList<String>> fliped = new HashMap<Integer, ArrayList<String>>(); for (Entry<String, Integer> entry : this.labelCounts.entrySet()) { ArrayList<String> labels = (fliped.containsKey(entry.getValue())) ? fliped.get(entry.getValue()) : new ArrayList<String>(); labels.add(entry.getKey()); fliped.put(entry.getValue(), labels); } TreeMap<Integer, ArrayList<String>> sorted = new TreeMap<Integer, ArrayList<String>>(fliped); ArrayList<String> suggested = sorted.entrySet().iterator().next().getValue(); return suggested; } /** * Get the photo objects belonging to this set. * * @return The array list of photos. */ public ArrayList<Photo> getPhotos() { return this.photos; } /** * Get the name of the photo objects belonging to this set. * @return The array list of photo names. */ public ArrayList<String> getPhotoNames() { ArrayList<String> names = new ArrayList<String>(); for (Photo photo : this.photos) { names.add(photo.getName()); } return names; } /** * Get the sum of the like counts of all the belonging photos. * * @return The sum of the like counts. */ public int getTotalLikesCount() { int count = 0; for (Photo photo : this.photos) { count += photo.getLikes(); } return count; } /** * Get the sum of the comment counts of all the belonging photos. * * @return The sum of the comment counts. */ public int getTotalCommentsCount() { int count = 0; for (Photo photo : this.photos) { count += photo.getComments().size(); } return count; } /** * Get the sum of the scores of all the belonging photos. * * @return The sum of the scores. */ public float getTotalScore() { float count = 0; for (Photo photo : this.photos) { count += photo.getScore(); } return count; } /** * Get the amount of the photos. * * @return The amount of the photos */ public int getPhotoAmount() { return this.photos.size(); } }
3e159f912bada503a9bd4847adee899bb7d5548d
5,491
java
Java
modules/activiti5-engine/src/main/java/org/activiti5/engine/impl/asyncexecutor/AsyncJobUtil.java
wjlc/rd-bpm
dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5
[ "Apache-1.1" ]
15
2018-09-06T07:57:49.000Z
2021-02-28T07:40:39.000Z
modules/activiti5-engine/src/main/java/org/activiti5/engine/impl/asyncexecutor/AsyncJobUtil.java
wjlc/rd-bpm
dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5
[ "Apache-1.1" ]
8
2019-11-13T08:32:36.000Z
2022-01-27T16:19:19.000Z
modules/activiti5-engine/src/main/java/org/activiti5/engine/impl/asyncexecutor/AsyncJobUtil.java
wjlc/rd-bpm
dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5
[ "Apache-1.1" ]
16
2018-09-07T07:56:35.000Z
2021-11-12T03:09:18.000Z
43.23622
148
0.70224
9,188
package org.activiti5.engine.impl.asyncexecutor; import org.activiti.engine.delegate.event.ActivitiEventType; import org.activiti5.engine.ActivitiOptimisticLockingException; import org.activiti5.engine.delegate.event.impl.ActivitiEventBuilder; import org.activiti5.engine.impl.cmd.ExecuteAsyncJobCmd; import org.activiti5.engine.impl.cmd.LockExclusiveJobCmd; import org.activiti5.engine.impl.cmd.UnlockExclusiveJobCmd; import org.activiti5.engine.impl.context.Context; import org.activiti5.engine.impl.interceptor.Command; import org.activiti5.engine.impl.interceptor.CommandConfig; import org.activiti5.engine.impl.interceptor.CommandContext; import org.activiti5.engine.impl.interceptor.CommandExecutor; import org.activiti5.engine.impl.jobexecutor.FailedJobCommandFactory; import org.activiti5.engine.impl.persistence.entity.JobEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AsyncJobUtil { private static Logger log = LoggerFactory.getLogger(AsyncJobUtil.class); public static void executeJob(final JobEntity job, final CommandExecutor commandExecutor) { try { if (job.isExclusive()) { commandExecutor.execute(new LockExclusiveJobCmd(job)); } } catch (Throwable lockException) { if (log.isDebugEnabled()) { log.debug("Could not lock exclusive job. Unlocking job so it can be acquired again. Catched exception: " + lockException.getMessage()); } unacquireJob(commandExecutor, job); return; } try { commandExecutor.execute(new ExecuteAsyncJobCmd(job)); } catch (final ActivitiOptimisticLockingException e) { handleFailedJob(job, e, commandExecutor); if (log.isDebugEnabled()) { log.debug("Optimistic locking exception during job execution. If you have multiple async executors running against the same database, " + "this exception means that this thread tried to acquire an exclusive job, which already was changed by another async executor thread." + "This is expected behavior in a clustered environment. " + "You can ignore this message if you indeed have multiple job executor threads running against the same database. " + "Exception message: {}", e.getMessage()); } } catch (Throwable exception) { handleFailedJob(job, exception, commandExecutor); // Finally, Throw the exception to indicate the ExecuteAsyncJobCmd failed String message = "Job " + job.getId() + " failed"; log.error(message, exception); } try { if (job.isExclusive()) { commandExecutor.execute(new UnlockExclusiveJobCmd(job)); } } catch (ActivitiOptimisticLockingException optimisticLockingException) { if (log.isDebugEnabled()) { log.debug("Optimistic locking exception while unlocking the job. If you have multiple async executors running against the same database, " + "this exception means that this thread tried to acquire an exclusive job, which already was changed by another async executor thread." + "This is expected behavior in a clustered environment. " + "You can ignore this message if you indeed have multiple job executor acquisition threads running against the same database. " + "Exception message: {}", optimisticLockingException.getMessage()); } return; } catch (Throwable t) { log.error("Error while unlocking exclusive job " + job.getId(), t); return; } } protected static void unacquireJob(final CommandExecutor commandExecutor, final JobEntity job) { CommandContext commandContext = Context.getCommandContext(); if (commandContext != null) { commandContext.getJobEntityManager().unacquireJob(job.getId()); } else { commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { commandContext.getJobEntityManager().unacquireJob(job.getId()); return null; } }); } } public static void handleFailedJob(final JobEntity job, final Throwable exception, final CommandExecutor commandExecutor) { commandExecutor.execute(new Command<Void>() { @Override public Void execute(CommandContext commandContext) { CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew(); FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory(); Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), exception); log.trace("Using FailedJobCommandFactory '" + failedJobCommandFactory.getClass() + "' and command of type '" + cmd.getClass() + "'"); commandExecutor.execute(commandConfig, cmd); // Dispatch an event, indicating job execution failed in a try-catch block, to prevent the original // exception to be swallowed if (commandContext.getEventDispatcher().isEnabled()) { try { commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityExceptionEvent( ActivitiEventType.JOB_EXECUTION_FAILURE, job, exception)); } catch(Throwable ignore) { log.warn("Exception occured while dispatching job failure event, ignoring.", ignore); } } return null; } }); } }
3e15a046b5ff4fc4e8992bcf7b09c22ad012682a
1,555
java
Java
server-core/engine/src/main/java/io/infectnet/server/engine/content/type/NestTypeComponent.java
infectnet/infectnet-server
470f12c90e0f501c1f6754487b696e430b5f89f4
[ "Apache-2.0" ]
2
2016-09-25T14:31:43.000Z
2016-10-17T20:32:32.000Z
server-core/engine/src/main/java/io/infectnet/server/engine/content/type/NestTypeComponent.java
terrifictrio/game-server
470f12c90e0f501c1f6754487b696e430b5f89f4
[ "Apache-2.0" ]
64
2016-09-26T15:45:15.000Z
2016-12-06T13:03:45.000Z
server-core/engine/src/main/java/io/infectnet/server/engine/content/type/NestTypeComponent.java
terrifictrio/game-server
470f12c90e0f501c1f6754487b696e430b5f89f4
[ "Apache-2.0" ]
null
null
null
36.162791
79
0.780064
9,189
package io.infectnet.server.engine.content.type; import io.infectnet.server.engine.core.entity.Category; import io.infectnet.server.engine.core.entity.Entity; import io.infectnet.server.engine.core.entity.component.CostComponent; import io.infectnet.server.engine.core.entity.component.HealthComponent; import io.infectnet.server.engine.core.entity.component.NullInventoryComponent; import io.infectnet.server.engine.core.entity.component.OwnerComponent; import io.infectnet.server.engine.core.entity.component.PositionComponent; import io.infectnet.server.engine.core.entity.component.TypeComponent; import io.infectnet.server.engine.core.entity.component.ViewComponent; public class NestTypeComponent extends TypeComponent { public static final String TYPE_NAME = "Nest"; private static final int INITIAL_HEALTH = 150; private static final int VIEW_RADIUS = 10; private static final int BOOT_COST = 100; private final CostComponent costComponent; public NestTypeComponent() { super(Category.BUILDING, TYPE_NAME); this.costComponent = new CostComponent(BOOT_COST); } @Override public Entity createEntityOfType() { return Entity.builder() .typeComponent(this) .ownerComponent(new OwnerComponent()) .healthComponent(new HealthComponent(INITIAL_HEALTH)) .positionComponent(new PositionComponent()) .viewComponent(new ViewComponent(VIEW_RADIUS)) .inventoryComponent(NullInventoryComponent.getInstance()) .costComponent(this.costComponent) .build(); } }
3e15a16f12906a6ab34905933cee9b814286c27f
1,613
java
Java
chapter_001/src/test/java/ru/job4j/list/ContainerOnLinkListTest.java
Suykum/junior_level
5c6e795dc16bdae49568ff30fbd2b48ac496906b
[ "Apache-2.0" ]
null
null
null
chapter_001/src/test/java/ru/job4j/list/ContainerOnLinkListTest.java
Suykum/junior_level
5c6e795dc16bdae49568ff30fbd2b48ac496906b
[ "Apache-2.0" ]
null
null
null
chapter_001/src/test/java/ru/job4j/list/ContainerOnLinkListTest.java
Suykum/junior_level
5c6e795dc16bdae49568ff30fbd2b48ac496906b
[ "Apache-2.0" ]
null
null
null
27.338983
59
0.644141
9,190
package ru.job4j.list; import org.junit.Test; import org.junit.Before; import java.util.ConcurrentModificationException; import java.util.Iterator; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class ContainerOnLinkListTest { private ContainerOnLinkList<Integer> container; @Before public void beforeTest() { container = new ContainerOnLinkList<>(); container.addFirst(1); container.addFirst(2); container.addFirst(3); } @Test public void whenAddNode() { assertThat(container.get(1), is(2)); } @Test public void whenDeleteNode() { assertThat(container.deleteFirst(), is(3)); } @Test public void whenHasNextTrue() { Iterator<Integer> iterator = container.iterator(); iterator.next(); assertThat(iterator.hasNext(), is(true)); } @Test public void whenHasNextFalse() { Iterator<Integer> iterator = container.iterator(); iterator.next(); iterator.next(); iterator.next(); assertThat(iterator.hasNext(), is(false)); } @Test public void whenGettingNextElement() { Iterator<Integer> iterator = container.iterator(); iterator.next(); iterator.next(); Integer result = iterator.next(); assertThat(result, is(1)); } @Test(expected = ConcurrentModificationException.class) public void whenIteratorThrowException() { Iterator<Integer> iterator = container.iterator(); container.addFirst(5); iterator.next(); } }
3e15a1abbbf059f14db965032a8513d25dad3941
2,189
java
Java
src/main/java/com/taobao/common/tfs/packet/UnlinkFileMessage.java
coraldane/tfs-java-client
05080d3dd709dff8aa96a9b2c5942beb64793650
[ "Apache-2.0" ]
null
null
null
src/main/java/com/taobao/common/tfs/packet/UnlinkFileMessage.java
coraldane/tfs-java-client
05080d3dd709dff8aa96a9b2c5942beb64793650
[ "Apache-2.0" ]
null
null
null
src/main/java/com/taobao/common/tfs/packet/UnlinkFileMessage.java
coraldane/tfs-java-client
05080d3dd709dff8aa96a9b2c5942beb64793650
[ "Apache-2.0" ]
null
null
null
25.453488
83
0.666514
9,191
/* * (C) 2007-2010 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ package com.taobao.common.tfs.packet; import com.taobao.common.tfs.etc.TfsConstant; public class UnlinkFileMessage extends BasePacket { public static final int DELETE = 0x0; public static final int UNDELETE = 0x2; public static final int CONCEAL = 0x4; public static final int REVEAL = 0x6; private int blockId; private long fileId; private int isServer; private int optionFlag; private DsListWrapper dsListWrapper; public UnlinkFileMessage(Transcoder transcoder) { super(transcoder); this.pcode = TfsConstant.UNLINK_FILE_MESSAGE; } public int getBlockId() { return blockId; } public void setBlockId(int blockId) { this.blockId = blockId; } public long getFileId() { return fileId; } public void setFileId(long fileId) { this.fileId = fileId; } public int getOptionFlag() { return optionFlag; } public void setOptionFlag(int optionFlag) { this.optionFlag = optionFlag; } public DsListWrapper getDsListWrapper() { return dsListWrapper; } public void setDsListWrapper(DsListWrapper dsListWrapper) { this.dsListWrapper = dsListWrapper; } public void setDel() { this.isServer |= DELETE;} public void setUndel() { this.isServer |= UNDELETE; } public void setConceal() { this.isServer |= CONCEAL; } public void setReveal() { this.isServer |= REVEAL; } public void setUnlinkType(int action) { this.isServer |= action; } @Override public int getPacketLength() { return (Integer.SIZE/8) * 3 + (Long.SIZE/8) + dsListWrapper.streamLength(); } @Override public void writePacketStream() { byteBuffer.putInt(blockId); byteBuffer.putLong(fileId); byteBuffer.putInt(isServer); this.dsListWrapper.writeToStream(byteBuffer); byteBuffer.putInt(optionFlag); } }
3e15a1bfd7bfa1e65e414096f90712c8dddfc20f
244
java
Java
spherical/src/main/java/com/telenav/spherical/model/RotateInertia.java
openstreetcam/android
66eb0ee1ab093562e2867087084b26803fe58174
[ "MIT" ]
71
2017-01-15T07:52:21.000Z
2020-11-24T11:15:21.000Z
spherical/src/main/java/com/telenav/spherical/model/RotateInertia.java
openstreetcam/android
66eb0ee1ab093562e2867087084b26803fe58174
[ "MIT" ]
104
2017-01-06T18:22:47.000Z
2020-11-23T00:12:59.000Z
spherical/src/main/java/com/telenav/spherical/model/RotateInertia.java
openstreetcam/android
66eb0ee1ab093562e2867087084b26803fe58174
[ "MIT" ]
21
2017-01-20T20:20:04.000Z
2020-11-21T07:28:33.000Z
12.842105
36
0.512295
9,192
package com.telenav.spherical.model; /** * Indicates the rotation inertia */ public enum RotateInertia { /** * none */ INERTIA_0, /** * weak */ INERTIA_50, /** * strong */ INERTIA_100,; }
3e15a32755f47e414db56da71c9cd2634a7e6ac7
3,073
java
Java
esykart-service/merchant-service/src/main/java/com/webientsoft/esykart/user/entity/Menu.java
sumit4myself/Esykart
2dc9e779a90c62e9a22be78669826c38ad2f094f
[ "CC0-1.0" ]
null
null
null
esykart-service/merchant-service/src/main/java/com/webientsoft/esykart/user/entity/Menu.java
sumit4myself/Esykart
2dc9e779a90c62e9a22be78669826c38ad2f094f
[ "CC0-1.0" ]
null
null
null
esykart-service/merchant-service/src/main/java/com/webientsoft/esykart/user/entity/Menu.java
sumit4myself/Esykart
2dc9e779a90c62e9a22be78669826c38ad2f094f
[ "CC0-1.0" ]
null
null
null
19.698718
90
0.704849
9,193
package com.webientsoft.esykart.user.entity; /* * Copyright (c) 2015, WebientSoft and/or its affiliates. All rights reserved. WebientSoft * PROPRIETARY/CONFIDENTIAL.Use is subject to license terms. */ import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonProperty; /** * The entity Class of core.module table. * * @author SumitS2 * @version 1.0 * @since 1.0 */ @Entity @Table(name = "menu") public class Menu implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "menu_id") private Integer menuId; @Column(name = "title", nullable = false) private String title; @Column(name = "icon") private String icon; @Column(name = "link") private String link; @Column(name = "sort_index", nullable = false) private int sortIndex; @JoinColumn(name = "menu_id", referencedColumnName = "menu_id") @OneToMany private Set<Permission> permissions; @JsonProperty("submenu") @OneToMany(mappedBy = "parentMenu",cascade = CascadeType.ALL) private Set<Menu> subMenus; @JoinColumn(name = "parent_id") @ManyToOne() private Menu parentMenu; public Menu() { } public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public int getSortIndex() { return sortIndex; } public void setSortIndex(int sortIndex) { this.sortIndex = sortIndex; } public Set<Permission> getPermissions() { return permissions; } public void setPermissions(Set<Permission> permissions) { this.permissions = permissions; } public Set<Menu> getSubMenus() { return subMenus; } public void setSubMenus(Set<Menu> subMenus) { this.subMenus = subMenus; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((menuId == null) ? 0 : menuId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Menu other = (Menu) obj; if (menuId == null) { if (other.menuId != null) return false; } else if (!menuId.equals(other.menuId)) return false; return true; } @Override public String toString() { return "Menu [title=" + title + ", link=" + link + "]"; } }
3e15a3de35e67357088a49b2503204c142a259fc
1,149
java
Java
src/test/java/ESAJDadosProcessoTest.java
rafagonc/tjdata
5c05f0d6ff39e5b961eaa4fe15241a4e2d95f629
[ "MIT" ]
1
2018-10-23T15:10:41.000Z
2018-10-23T15:10:41.000Z
src/test/java/ESAJDadosProcessoTest.java
rafagonc/tjdata
5c05f0d6ff39e5b961eaa4fe15241a4e2d95f629
[ "MIT" ]
null
null
null
src/test/java/ESAJDadosProcessoTest.java
rafagonc/tjdata
5c05f0d6ff39e5b961eaa4fe15241a4e2d95f629
[ "MIT" ]
null
null
null
22.096154
66
0.679721
9,194
import br.com.rafagonc.tjdata.database.ESAJDatabase; import br.com.rafagonc.tjdata.database.ESAJDatabaseManager; import br.com.rafagonc.tjdata.models.ESAJDadosProcesso; import org.hibernate.Transaction; import org.junit.Before; /** * Created by rafagonc on 15/07/17. */ public class ESAJDadosProcessoTest { private ESAJDatabase db; private ESAJDatabaseManager manager; @Before public void setUp() throws Exception { manager = ESAJDatabaseManager.share(); db = manager.getDatabase(); } @org.junit.Test public void testCreate() throws Exception { create(); } @org.junit.Test public void testDelete() throws Exception { ESAJDadosProcesso dadosProcesso = create(); Transaction t = manager.begin(); db.getDadosProcessoRepository().delete(dadosProcesso); t.commit(); } private ESAJDadosProcesso create() { Transaction t = manager.begin(); ESAJDadosProcesso dadosProcesso = new ESAJDadosProcesso(); db.getDadosProcessoRepository().save(dadosProcesso); t.commit(); return dadosProcesso; } }
3e15a4493d0aa09dd013bb322726ce1a4b783490
3,804
java
Java
activemq-ra/src/test/java/org/apache/activemq/ra/ActiveMQConnectionFactoryTest.java
august-Liu/activemq
8af1df7aea024753d2dded503c2eb8fea0488be1
[ "Apache-2.0" ]
1
2015-02-05T06:01:50.000Z
2015-02-05T06:01:50.000Z
activemq-ra/src/test/java/org/apache/activemq/ra/ActiveMQConnectionFactoryTest.java
august-Liu/activemq
8af1df7aea024753d2dded503c2eb8fea0488be1
[ "Apache-2.0" ]
null
null
null
activemq-ra/src/test/java/org/apache/activemq/ra/ActiveMQConnectionFactoryTest.java
august-Liu/activemq
8af1df7aea024753d2dded503c2eb8fea0488be1
[ "Apache-2.0" ]
null
null
null
34.899083
139
0.714248
9,195
/* * Copyright 2008 hak8fe. * * 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. * under the License. */ package org.apache.activemq.ra; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Timer; import javax.jms.Connection; import javax.jms.Session; import javax.jms.TopicSubscriber; import javax.resource.spi.BootstrapContext; import javax.resource.spi.UnavailableException; import javax.resource.spi.XATerminator; import javax.resource.spi.work.WorkManager; import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQTopicSubscriber; /** * * @author hak8fe */ public class ActiveMQConnectionFactoryTest extends TestCase { ActiveMQManagedConnectionFactory mcf; ActiveMQConnectionRequestInfo info; String url = "vm://localhost"; String user = "defaultUser"; String pwd = "defaultPasswd"; public ActiveMQConnectionFactoryTest(String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); mcf = new ActiveMQManagedConnectionFactory(); info = new ActiveMQConnectionRequestInfo(); info.setServerUrl(url); info.setUserName(user); info.setPassword(pwd); info.setAllPrefetchValues(new Integer(100)); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testSerializability() throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(mcf, new ConnectionManagerAdapter(), info); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(factory); oos.close(); byte[] byteArray = bos.toByteArray(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArray)); ActiveMQConnectionFactory deserializedFactory = (ActiveMQConnectionFactory) ois.readObject(); ois.close(); Connection con = deserializedFactory.createConnection("defaultUser", "defaultPassword"); ActiveMQConnection connection = ((ActiveMQConnection)((ManagedConnectionProxy)con).getManagedConnection().getPhysicalConnection()); assertEquals(100, connection.getPrefetchPolicy().getQueuePrefetch()); assertNotNull("Connection object returned by ActiveMQConnectionFactory.createConnection() is null", con); } public void testOptimizeDurablePrefetch() throws Exception { ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter(); ra.setServerUrl(url); ra.setUserName(user); ra.setPassword(pwd); ra.setOptimizeDurableTopicPrefetch(0); ra.setDurableTopicPrefetch(0); Connection con = ra.makeConnection(); con.setClientID("x"); Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); TopicSubscriber sub = sess.createDurableSubscriber(sess.createTopic("TEST"), "x"); con.start(); assertEquals(0, ((ActiveMQTopicSubscriber)sub).getPrefetchNumber()); } }
3e15a537036f311c7af34131ea837169c4ade818
1,794
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/W_Menu_OpMode.java
Team9019/2016-17
821d9d1d5a6c553a5077c59193885ff556994a42
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/W_Menu_OpMode.java
Team9019/2016-17
821d9d1d5a6c553a5077c59193885ff556994a42
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/W_Menu_OpMode.java
Team9019/2016-17
821d9d1d5a6c553a5077c59193885ff556994a42
[ "MIT" ]
null
null
null
32.035714
106
0.641026
9,196
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.ElapsedTime; @TeleOp(name = "Config Menu", group = "Utilities") //@Disabled public class W_Menu_OpMode extends OpMode { //Establish sub-classes with Constructor call Menu_Commands menu =new Menu_Commands(this); private ElapsedTime runtime = new ElapsedTime(); private int TimeDebugSleep = 0; @Override public void init() { //read values from file menu.ReadFile();//this); runtime.reset(); //Display file values to the driver while (runtime.seconds() < 2) { telemetry.addData("Read from File:", menu.param.colorAlliance + " Alliance"); telemetry.addData("Read from File:", menu.param.autonType + " Starting Position"); telemetry.addData("Read from File:", Integer.toString(menu.param.delayInSec) + " Sec. Delay"); telemetry.addData("Read from File:", menu.param.testList + " Test"); telemetry.update(); } } @Override public void init_loop() { //Collect new settings from driver menu.CollectNew(); } @Override public void loop() { //Show menu settings to driver telemetry.addData("Set on Menu:", menu.param.colorAlliance + " Alliance"); telemetry.addData("Set on Menu:", menu.param.autonType + " Starting Position"); telemetry.addData("Set on Menu:", Integer.toString(menu.param.delayInSec) + " Sec. Delay"); telemetry.addData("Set on Menu:", menu.param.testList + " Test"); telemetry.addData("DONE", "Press STOP to close."); telemetry.update(); } }
3e15a7021318dc23acc998fb8ac9ff2ba209bfe9
3,092
java
Java
src/test/java/org/alfresco/event/gateway/config/amqp/ActiveMQTest.java
asksasasa83/alfresco-event-gateway
7516bff49aeb0242592595fa185656bd216b729a
[ "Apache-2.0" ]
1
2021-05-25T13:59:35.000Z
2021-05-25T13:59:35.000Z
src/test/java/org/alfresco/event/gateway/config/amqp/ActiveMQTest.java
asksasasa83/alfresco-event-gateway
7516bff49aeb0242592595fa185656bd216b729a
[ "Apache-2.0" ]
null
null
null
src/test/java/org/alfresco/event/gateway/config/amqp/ActiveMQTest.java
asksasasa83/alfresco-event-gateway
7516bff49aeb0242592595fa185656bd216b729a
[ "Apache-2.0" ]
null
null
null
38.17284
111
0.740298
9,197
/* * Copyright 2018 Alfresco Software, 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 org.alfresco.event.gateway.config.amqp; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.alfresco.event.gateway.AbstractCamelMockTest; import org.alfresco.event.gateway.config.ToRouteProperties; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; /** * @author Jamal Kaabi-Mofrad */ @ActiveProfiles("mock_from_activemq_to_activemq") public class ActiveMQTest extends AbstractCamelMockTest { private static final String SOURCE_TOPIC_NAME = "start"; private static final String TARGET_ALL_EVENTS_TOPIC_NAME = "alfresco.events.target.activemq.testAllEvents"; @Autowired private AmqpFromProperties fromProperties; @Autowired private AmqpToProperties toProperties; @Test public void testAmqpFromProperties() { assertAmqpFromProperties(fromProperties); } @Test public void testAmqpToProperties() { assertEquals("localhost", toProperties.getHost()); assertEquals(5672, toProperties.getPort()); assertEquals("localhost:5672", toProperties.getAddresses()); assertEquals("amqp://" + toProperties.getAddresses(), toProperties.getUrl()); assertNull(toProperties.getUsername()); assertNull(toProperties.getPassword()); assertNotNull(toProperties.getToRoute()); assertEquals(TARGET_ALL_EVENTS_TOPIC_NAME, toProperties.getToRoute().getTopicName()); assertEquals("mock:" + TARGET_ALL_EVENTS_TOPIC_NAME, toProperties.getToRoute().getUri()); } @Override protected ToRouteProperties getToRoute() { return toProperties.getToRoute(); } public static void assertAmqpFromProperties(AmqpFromProperties fromProperties) { assertEquals("localhost", fromProperties.getHost()); assertEquals(5672, fromProperties.getPort()); assertEquals("localhost:5672", fromProperties.getAddresses()); assertEquals("amqp://" + fromProperties.getAddresses(), fromProperties.getUrl()); assertNull(fromProperties.getUsername()); assertNull(fromProperties.getPassword()); assertNotNull(fromProperties.getFromRoute()); assertEquals(SOURCE_TOPIC_NAME, fromProperties.getFromRoute().getTopicName()); assertEquals("direct:" + SOURCE_TOPIC_NAME, fromProperties.getFromRoute().getUri()); } }
3e15a7481ef3ee0eaeef08dc242fbafdeeb72fca
6,350
java
Java
app/src/main/java/no/uio/gardir/leavingearthoutcome/adapters/NewResearchAdapter.java
gardir/LeavingEarthOutcome
eba40f7a46440489abdc155914308fa45ad6208d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/no/uio/gardir/leavingearthoutcome/adapters/NewResearchAdapter.java
gardir/LeavingEarthOutcome
eba40f7a46440489abdc155914308fa45ad6208d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/no/uio/gardir/leavingearthoutcome/adapters/NewResearchAdapter.java
gardir/LeavingEarthOutcome
eba40f7a46440489abdc155914308fa45ad6208d
[ "Apache-2.0" ]
null
null
null
37.797619
111
0.552598
9,198
package no.uio.gardir.leavingearthoutcome.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.LinkedList; import no.uio.gardir.leavingearthoutcome.MainMenu; import no.uio.gardir.leavingearthoutcome.activities.NewResearchActivity; import no.uio.gardir.leavingearthoutcome.engine.Player; import no.uio.gardir.leavingearthoutcome.engine.Research; /** * Created by gardir on 20.10.16. */ public class NewResearchAdapter extends BaseAdapter { private Context mContext; private int dpWidth = MainMenu.toDP(317), dpHeight = MainMenu.toDP(206); private LinkedList<Research.ResearchType> researches = Research.getAvailableResearches(Player.getPlayer()); public NewResearchAdapter(Context c) { this.mContext = c; } @Override public int getCount() { if ( NewResearchActivity.dynamic ) { return NewResearchActivity.getCOUNT(); } else { return 12; } } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if ( NewResearchActivity.dynamic ) { return createDynamicImageView( position, convertView, parent ); } else { return createStaticImageView( position, convertView, parent ); } } public View createStaticImageView( final int position, View convertView, ViewGroup parent ) { View view = null; boolean imageSet = false; for ( final Research.ResearchType r : researches ) { if (r.ordinal() == position) { imageSet = true; if (convertView == null || !(view instanceof ImageView)) { view = new ImageView(mContext); } else { view = convertView; } // Used to set width/height according to how many others there is int maxWidth = Math.round(dpWidth / (float) 4), maxHeight = Math.round( dpHeight / (float) 3); /*((ImageView) view).setImageResource( MainMenu.imageResIds.get(r)*/ ((ImageView) view).setImageBitmap( MainMenu.decodeSampledBitmapFromResource( mContext.getResources(), MainMenu.imageResIds.get(r), maxWidth, maxHeight) ); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String clickedResearch = String.format("%d", position + 1); Research.giveResearch(Player.getPlayer(), clickedResearch); NewResearchActivity.calcCOUNT(); NewResearchAdapter.this.notifyDataSetChanged(); researches.remove(r); } }); ((ImageView)view).setAdjustViewBounds(true); } } if ( !imageSet ) { // No more researches view = new TextView(mContext); if ( NewResearchActivity.getCOUNT() == 0 ) { ((TextView) view).setText("No more researches"); } else { ((TextView) view).setText("Researched"); } } return view; } public View createDynamicImageView(final int position, View convertView, ViewGroup parent) { View view; int count = NewResearchActivity.getCOUNT(); if ( count > 0) { if ( convertView == null ) { view = new ImageView(mContext); } else { view = convertView; } // Used to set width/height according to how many others there is int maxWidth = count > 4 ? dpWidth/4 : dpWidth/count; int maxHeight = count % 4 == 0 ? dpHeight / (count/4) : dpHeight / ((count/4)+1); ((ImageView)view).setImageBitmap( MainMenu.decodeSampledBitmapFromResource( mContext.getResources(), MainMenu.imageResIds.get(researches.get(position)), maxWidth, maxHeight)); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String clickedResearch = String.format("%d", position + 1); Research.giveResearch(Player.getPlayer(), clickedResearch); researches.remove(position); NewResearchActivity.calcCOUNT(); NewResearchAdapter.this.notifyDataSetChanged(); } }); ((ImageView)view).setAdjustViewBounds(true); } else { if ( convertView == null ) { view = new TextView(mContext); } else { view = convertView; } ((TextView)view).setText("No more researches"); } return view; } private View createTextView( final int position, View convertView, View parent ) { TextView textView; if ( convertView == null ) { textView = new TextView(mContext); } else { textView = (TextView) convertView; } if ( researches.size() > 0 ) { textView.setText( researches.get( position ).toString() ); } else { textView.setText("No more researches"); } textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String clickedResearch = String.format("%d", position+1); Research.giveResearch(Player.getPlayer(), clickedResearch); researches.remove(position); NewResearchAdapter.this.notifyDataSetChanged(); } }); return textView; } }
3e15a8bb30c2ae10a097d0f52f17ed369063384d
309
java
Java
app/src/main/java/com/example/aw/conversion/VideoCompressionCallback.java
ash-mega/conversion
1fb97370554fd29513acfc5332e9f2a96cc42f50
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/aw/conversion/VideoCompressionCallback.java
ash-mega/conversion
1fb97370554fd29513acfc5332e9f2a96cc42f50
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/aw/conversion/VideoCompressionCallback.java
ash-mega/conversion
1fb97370554fd29513acfc5332e9f2a96cc42f50
[ "Apache-2.0" ]
null
null
null
23.769231
74
0.779935
9,199
package com.example.aw.conversion; public interface VideoCompressionCallback { void onCompressUpdateProgress(int progress,String currentIndexString); void onCompressSuccessful(String path); void onCompressFailed(String path); void onCompressFinished(String currentIndexString); }
3e15abb766e7709643e4fadc3b91e157533ca666
4,090
java
Java
app/src/main/java/org/gdg/frisbee/android/api/GapiOkHttpRequest.java
CesarNog/frisbee
1e6a320bb58416f5df64e0ea79c2a4f0b7bd6031
[ "Apache-2.0" ]
3
2015-05-29T06:15:26.000Z
2021-12-15T15:19:48.000Z
app/src/main/java/org/gdg/frisbee/android/api/GapiOkHttpRequest.java
CesarNog/frisbee
1e6a320bb58416f5df64e0ea79c2a4f0b7bd6031
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/gdg/frisbee/android/api/GapiOkHttpRequest.java
CesarNog/frisbee
1e6a320bb58416f5df64e0ea79c2a4f0b7bd6031
[ "Apache-2.0" ]
null
null
null
39.708738
113
0.610269
9,200
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.gdg.frisbee.android.api; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.util.Preconditions; import org.gdg.frisbee.android.app.App; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; public class GapiOkHttpRequest extends LowLevelHttpRequest { private final HttpURLConnection connection; /** * @param connection HTTP URL connection */ GapiOkHttpRequest(HttpURLConnection connection) { this.connection = connection; connection.setInstanceFollowRedirects(true); } @Override public void addHeader(String name, String value) { connection.addRequestProperty(name, value); } @Override public void setTimeout(int connectTimeout, int readTimeout) { connection.setReadTimeout(readTimeout); connection.setConnectTimeout(connectTimeout); } @Override public LowLevelHttpResponse execute() throws IOException { HttpURLConnection connection = this.connection; long startTime = System.currentTimeMillis(); // write content if (getStreamingContent() != null) { String contentType = getContentType(); if (contentType != null) { addHeader("Content-Type", contentType); } String contentEncoding = getContentEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); } long contentLength = getContentLength(); if (contentLength >= 0) { addHeader("Content-Length", Long.toString(contentLength)); } String requestMethod = connection.getRequestMethod(); if ("POST".equals(requestMethod) || "PUT".equals(requestMethod)) { connection.setDoOutput(true); // see http://developer.android.com/reference/java/net/HttpURLConnection.html if (contentLength >= 0 && contentLength <= Integer.MAX_VALUE) { connection.setFixedLengthStreamingMode((int) contentLength); } else { connection.setChunkedStreamingMode(0); } OutputStream out = connection.getOutputStream(); try { getStreamingContent().writeTo(out); } finally { out.close(); } } else { // cannot call setDoOutput(true) because it would change a GET method to POST // for HEAD, OPTIONS, DELETE, or TRACE it would throw an exceptions Preconditions.checkArgument( contentLength == 0, "%s with non-zero content length is not supported", requestMethod); } } // connect boolean successfulConnection = false; try { connection.connect(); GapiOkResponse response = new GapiOkResponse(connection); successfulConnection = true; App.getInstance().getTracker().sendTiming("net",System.currentTimeMillis()-startTime, "gapi", null); return response; } finally { if (!successfulConnection) { connection.disconnect(); } } } }
3e15ad6b7f77a86b3c3dfa45a3cfcd615c3c3a94
5,878
java
Java
src/main/java/org/dmc/solr/SolrUtils.java
dmc-uilabs/dmcrest
531ae72c1fa60299bc5b45622f396af178da503e
[ "MIT" ]
1
2017-07-12T20:20:52.000Z
2017-07-12T20:20:52.000Z
src/main/java/org/dmc/solr/SolrUtils.java
dmc-uilabs/dmcrest
531ae72c1fa60299bc5b45622f396af178da503e
[ "MIT" ]
18
2017-03-31T16:36:11.000Z
2017-09-29T20:14:40.000Z
src/main/java/org/dmc/solr/SolrUtils.java
dmc-uilabs/dmcrest
531ae72c1fa60299bc5b45622f396af178da503e
[ "MIT" ]
1
2017-09-21T01:04:31.000Z
2017-09-21T01:04:31.000Z
31.265957
100
0.600204
9,201
package org.dmc.solr; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import org.dmc.services.Config; import org.dmc.services.ServiceLogger; import org.dmc.services.search.SearchException; import org.dmc.services.search.SearchQueueImpl; /** * Created by 200005921 on 1/13/2016. */ public class SolrUtils { private static final String logTag = SolrUtils.class.getName(); //public static String BASE_URL = "http://52.24.49.48:8983/solr/"; public static String FULL_IMPORT = "dataimport?command=full-import&clean=true"; public static final String CORE_GFORGE_COMPANIES = "gforge_companies"; public static final String CORE_GFORGE_COMPONENTS = "gforge_components"; public static final String CORE_GFORGE_PROJECTS = "gforge_projects"; public static final String CORE_GFORGE_SERVICES = "gforge_services"; public static final String CORE_GFORGE_USERS = "gforge_users"; public static final String CORE_GFORGE_WIKI = "gforge_wiki"; public static final String Q_ALL_FIELDS = "*"; // http://52.88.250.74:8983/solr/gforge_users/dataimport?command=full-import&clean=true private static String baseUrl; static { baseUrl = System.getenv("SOLR_BASE_URL"); } public static String getBaseUrl () { return baseUrl; } public static String invokeFulIndexingComponents () throws IOException { return invokeFullIndexing(baseUrl, CORE_GFORGE_COMPONENTS); } public static String invokeFulIndexingProjects () throws IOException { return invokeFullIndexing(baseUrl, CORE_GFORGE_PROJECTS); } public static String invokeFulIndexingServices () throws IOException { return invokeFullIndexing(baseUrl, CORE_GFORGE_SERVICES); } public static String invokeFulIndexingUsers () throws IOException { return invokeFullIndexing(baseUrl, CORE_GFORGE_USERS); } public static String invokeFulIndexingWiki () throws IOException { return invokeFullIndexing(baseUrl, CORE_GFORGE_WIKI); } public static String invokeFullIndexing (String baseUrl, String coreName) throws IOException { String url = baseUrl + coreName + "/" + FULL_IMPORT; CloseableHttpClient httpClient; CloseableHttpResponse response = null; httpClient = HttpClients.createDefault(); ServiceLogger.log(logTag, "Triggering SOLR: " + url); HttpGet httpGet = new HttpGet(url); String responseText = null; try { response = httpClient.execute(httpGet); responseText = getResponseContent(response.getEntity()); } catch (IOException e) { e.printStackTrace(); throw new IOException(e.toString()); } return responseText; } public static String getResponseContent (HttpEntity entity) throws IOException { String response = null; if (entity != null) { InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(entity.getContent()); br = new BufferedReader(isr); StringBuilder out = new StringBuilder(); String line; while ((line = br.readLine()) != null) { out.append(line); } response = out.toString(); } catch (IOException ioE) { throw new IOException("Error reading response: " + ioE.toString()); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { } isr = null; } } } return response; } public static String convertToSolrQuery (String query, List<String> fields) { String solrQuery = query; if (query != null) { if (fields != null) { solrQuery = ""; for (int i=0; i < fields.size(); i++) { if (i > 0) solrQuery += " OR "; //String Q = fields.get(i) + ":" + "\"" + query + "\""; String Q = fields.get(i) + ":" + query; solrQuery += Q; } } else { } } else { solrQuery = "*:*"; } return solrQuery; } /** * * Trigger full indexing of solr by inserting a message into the SEARCH_QUEUE * Call this function in DAOs whenever data is updated * * @param solrCoreName Specifies the name of the core to re-index * SolrUtils.CORE_GFORGE_COMPANIES * SolrUtils.CORE_GFORGE_COMPONENTS * SolrUtils.CORE_GFORGE_PROJECTS * SolrUtils.CORE_GFORGE_SERVICES * SolrUtils.CORE_GFORGE_USERS * SolrUtils.CORE_GFORGE_WIKI * */ public static void triggerFullIndexing (String solrCoreName) throws SearchException { if (Config.IS_TEST == null) { //ServiceLogger.log(LOGTAG, "SolR indexing turned off"); // Trigger solr indexing try { SearchQueueImpl.sendFullIndexingMessage(solrCoreName); ServiceLogger.log(logTag, "SolR indexing triggered for SOLR core: " + solrCoreName); } catch (SearchException e) { throw e; } } } }
3e15add6d22b2e32a593552921bca908031c8c5d
6,533
java
Java
library/src/main/java/io/github/yedaxia/apidocs/parser/AbsControllerParser.java
105032013072/apidocs
b7304cf25dafe5209a980b44367d420479ad7d49
[ "Apache-2.0" ]
null
null
null
library/src/main/java/io/github/yedaxia/apidocs/parser/AbsControllerParser.java
105032013072/apidocs
b7304cf25dafe5209a980b44367d420479ad7d49
[ "Apache-2.0" ]
null
null
null
library/src/main/java/io/github/yedaxia/apidocs/parser/AbsControllerParser.java
105032013072/apidocs
b7304cf25dafe5209a980b44367d420479ad7d49
[ "Apache-2.0" ]
null
null
null
44.141892
121
0.551967
9,202
package io.github.yedaxia.apidocs.parser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.ClassExpr; import com.github.javaparser.ast.expr.MemberValuePair; import com.github.javaparser.ast.expr.NormalAnnotationExpr; import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; import com.github.javaparser.javadoc.JavadocBlockTag; import io.github.yedaxia.apidocs.ParseUtils; import io.github.yedaxia.apidocs.Utils; import java.io.File; import java.util.List; import java.util.Optional; /** * parse Controller Java the common part, get all request nodes * * @author yeguozhong yedaxia.github.com */ public abstract class AbsControllerParser { private CompilationUnit compilationUnit; private ControllerNode controllerNode; private File javaFile; public ControllerNode parse(File javaFile){ this.javaFile = javaFile; this.compilationUnit = ParseUtils.compilationUnit(javaFile); this.controllerNode = new ControllerNode(); String controllerName = Utils.getJavaFileName(javaFile); compilationUnit.getClassByName(controllerName) .ifPresent(c -> { parseClassDoc(c); parseMethodDocs(c); afterHandleController(controllerNode, c); }); return controllerNode; } protected File getControllerFile(){ return javaFile; } private void parseClassDoc(ClassOrInterfaceDeclaration c){ c.getJavadoc().ifPresent( d -> { String description = d.getDescription().toText(); controllerNode.setDescription(Utils.isNotEmpty(description)? description: c.getNameAsString()); List<JavadocBlockTag> blockTags = d.getBlockTags(); if(blockTags != null){ for(JavadocBlockTag blockTag : blockTags){ if("author".equalsIgnoreCase(blockTag.getTagName())){ controllerNode.setAuthor(blockTag.getContent().toText()); } } } }); if(controllerNode.getDescription() == null){ controllerNode.setDescription(c.getNameAsString()); } } private void parseMethodDocs(ClassOrInterfaceDeclaration c){ c.getChildNodesByType(MethodDeclaration.class).stream() .filter(m -> m.getModifiers().contains(Modifier.PUBLIC) && m.getAnnotationByName("ApiDoc").isPresent()) .forEach(m -> { m.getAnnotationByName("ApiDoc").ifPresent(an -> { RequestNode requestNode = new RequestNode(); m.getAnnotationByClass(Deprecated.class).ifPresent(f -> {requestNode.setDeprecated(true);}); m.getJavadoc().ifPresent( d -> { String description = d.getDescription().toText(); requestNode.setDescription(description); d.getBlockTags().stream() .filter(t -> t.getTagName().equals("param")) .forEach(t ->{ ParamNode paramNode = new ParamNode(); paramNode.setName(t.getName().get()); paramNode.setDescription(t.getContent().toText()); requestNode.addParamNode(paramNode); }); }); m.getParameters().forEach(p -> { String paraName = p.getName().asString(); ParamNode paramNode = requestNode.getParamNodeByName(paraName); if(paramNode != null){ paramNode.setType(ParseUtils.unifyType(p.getType().asString())); } }); afterHandleMethod(requestNode, m); com.github.javaparser.ast.type.Type resultClassType = null; if(an instanceof SingleMemberAnnotationExpr){ resultClassType = ((ClassExpr) ((SingleMemberAnnotationExpr) an).getMemberValue()).getType(); }else if(an instanceof NormalAnnotationExpr){ Optional<MemberValuePair> opPair = ((NormalAnnotationExpr)an) .getPairs().stream() .filter(rs -> rs.getNameAsString().equals("result")) .findFirst(); if(opPair.isPresent()){ resultClassType = ((ClassExpr) opPair.get().getValue()).getType(); } } if(resultClassType == null){ return; } ResponseNode responseNode = new ResponseNode(); File resultJavaFile; if(resultClassType.asString().endsWith("[]")){ responseNode.setList(Boolean.TRUE); String type = resultClassType.getElementType().asString(); resultJavaFile = ParseUtils.searchJavaFile(javaFile, type); }else{ responseNode.setList(Boolean.FALSE); resultJavaFile = ParseUtils.searchJavaFile(javaFile, resultClassType.asString()); } responseNode.setClassName(Utils.getJavaFileName(resultJavaFile)); ParseUtils.parseResponseNode(resultJavaFile, responseNode); requestNode.setResponseNode(responseNode); controllerNode.addRequestNode(requestNode); }); }); } /** * called after controller node has handled * @param clazz */ protected void afterHandleController(ControllerNode controllerNode, ClassOrInterfaceDeclaration clazz){} /** * called after request method node has handled */ protected void afterHandleMethod(RequestNode requestNode, MethodDeclaration md){} }
3e15b008a9e62b23eef64d161ad609ea56ffc404
12,749
java
Java
geode-core/src/main/java/org/apache/geode/internal/cache/ClusterConfigurationLoader.java
xiaoyuMo/geode
d4a94f38a80b1e587384dfabf6c52e07e9c1e17a
[ "Apache-2.0" ]
null
null
null
geode-core/src/main/java/org/apache/geode/internal/cache/ClusterConfigurationLoader.java
xiaoyuMo/geode
d4a94f38a80b1e587384dfabf6c52e07e9c1e17a
[ "Apache-2.0" ]
4
2020-05-22T16:10:25.000Z
2022-03-30T23:49:10.000Z
geode-core/src/main/java/org/apache/geode/internal/cache/ClusterConfigurationLoader.java
xiaoyuMo/geode
d4a94f38a80b1e587384dfabf6c52e07e9c1e17a
[ "Apache-2.0" ]
1
2022-01-19T00:34:07.000Z
2022-01-19T00:34:07.000Z
36.953623
100
0.719037
9,203
/* * 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.apache.geode.internal.cache; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import com.healthmarketscience.rmiio.RemoteInputStream; import com.healthmarketscience.rmiio.RemoteInputStreamClient; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.apache.geode.UnmodifiableException; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.Cache; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionInvocationTargetException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.distributed.ConfigurationPersistenceService; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.LockServiceDestroyedException; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.ClassPathLoader; import org.apache.geode.internal.ConfigSource; import org.apache.geode.internal.DeployedJar; import org.apache.geode.internal.JarDeployer; import org.apache.geode.internal.config.ClusterConfigurationNotAvailableException; import org.apache.geode.internal.logging.LogService; import org.apache.geode.management.internal.beans.FileUploader; import org.apache.geode.management.internal.cli.CliUtil; import org.apache.geode.management.internal.configuration.domain.Configuration; import org.apache.geode.management.internal.configuration.functions.DownloadJarFunction; import org.apache.geode.management.internal.configuration.functions.GetClusterConfigurationFunction; import org.apache.geode.management.internal.configuration.messages.ConfigurationResponse; public class ClusterConfigurationLoader { private static final Logger logger = LogService.getLogger(); @Immutable private static final Function GET_CLUSTER_CONFIG_FUNCTION = new GetClusterConfigurationFunction(); /** * Deploys the jars received from shared configuration, it undeploys any other jars that were not * part of shared configuration * * @param response {@link ConfigurationResponse} received from the locators */ public void deployJarsReceivedFromClusterConfiguration(ConfigurationResponse response) throws IOException, ClassNotFoundException { if (response == null) { return; } logger.info("deploying jars received from cluster configuration"); List<String> jarFileNames = response.getJarNames().values().stream().flatMap(Set::stream).collect(Collectors.toList()); if (jarFileNames != null && !jarFileNames.isEmpty()) { logger.info("Got response with jars: {}", jarFileNames.stream().collect(joining(","))); JarDeployer jarDeployer = ClassPathLoader.getLatest().getJarDeployer(); jarDeployer.suspendAll(); try { List<String> extraJarsOnServer = jarDeployer.findDeployedJars().stream().map(DeployedJar::getJarName) .filter(jarName -> !jarFileNames.contains(jarName)).collect(toList()); for (String extraJar : extraJarsOnServer) { logger.info("Removing jar not present in cluster configuration: {}", extraJar); jarDeployer.deleteAllVersionsOfJar(extraJar); } Map<String, File> stagedJarFiles = getJarsFromLocator(response.getMember(), response.getJarNames()); List<DeployedJar> deployedJars = jarDeployer.deploy(stagedJarFiles); deployedJars.stream().filter(Objects::nonNull) .forEach((jar) -> logger.info("Deployed: {}", jar.getFile().getAbsolutePath())); } finally { jarDeployer.resumeAll(); } } } private Map<String, File> getJarsFromLocator(DistributedMember locator, Map<String, Set<String>> jarNames) throws IOException { Map<String, File> results = new HashMap<>(); for (String group : jarNames.keySet()) { for (String jar : jarNames.get(group)) { results.put(jar, downloadJar(locator, group, jar)); } } return results; } public File downloadJar(DistributedMember locator, String groupName, String jarName) throws IOException { ResultCollector<RemoteInputStream, List<RemoteInputStream>> rc = (ResultCollector<RemoteInputStream, List<RemoteInputStream>>) CliUtil.executeFunction( new DownloadJarFunction(), new Object[] {groupName, jarName}, Collections.singleton(locator)); List<RemoteInputStream> result = rc.getResult(); Path tempDir = FileUploader.createSecuredTempDirectory("deploy-"); Path tempJar = Paths.get(tempDir.toString(), jarName); FileOutputStream fos = new FileOutputStream(tempJar.toString()); InputStream jarStream = RemoteInputStreamClient.wrap(result.get(0)); IOUtils.copyLarge(jarStream, fos); fos.close(); jarStream.close(); return tempJar.toFile(); } /*** * Apply the cache-xml cluster configuration on this member */ public void applyClusterXmlConfiguration(Cache cache, ConfigurationResponse response, String groupList) { if (response == null || response.getRequestedConfiguration().isEmpty()) { return; } Set<String> groups = getGroups(groupList); Map<String, Configuration> requestedConfiguration = response.getRequestedConfiguration(); List<String> cacheXmlContentList = new LinkedList<String>(); // apply the cluster config first Configuration clusterConfiguration = requestedConfiguration.get(ConfigurationPersistenceService.CLUSTER_CONFIG); if (clusterConfiguration != null) { String cacheXmlContent = clusterConfiguration.getCacheXmlContent(); if (StringUtils.isNotBlank(cacheXmlContent)) { cacheXmlContentList.add(cacheXmlContent); } } // then apply the groups config for (String group : groups) { Configuration groupConfiguration = requestedConfiguration.get(group); if (groupConfiguration != null) { String cacheXmlContent = groupConfiguration.getCacheXmlContent(); if (StringUtils.isNotBlank(cacheXmlContent)) { cacheXmlContentList.add(cacheXmlContent); } } } // apply the requested cache xml for (String cacheXmlContent : cacheXmlContentList) { InputStream is = new ByteArrayInputStream(cacheXmlContent.getBytes()); try { cache.loadCacheXml(is); } finally { try { is.close(); } catch (IOException e) { } } } } /*** * Apply the gemfire properties cluster configuration on this member * * @param response {@link ConfigurationResponse} containing the requested {@link Configuration} * @param config this member's config */ public void applyClusterPropertiesConfiguration(ConfigurationResponse response, DistributionConfig config) { if (response == null || response.getRequestedConfiguration().isEmpty()) { return; } Set<String> groups = getGroups(config.getGroups()); Map<String, Configuration> requestedConfiguration = response.getRequestedConfiguration(); final Properties runtimeProps = new Properties(); // apply the cluster config first Configuration clusterConfiguration = requestedConfiguration.get(ConfigurationPersistenceService.CLUSTER_CONFIG); if (clusterConfiguration != null) { runtimeProps.putAll(clusterConfiguration.getGemfireProperties()); } final Properties groupProps = new Properties(); // then apply the group config for (String group : groups) { Configuration groupConfiguration = requestedConfiguration.get(group); if (groupConfiguration != null) { for (Map.Entry<Object, Object> e : groupConfiguration.getGemfireProperties().entrySet()) { if (groupProps.containsKey(e.getKey())) { logger.warn("Conflicting property {} from group {}", e.getKey(), group); } else { groupProps.put(e.getKey(), e.getValue()); } } } } runtimeProps.putAll(groupProps); Set<Object> attNames = runtimeProps.keySet(); for (Object attNameObj : attNames) { String attName = (String) attNameObj; String attValue = runtimeProps.getProperty(attName); try { config.setAttribute(attName, attValue, ConfigSource.runtime()); } catch (IllegalArgumentException e) { logger.info(e.getMessage()); } catch (UnmodifiableException e) { logger.info(e.getMessage()); } } } /** * Request the shared configuration for group(s) from locator(s) this member is bootstrapped with. * * This will request the group config this server belongs plus the "cluster" config * * @return {@link ConfigurationResponse} */ public ConfigurationResponse requestConfigurationFromLocators(String groupList, Set<InternalDistributedMember> locatorList) throws ClusterConfigurationNotAvailableException, UnknownHostException { Set<String> groups = getGroups(groupList); ConfigurationResponse response = null; int attempts = 6; OUTER: while (attempts > 0) { for (InternalDistributedMember locator : locatorList) { logger.info("Attempting to retrieve cluster configuration from {} - {} attempts remaining", locator.getName(), attempts); response = requestConfigurationFromOneLocator(locator, groups); if (response != null) { break OUTER; } } try { Thread.sleep(10000); } catch (InterruptedException ex) { break; } attempts--; } // if the response is null if (response == null) { throw new ClusterConfigurationNotAvailableException( "Unable to retrieve cluster configuration from the locator."); } return response; } protected ConfigurationResponse requestConfigurationFromOneLocator( InternalDistributedMember locator, Set<String> groups) { ConfigurationResponse configResponse = null; try { ResultCollector resultCollector = FunctionService.onMember(locator).setArguments(groups) .execute(GET_CLUSTER_CONFIG_FUNCTION); Object result = ((ArrayList) resultCollector.getResult()).get(0); if (result instanceof ConfigurationResponse) { configResponse = (ConfigurationResponse) result; configResponse.setMember(locator); } else { logger.error("Received invalid result from {}: {}", locator.toString(), result); if (result instanceof Throwable) { // log the stack trace. logger.error(result.toString(), result); } } } catch (FunctionException fex) { // Rethrow unless we're possibly reconnecting if (!(fex.getCause() instanceof LockServiceDestroyedException || fex.getCause() instanceof FunctionInvocationTargetException)) { throw fex; } } return configResponse; } Set<String> getGroups(String groupString) { if (StringUtils.isBlank(groupString)) { return new HashSet<>(); } return (Arrays.stream(groupString.split(",")).collect(Collectors.toSet())); } }
3e15b02fc241d52117469a015afb34cfde62fc70
422
java
Java
soottocfg/src/main/java/soottocfg/cfg/type/Type.java
peterschrammel/jayhorn
8b1c4f6f186a37c5723a0509451fbbad1a04e7d5
[ "MIT" ]
null
null
null
soottocfg/src/main/java/soottocfg/cfg/type/Type.java
peterschrammel/jayhorn
8b1c4f6f186a37c5723a0509451fbbad1a04e7d5
[ "MIT" ]
null
null
null
soottocfg/src/main/java/soottocfg/cfg/type/Type.java
peterschrammel/jayhorn
8b1c4f6f186a37c5723a0509451fbbad1a04e7d5
[ "MIT" ]
null
null
null
16.88
78
0.694313
9,204
/** * */ package soottocfg.cfg.type; import java.io.Serializable; /** * @author schaef Note that Type is not abstract, so we can use it as wildcard * type. */ public class Type implements Serializable { private static final long serialVersionUID = -5408794248925241891L; private static final Type instance = new Type(); public static Type instance() { return instance; } protected Type() { } }
3e15b1758dc85e48d0e3776f046f7c10cf159c2e
2,583
java
Java
src/main/java/com/store/domain/service/catalog/impl/CachedBundleService.java
miguel-isasmendi/store
43c9e4ea1fe3bcba8d09f9eff43f0ed72cb59427
[ "MIT" ]
null
null
null
src/main/java/com/store/domain/service/catalog/impl/CachedBundleService.java
miguel-isasmendi/store
43c9e4ea1fe3bcba8d09f9eff43f0ed72cb59427
[ "MIT" ]
null
null
null
src/main/java/com/store/domain/service/catalog/impl/CachedBundleService.java
miguel-isasmendi/store
43c9e4ea1fe3bcba8d09f9eff43f0ed72cb59427
[ "MIT" ]
null
null
null
32.2875
112
0.799845
9,205
package com.store.domain.service.catalog.impl; import java.util.List; import java.util.stream.Collectors; import com.google.appengine.api.memcache.MemcacheService; import com.google.inject.Inject; import com.store.architecture.cache.CacheHandler; import com.store.domain.dao.catalog.BundleDao; import com.store.domain.model.bundle.Bundle; import com.store.domain.model.bundle.build.coordinator.BundleBuildCoordinator; import com.store.domain.model.bundle.data.BundleCreationData; import com.store.domain.model.bundle.data.BundleData; import com.store.domain.model.product.data.ProductData; import com.store.domain.service.catalog.BundleService; import lombok.NonNull; public class CachedBundleService implements BundleService { private static final String CACHE_BUNDLE_PREFIX = "bundle_"; private static final String CACHE_BUNDLE_IDS_PREFIX = "products_ids"; private BundleDao bundleDao; private CacheHandler<Bundle> bundleCacheHandler; private CacheHandler<List<Long>> bundleIdsCacheHandler; @Inject public CachedBundleService(@NonNull BundleDao bundleDao, @NonNull MemcacheService cache) { this.bundleDao = bundleDao; this.bundleCacheHandler = CacheHandler.<Bundle>builder().cache(cache).keyGeneratorClosure(Bundle::getBundleId) .prefix(CACHE_BUNDLE_PREFIX).build(); this.bundleIdsCacheHandler = CacheHandler.<List<Long>>builder().cache(cache).prefix(CACHE_BUNDLE_IDS_PREFIX) .build(); } @Override public BundleData create(@NonNull Long userId, @NonNull BundleCreationData bundleCreationData) { Bundle bundle = bundleDao.create(userId, bundleCreationData); bundleCacheHandler.putIntoCache(bundle); bundleIdsCacheHandler.deleteFromCache(); return BundleBuildCoordinator.toData(bundle); } @Override public BundleData getById(@NonNull Long bundleId) { Bundle bundle = bundleCacheHandler.getFromCacheUsingPartialKey(bundleId); if (bundle == null) { bundle = bundleDao.getById(bundleId); bundleCacheHandler.putIntoCache(bundle); } return BundleBuildCoordinator.toData(bundle); } @Override public BundleData deleteById(@NonNull Long bundleId) { bundleCacheHandler.deleteFromCacheUsingPartialKey(bundleId); return BundleBuildCoordinator.toData(bundleDao.delete(bundleId)); } @Override public List<BundleData> getBundles() { List<Long> bundleIds = bundleIdsCacheHandler.getFromCache(); if (bundleIds == null) { bundleIds = bundleDao.getBundlesIds(); bundleIdsCacheHandler.putIntoCacheUsingPartialKey(bundleIds); } return bundleIds.stream().map(this::getById).collect(Collectors.toList()); } }
3e15b192eb4f653f5b2e8ca28e23d98a6095c365
328
java
Java
app/src/main/java/com/wwzz/coolweather/MyApplication.java
wangzhao9211/mycoolwether
82b4dd6863e5b12de94671f3247929181cbbd962
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/wwzz/coolweather/MyApplication.java
wangzhao9211/mycoolwether
82b4dd6863e5b12de94671f3247929181cbbd962
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/wwzz/coolweather/MyApplication.java
wangzhao9211/mycoolwether
82b4dd6863e5b12de94671f3247929181cbbd962
[ "Apache-2.0" ]
null
null
null
15.181818
49
0.664671
9,206
package com.wwzz.coolweather; import android.app.Application; import org.litepal.LitePal; /** * 作者:wz created on 2017/3/6 09:35 * dycjh@example.com * 功能: */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); LitePal.initialize(this); } }
3e15b2084b9232f6c7e82ed15768401c536be5d8
525
java
Java
union-dao/src/main/java/xyz/appint/union/dao/dao/annotation/Col.java
xyz-appint/union
3c61dbd673fd21642ab35adaec07406c047e2248
[ "Apache-2.0" ]
null
null
null
union-dao/src/main/java/xyz/appint/union/dao/dao/annotation/Col.java
xyz-appint/union
3c61dbd673fd21642ab35adaec07406c047e2248
[ "Apache-2.0" ]
null
null
null
union-dao/src/main/java/xyz/appint/union/dao/dao/annotation/Col.java
xyz-appint/union
3c61dbd673fd21642ab35adaec07406c047e2248
[ "Apache-2.0" ]
null
null
null
17.5
45
0.630476
9,207
package xyz.appint.union.dao.dao.annotation; import java.lang.annotation.*; /** * Created by justin on 15/9/18. */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Col { String name() default ""; String value() default ""; Include include() default Include.ALWAYS; // String defaultVal() default ""; public static enum Include { ALWAYS, NON_NULL, NON_EMPTY, NON_DEFAULT; private Include() { } } }
3e15b24b5d4c9e06f75aeb1d8614b92c4b5efe15
3,397
java
Java
test/hotspot/jtreg/serviceability/attach/RemovingUnixDomainSocketTest.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
test/hotspot/jtreg/serviceability/attach/RemovingUnixDomainSocketTest.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
test/hotspot/jtreg/serviceability/attach/RemovingUnixDomainSocketTest.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
null
null
null
34.313131
87
0.652635
9,208
/* * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8225193 * @requires os.family != "windows" * @library /test/lib * @run driver RemovingUnixDomainSocketTest */ import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.concurrent.TimeUnit; import jdk.test.lib.Utils; import jdk.test.lib.apps.LingeredApp; import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; public class RemovingUnixDomainSocketTest { // timeout (in seconds) private static final long timeout = Utils.adjustTimeout(60); private static void runJCmd(long pid) throws InterruptedException, IOException { JDKToolLauncher jcmd = JDKToolLauncher.createUsingTestJDK("jcmd"); jcmd.addVMArgs(Utils.getFilteredTestJavaOpts("-showversion")); jcmd.addToolArg(Long.toString(pid)); jcmd.addToolArg("VM.version"); ProcessBuilder pb = new ProcessBuilder(jcmd.getCommand()); Process jcmdProc = pb.start(); OutputAnalyzer out = new OutputAnalyzer(jcmdProc); if (!jcmdProc.waitFor(timeout, TimeUnit.SECONDS)) { log("jcmd is still running after " + timeout + " seconds, terminating..."); jcmdProc.destroy(); jcmdProc.waitFor(); } log("jcmd stdout: [" + out.getStdout() + "];\n" + "jcmd stderr: [" + out.getStderr() + "]\n" + "jcmd exitValue = " + out.getExitValue()); out.shouldHaveExitValue(0); out.stderrShouldBeEmptyIgnoreDeprecatedWarnings(); } public static void main(String... args) throws Exception { LingeredApp app = null; try { app = LingeredApp.startApp(); // Access to Attach Listener runJCmd(app.getPid()); // Remove unix domain socket file File sockFile = Path.of(System.getProperty("java.io.tmpdir"), ".java_pid" + app.getPid()) .toFile(); log("Remove " + sockFile.toString()); sockFile.delete(); // Access to Attach Listener again runJCmd(app.getPid()); } finally { LingeredApp.stopApp(app); } } static void log(Object s) { System.out.println(String.valueOf(s)); } }
3e15b29cf8a4590d1ebf88d36114531a0b06495a
394
java
Java
java_collections/src/main/java/com/chenxushao/java/collection/map/HashMapDemo1.java
chenxushao/java_enhance
5b883f6c25dc7811d600e009a4b0c3ac2dac5dba
[ "Apache-2.0" ]
null
null
null
java_collections/src/main/java/com/chenxushao/java/collection/map/HashMapDemo1.java
chenxushao/java_enhance
5b883f6c25dc7811d600e009a4b0c3ac2dac5dba
[ "Apache-2.0" ]
null
null
null
java_collections/src/main/java/com/chenxushao/java/collection/map/HashMapDemo1.java
chenxushao/java_enhance
5b883f6c25dc7811d600e009a4b0c3ac2dac5dba
[ "Apache-2.0" ]
null
null
null
20.736842
58
0.667513
9,209
package com.chenxushao.java.collection.map; import java.util.HashMap; import java.util.Map; public class HashMapDemo1 { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); System.out.println(map.containsKey("1")); System.out.println(map.containsKey(new String("1"))); } }
3e15b32d2f0cb74119bd7ab54b828b4a824ee8e0
4,348
java
Java
src/main/java/de/dennisguse/opentracks/util/IntentDashboardUtils.java
vlmendz/OpenTracks
976d4f848ff24a9183b68f80949c145e9b1d50b3
[ "Apache-2.0" ]
381
2019-12-29T15:28:06.000Z
2022-03-30T15:23:46.000Z
src/main/java/de/dennisguse/opentracks/util/IntentDashboardUtils.java
vsevjednom-cz/OpenTracks
a67b6cfa6e424fb954881c9ce600e91ff6500939
[ "Apache-2.0" ]
799
2019-12-27T22:57:24.000Z
2022-03-31T21:52:29.000Z
src/main/java/de/dennisguse/opentracks/util/IntentDashboardUtils.java
vsevjednom-cz/OpenTracks
a67b6cfa6e424fb954881c9ce600e91ff6500939
[ "Apache-2.0" ]
89
2019-12-28T14:11:12.000Z
2022-03-10T11:13:20.000Z
41.018868
147
0.74448
9,210
package de.dennisguse.opentracks.util; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.net.Uri; import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import de.dennisguse.opentracks.content.data.MarkerColumns; import de.dennisguse.opentracks.content.data.Track; import de.dennisguse.opentracks.content.data.TrackPointsColumns; import de.dennisguse.opentracks.content.data.TracksColumns; import de.dennisguse.opentracks.content.provider.ContentProviderUtils; import de.dennisguse.opentracks.settings.PreferencesUtils; /** * Create an {@link Intent} to request showing a Dashboard. * The receiving {@link android.app.Activity} gets temporary access to the {@link TracksColumns} and the {@link TrackPointsColumns} (incl. update). */ public class IntentDashboardUtils { private static final String ACTION_DASHBOARD = "Intent.OpenTracks-Dashboard"; private static final String ACTION_DASHBOARD_PAYLOAD = ACTION_DASHBOARD + ".Payload"; /** * Assume "v1" if not present. */ private static final String EXTRAS_PROTOCOL_VERSION = "PROTOCOL_VERSION"; /** * version 1: the initial version. * version 2: replaced pause/resume trackpoints for track segmentation (lat=100 / lat=200) by TrackPoint.Type. */ private static final int CURRENT_VERSION = 2; private static final String EXTRAS_OPENTRACKS_IS_RECORDING_THIS_TRACK = "EXTRAS_OPENTRACKS_IS_RECORDING_THIS_TRACK"; private static final String EXTRAS_SHOULD_KEEP_SCREEN_ON = "EXTRAS_SHOULD_KEEP_SCREEN_ON"; private static final String EXTRAS_SHOW_WHEN_LOCKED = "EXTRAS_SHOULD_KEEP_SCREEN_ON"; private static final String EXTRAS_SHOW_FULLSCREEN = "EXTRAS_SHOULD_FULLSCREEN"; private static final int TRACK_URI_INDEX = 0; private static final int TRACKPOINTS_URI_INDEX = 1; private static final int MARKERS_URI_INDEX = 2; private IntentDashboardUtils() { } /** * Send intent to show tracks on a map (needs an another app) as resource URIs. * * @param context the context * @param trackIds the track ids */ public static void startDashboard(Context context, boolean isRecording, Track.Id... trackIds) { if (trackIds.length == 0) { return; } String trackIdList = ContentProviderUtils.formatIdListForUri(trackIds); ArrayList<Uri> uris = new ArrayList<>(); uris.add(TRACK_URI_INDEX, Uri.withAppendedPath(TracksColumns.CONTENT_URI, trackIdList)); uris.add(TRACKPOINTS_URI_INDEX, Uri.withAppendedPath(TrackPointsColumns.CONTENT_URI_BY_TRACKID, trackIdList)); uris.add(MARKERS_URI_INDEX, Uri.withAppendedPath(MarkerColumns.CONTENT_URI_BY_TRACKID, trackIdList)); Intent intent = new Intent(ACTION_DASHBOARD); intent.putExtra(EXTRAS_PROTOCOL_VERSION, CURRENT_VERSION); intent.putParcelableArrayListExtra(ACTION_DASHBOARD_PAYLOAD, uris); intent.putExtra(EXTRAS_SHOULD_KEEP_SCREEN_ON, PreferencesUtils.shouldKeepScreenOn()); intent.putExtra(EXTRAS_SHOW_WHEN_LOCKED, PreferencesUtils.shouldShowStatsOnLockscreen()); intent.putExtra(EXTRAS_OPENTRACKS_IS_RECORDING_THIS_TRACK, isRecording); if (isRecording) { intent.putExtra(EXTRAS_SHOW_FULLSCREEN, PreferencesUtils.shouldUseFullscreen()); } intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); ClipData clipData = ClipData.newRawUri(null, uris.get(TRACK_URI_INDEX)); clipData.addItem(new ClipData.Item(uris.get(TRACKPOINTS_URI_INDEX))); clipData.addItem(new ClipData.Item(uris.get(MARKERS_URI_INDEX))); intent.setClipData(clipData); context.startActivity(intent); } public static Set<Track.Id> extractTrackIdsFromIntent(@NonNull Intent intent) { final ArrayList<Uri> uris = intent.getParcelableArrayListExtra(ACTION_DASHBOARD_PAYLOAD); final Uri tracksUri = uris.get(TRACK_URI_INDEX); String[] trackIdsString = ContentProviderUtils.parseTrackIdsFromUri(tracksUri); Set<Track.Id> trackIds = new HashSet<>(trackIdsString.length); for (String s : trackIdsString) { trackIds.add(new Track.Id(Long.parseLong(s))); } return trackIds; } }
3e15b3626cc27d95cb1a47bbbb1c49178c34816d
14,432
java
Java
nusimloader-plugin-huawei/src/test/java/de/scoopgmbh/nusimapp/nusimsim/adapter/huawei/HuaweiNusimSimAdapterTest.java
telekom/nuSIM-Loader-Application
9110b36eb49d687390f4d616eeae45d29fcfce40
[ "Apache-2.0" ]
6
2021-02-26T14:54:05.000Z
2021-07-02T04:14:06.000Z
nusimloader-plugin-huawei/src/test/java/de/scoopgmbh/nusimapp/nusimsim/adapter/huawei/HuaweiNusimSimAdapterTest.java
telekom/nuSIM-Loader-Application
9110b36eb49d687390f4d616eeae45d29fcfce40
[ "Apache-2.0" ]
7
2021-03-21T10:25:37.000Z
2021-06-10T09:41:35.000Z
nusimloader-plugin-huawei/src/test/java/de/scoopgmbh/nusimapp/nusimsim/adapter/huawei/HuaweiNusimSimAdapterTest.java
telekom/nuSIM-Loader-Application
9110b36eb49d687390f4d616eeae45d29fcfce40
[ "Apache-2.0" ]
1
2021-04-22T10:20:55.000Z
2021-04-22T10:20:55.000Z
55.047101
288
0.709669
9,211
/* Copyright 2020 HiSilicon (Shanghai) 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 de.scoopgmbh.nusimapp.nusimsim.adapter.huawei; import com.google.common.base.Strings; import com.google.common.io.BaseEncoding; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import de.scoopgmbh.nusimapp.nusimsim.adapter.NoEidAvailableException; import de.scoopgmbh.nusimapp.nusimsim.adapter.ProfileLoadingException; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.startsWith; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class HuaweiNusimSimAdapterTest { private final int commandRetries = 3; // must be higher than 1 private ISerialPortHandler serialPortHandler; private Supplier<ISerialPortHandler> serialPortHandlerSupplier; private Config adapterConfig; @Before public void setup() { serialPortHandler = mock(ISerialPortHandler.class); serialPortHandlerSupplier = () -> serialPortHandler; adapterConfig = ConfigFactory.empty() .withValue("serialPort", ConfigValueFactory.fromAnyRef("DUMMY-UNUSED")) .withValue("baudRate", ConfigValueFactory.fromAnyRef(1)) .withValue("commandRetries", ConfigValueFactory.fromAnyRef(commandRetries)) .withValue("commandTimeoutMs", ConfigValueFactory.fromAnyRef(20)) .withValue("commandRetryDelayMs", ConfigValueFactory.fromAnyRef(100)); } @After public void tearDown() { verify(serialPortHandler, times(1)).close(); verifyNoMoreInteractions(serialPortHandler); } @Test public void testGetEID() throws Exception { when(serialPortHandler.sendCommand(eq("AT+NSESIM=GETEID"))) .thenReturn(completedFuture("some output before \r\n \r\n+GETEID:9jnerlff23u8ed01np9g6ysbhsh0dvcs\r\n \r\nother output afterwards")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); String eid = subject.getEID(); assertEquals("9jnerlff23u8ed01np9g6ysbhsh0dvcs", eid); verify(serialPortHandler, times(1)).sendCommand("AT+NSESIM=GETEID"); } @Test public void testGetEIDWithOneRetry() throws Exception { when(serialPortHandler.sendCommand(eq("AT+NSESIM=GETEID"))) .thenReturn(completedFutureWithException(new RuntimeException("boo"))) .thenReturn(completedFuture("+GETEID:9jnerlff23u8ed01np9g6ysbhsh0dvcs")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); String eid = subject.getEID(); assertEquals("9jnerlff23u8ed01np9g6ysbhsh0dvcs", eid); verify(serialPortHandler, times(2)).sendCommand("AT+NSESIM=GETEID"); } @Test public void testGetEIDErroneousOutput() { when(serialPortHandler.sendCommand(eq("AT+NSESIM=GETEID"))) .thenReturn(completedFuture("some weird output before \r\n \r\n ... but no +GETEID answer\r\n")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); try { subject.getEID(); fail("expected NoEidAvailableException"); } catch (NoEidAvailableException ex) { verify(serialPortHandler, times(commandRetries)).sendCommand("AT+NSESIM=GETEID"); } } @Test public void testGetEIDException() { when(serialPortHandler.sendCommand(eq("AT+NSESIM=GETEID"))) .thenReturn(completedFutureWithException(new SerialPortErroneousOutputException("some error output"))); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); try { subject.getEID(); fail("expected NoEidAvailableException"); } catch (NoEidAvailableException ex) { verify(serialPortHandler, times(commandRetries)).sendCommand("AT+NSESIM=GETEID"); } } @Test public void testGetNusimCapabilities() { when(serialPortHandler.sendCommand(eq("AT+NSESIM=GETCAPABILITIES"))) .thenReturn(completedFuture("some output before \r\n \r\n+GETCAPABILITIES:09,03\r\n \r\nother output afterwards")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); String nusimCapabilities = subject.getNusimCapabilities(); assertEquals("03", nusimCapabilities); verify(serialPortHandler, times(1)).sendCommand("AT+NSESIM=GETCAPABILITIES"); } @Test public void testGetCertNusim() { // test vectors taken from Eagle_Provisioning_Spec_V12.pdf, page 71, chapter A.4.2 "CERT.EAGLE.ECDSA" when(serialPortHandler.sendCommand(eq("AT+NSESIM=GETCERTIFICATE"))) .thenReturn(completedFuture("some output before \r\n \r\n+GETCERTIFICATE:" + "30820206308201aca003020102021012345678000000001234567811223344300a06" + "082a8648ce3d0403023038310b30090603550406130244453111300f060355040a0c" + "74t3tndxag9o7h0890bnpfzh4olk2h9x" + "1e170d3138303230373132343634385a170d3238303230353132343634385a306031" + "0b300906035504061302444531133011060355040a0c0a546573745f4561676c6531" + "29302706035504051320313233343536373830303030303030303132333435363738" + "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" + "8648ce3d020106092b24030302080101070342000452e0384954ed5a69802561c887" + "1c59bc1e58e7878d4367de1ac7a277ce09d9763d46042c879f18e2e0a9130d089fce" + "8c24edc5e8512d53c7dd721aa256e83f38a36f306d301f0603551d23041830168014" + "c8650a03d7c197ce125ac86e72b0c977ca277d9e301d0603551d0e041604143721f9" + "12551976af97f0ab1a04be87dba6252702300e0603551d0f0101ff04040302078030" + "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" + "48ce3d0403020348003045022100a8127d6b93015b9fac7c708b732d449d0dfe6a0e" + "80533d6a885e9242dd62f4eb02206e95eac30c7e9c398118f279dcd42db1aec5977f" + "613911a74cc9058b0d235a9c\r\n \r\nother output afterwards")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); String certNusim = subject.getCertNusim(); assertEquals("-----BEGIN CERTIFICATE-----\n" + "74t3tndxag9o7h0890bnpfzh4olk2h9x" + "kgfhvu9qnh3mr6eel97y6fq2hezzol8z" + "QwHhcNMTgwMjA3MTI0NjQ4WhcNMjgwMjA1MTI0NjQ4WjBgMQswCQYDVQQGEwJERTETM\n" + "se2xy1bknelxn4y8xzxu3trosptip3q5" + "se2xy1bknelxn4y8xzxu3trosptip3q5" + "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" + "74t3tndxag9o7h0890bnpfzh4olk2h9x" + "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7" + "74t3tndxag9o7h0890bnpfzh4olk2h9x" + "caf86f4uutaoxfysmf7anj01xl6sv3ps" + "74t3tndxag9o7h0890bnpfzh4olk2h9x" + "-----END CERTIFICATE-----\n", certNusim); verify(serialPortHandler, times(1)).sendCommand("AT+NSESIM=GETCERTIFICATE"); } @Test public void testLoadProfile() throws Exception { // test vectors taken from Eagle_Provisioning_Spec_V12.pdf, page 67, chapter A.1 "Keys" String mac = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; String eKPubDP = "04A47A63C15060F1B524C58082A2956C2139B2FD8688274CD5D756189B84F94E400CD691ED9BE1F0F8A2D206850D08328426FA0C092BCE39B98A50ED0B2ED871DE"; String sigEKPubDP = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; String kPubDP = "9jnerlff23u8ed01np9g6ysbhsh0dvcs"; String sigKPubDP = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; String kPubCI = "74t3tndxag9o7h0890bnpfzh4olk2h9x"; byte[] encP = "profile data".getBytes(StandardCharsets.US_ASCII); when(serialPortHandler.sendCommand(startsWith("AT+NSESIM=SETPROFILE"), any(), any())).thenReturn(completedFuture("first \n some \n arbitrary \n output \n then \n+SETPROFILE: 123456789012\n plus \n some \n more \n output\n")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); String iccid = subject.loadProfile("eid gets ignored", mac, BaseEncoding.base64().encode(encP), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(eKPubDP)), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(sigEKPubDP)), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(kPubDP)), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(sigKPubDP)), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(kPubCI))); assertEquals("123456789012", iccid); int expectedLength = 65 /*eKPubDP*/ + 16 /*mac*/ + 64 /*sigEKPubDP*/ + 65 /*kPubDP*/ + 64 /*sigKPubDP*/ + 65 /*kPubCI*/ + encP.length; String expectedSetProfileCommand = "AT+NSESIM=SETPROFILE," + expectedLength + "," + eKPubDP + mac + sigEKPubDP + kPubDP + sigKPubDP + kPubCI + BaseEncoding.base16().upperCase().encode(encP); verify(serialPortHandler, times(1)).sendCommand(eq(expectedSetProfileCommand), any(), any()); } @Test public void testLoadProfileNoDPAuth() throws Exception { // test vectors taken from Eagle_Provisioning_Spec_V12.pdf, page 67, chapter A.1 "Keys" String mac = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; String eKPubDP = "04A47A63C15060F1B524C58082A2956C2139B2FD8688274CD5D756189B84F94E400CD691ED9BE1F0F8A2D206850D08328426FA0C092BCE39B98A50ED0B2ED871DE"; byte[] encP = "profile data".getBytes(StandardCharsets.US_ASCII); when(serialPortHandler.sendCommand(startsWith("AT+NSESIM=SETPROFILE"), any(), any())).thenReturn(completedFuture("first \n some \n arbitrary \n output \n then \n+SETPROFILE: 12345678901234\n plus \n some \n more \n output\n")); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); String iccid = subject.loadProfile("eid gets ignored", mac, BaseEncoding.base64().encode(encP), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(eKPubDP)), null, null, null, null); assertEquals("12345678901234", iccid); int expectedLength = 65 /*eKPubDP*/ + 16 /*mac*/ + 64 /*sigEKPubDP*/ + 65 /*kPubDP*/ + 64 /*sigKPubDP*/ + 65 /*kPubCI*/ + encP.length; String nullsForEmptyDP = Strings.repeat("00", 64 + 65 + 64 + 65); String expectedSetProfileCommand = "AT+NSESIM=SETPROFILE," + expectedLength + "," + eKPubDP + mac + nullsForEmptyDP + BaseEncoding.base16().upperCase().encode(encP); verify(serialPortHandler, times(1)).sendCommand(eq(expectedSetProfileCommand), any(), any()); } @Test public void testLoadProfileError() { // test vectors taken from Eagle_Provisioning_Spec_V12.pdf, page 67, chapter A.1 "Keys" String mac = "caf86f4uutaoxfysmf7anj01xl6sv3ps"; String eKPubDP = "04A47A63C15060F1B524C58082A2956C2139B2FD8688274CD5D756189B84F94E400CD691ED9BE1F0F8A2D206850D08328426FA0C092BCE39B98A50ED0B2ED871DE"; byte[] encP = "profile data".getBytes(StandardCharsets.US_ASCII); when(serialPortHandler.sendCommand(startsWith("AT+NSESIM=SETPROFILE"), any(), any())).thenReturn(completedFutureWithException(new SerialPortErroneousOutputException("first \n some \n arbitrary \n output \n then an error: \n+SETPROFILE: 541 \n plus \n some \n more \n output\n"))); HuaweiNusimSimAdapter subject = new HuaweiNusimSimAdapter(adapterConfig, serialPortHandlerSupplier); try { subject.loadProfile("eid gets ignored", mac, BaseEncoding.base64().encode(encP), BaseEncoding.base64().encode(BaseEncoding.base16().upperCase().decode(eKPubDP)), null, null, null, null); } catch (ProfileLoadingException ex) { assertEquals("error 541: invalid KpubCI (does not match stored KpubCI)", ex.getMessage()); } int expectedLength = 65 /*eKPubDP*/ + 16 /*mac*/ + 64 /*sigEKPubDP*/ + 65 /*kPubDP*/ + 64 /*sigKPubDP*/ + 65 /*kPubCI*/ + encP.length; String nullsForEmptyDP = Strings.repeat("00", 64 + 65 + 64 + 65); String expectedSetProfileCommand = "AT+NSESIM=SETPROFILE," + expectedLength + "," + eKPubDP + mac + nullsForEmptyDP + BaseEncoding.base16().upperCase().encode(encP); verify(serialPortHandler, times(commandRetries)).sendCommand(eq(expectedSetProfileCommand), any(), any()); } private static <T> CompletableFuture<T> completedFutureWithException(Throwable ex) { CompletableFuture<T> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(ex); return completableFuture; } }
3e15b3cc26d0fb035420e03b3a34fba11aa92a59
5,598
java
Java
message-builder-html/src/main/java/ca/infoway/messagebuilder/datatype/mif/MifDocumentation.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
1
2022-03-09T12:17:41.000Z
2022-03-09T12:17:41.000Z
message-builder-html/src/main/java/ca/infoway/messagebuilder/datatype/mif/MifDocumentation.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
message-builder-html/src/main/java/ca/infoway/messagebuilder/datatype/mif/MifDocumentation.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
38.081633
114
0.742587
9,212
/** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2013-01-02 17:05:34 -0500 (Wed, 02 Jan 2013) $ * Revision: $LastChangedRevision: 6471 $ */ package ca.infoway.messagebuilder.datatype.mif; import java.util.ArrayList; import java.util.List; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Namespace; import org.simpleframework.xml.Root; import ca.infoway.messagebuilder.xml.Annotation; import ca.infoway.messagebuilder.xml.AnnotationType; @Root(strict = false) @Namespace(prefix = "mif", reference = "urn:hl7-org:v3/mif2") public class MifDocumentation { @Element(required = false) private MifBasicAnnotation definition; @Element(required = false) private MifBasicAnnotation description; @ElementList(entry = "usageConstraint", required = false, inline = true) private List<MifBasicAnnotation> usageConstraints = new ArrayList<MifBasicAnnotation>(); @ElementList(entry = "usageNotes", required = false, inline = true) private List<MifBasicAnnotation> usageNotes = new ArrayList<MifBasicAnnotation>(); @Element(required = false) private MifBasicAnnotation rationale; @ElementList(entry = "designComments", required = false, inline = true) private List<MifBasicAnnotation> designComments = new ArrayList<MifBasicAnnotation>(); @ElementList(entry = "otherAnnotation", required = false, inline = true) private List<MifOtherAnnotation> otherAnnotations = new ArrayList<MifOtherAnnotation>(); @Element(required=false) private MifBasicAnnotation requirements; @ElementList(entry = "stabilityRemarks", required = false, inline = true) private List<MifBasicAnnotation> stabilityRemarks = new ArrayList<MifBasicAnnotation>(); @Element(required=false) private MifBasicAnnotation walkthrough; @ElementList(entry="appendix",required=false,inline=true) private List<MifBasicAnnotation> appendices = new ArrayList<MifBasicAnnotation>(); private int unusedAnnotations = 0; public MifDocumentation() { } public MifDocumentation(List<Annotation> annotations) { for (Annotation annotation : annotations) { if (AnnotationType.DEFINITION.equals(annotation .getAnnotationTypeAsEnum())) { this.definition = new MifBasicAnnotation(annotation.getText()); } else if (AnnotationType.DESCRIPTION.equals(annotation .getAnnotationTypeAsEnum())) { this.description = new MifBasicAnnotation(annotation.getText()); } else if (AnnotationType.USAGE_CONSTRAINT.equals(annotation .getAnnotationTypeAsEnum())) { this.usageConstraints.add(new MifBasicAnnotation(annotation.getText())); } else if (AnnotationType.USAGE_NOTES.equals(annotation .getAnnotationTypeAsEnum())) { this.usageNotes.add(new MifBasicAnnotation(annotation.getText())); } else if (AnnotationType.RATIONALE.equals(annotation .getAnnotationTypeAsEnum())) { this.rationale = new MifBasicAnnotation(annotation.getText()); } else if (AnnotationType.REQUIREMENTS.equals(annotation .getAnnotationTypeAsEnum())) { this.requirements = new MifBasicAnnotation(annotation.getText()); } else if (AnnotationType.DESIGN_COMMENTS.equals(annotation .getAnnotationTypeAsEnum())) { this.designComments.add(new MifBasicAnnotation(annotation.getText())); } else if (AnnotationType.STABILITY_REMARKS.equals(annotation .getAnnotationTypeAsEnum())) { this.stabilityRemarks.add(new MifBasicAnnotation(annotation.getText())); } else if (AnnotationType.WALKTHROUGH.equals(annotation .getAnnotationTypeAsEnum())) { this.walkthrough = new MifBasicAnnotation(annotation.getText()); } else if (AnnotationType.APPENDIX.equals(annotation .getAnnotationTypeAsEnum())) { this.appendices.add(new MifBasicAnnotation(annotation.getText())); } else if (AnnotationType.OTHER_NOTES.equals(annotation .getAnnotationTypeAsEnum())) { this.otherAnnotations.add(new MifOtherAnnotation(annotation.getText(), annotation.getOtherAnnotationType())); } else { this.unusedAnnotations++ ; } } } public MifBasicAnnotation getDefinition() { return definition; } public MifBasicAnnotation getDescription() { return description; } public List<MifBasicAnnotation> getUsageConstraints() { return usageConstraints; } public List<MifBasicAnnotation> getUsageNotes() { return usageNotes; } public MifBasicAnnotation getRationale() { return rationale; } public List<MifBasicAnnotation> getDesignComments() { return designComments; } public List<MifOtherAnnotation> getOtherAnnotations() { return otherAnnotations; } public int getUnusedAnnotations() { return new Integer(unusedAnnotations); } public MifBasicAnnotation getRequirements() { return requirements; } public MifBasicAnnotation getWalkthrough() { return walkthrough; } }
3e15b592a7340b517e4dd608c4c6133b989b385d
2,404
java
Java
src/main/java/com/google/gson/jpush/internal/a/ac.java
tiwer/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
39
2017-08-07T09:03:54.000Z
2021-09-29T09:31:39.000Z
src/main/java/com/google/gson/jpush/internal/a/ac.java
JackChan1999/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
null
null
null
src/main/java/com/google/gson/jpush/internal/a/ac.java
JackChan1999/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
39
2017-05-08T13:11:39.000Z
2021-12-26T12:42:14.000Z
24.282828
126
0.492928
9,213
package com.google.gson.jpush.internal.a; import com.google.gson.jpush.af; import com.google.gson.jpush.al; import com.google.gson.jpush.b.a; import com.google.gson.jpush.b.c; import com.google.gson.jpush.b.d; import com.google.gson.jpush.internal.v; final class ac extends al<Number> { private static final String z; /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ static { /* r0 = "\u001cI\"\u001c!-X<\u001eb7D?\u001b'+\u001dr\u001e--\u000br"; r0 = r0.toCharArray(); r1 = r0.length; r2 = 0; r3 = 1; if (r1 > r3) goto L_0x0027; L_0x000b: r3 = r0; r4 = r2; r7 = r1; r1 = r0; r0 = r7; L_0x0010: r6 = r1[r2]; r5 = r4 % 5; switch(r5) { case 0: goto L_0x0035; case 1: goto L_0x0038; case 2: goto L_0x003b; case 3: goto L_0x003e; default: goto L_0x0017; }; L_0x0017: r5 = 66; L_0x0019: r5 = r5 ^ r6; r5 = (char) r5; r1[r2] = r5; r2 = r4 + 1; if (r0 != 0) goto L_0x0025; L_0x0021: r1 = r3; r4 = r2; r2 = r0; goto L_0x0010; L_0x0025: r1 = r0; r0 = r3; L_0x0027: if (r1 > r2) goto L_0x000b; L_0x0029: r1 = new java.lang.String; r1.<init>(r0); r0 = r1.intern(); z = r0; return; L_0x0035: r5 = 89; goto L_0x0019; L_0x0038: r5 = 49; goto L_0x0019; L_0x003b: r5 = 82; goto L_0x0019; L_0x003e: r5 = 121; // 0x79 float:1.7E-43 double:6.0E-322; goto L_0x0019; */ throw new UnsupportedOperationException("Method not decompiled: com.google.gson.jpush.internal.a.ac.<clinit>():void"); } ac() { } public final /* synthetic */ Object a(a aVar) { c f = aVar.f(); switch (az.a[f.ordinal()]) { case 1: return new v(aVar.h()); case 4: aVar.j(); return null; default: throw new af(new StringBuilder(z).append(f).toString()); } } public final /* bridge */ /* synthetic */ void a(d dVar, Object obj) { dVar.a((Number) obj); } }
3e15b623156373b97b09ab183bf26c76201f0214
6,977
java
Java
app/src/main/java/org/dhis2/data/user/UserComponent.java
arneroen/dhis2-android-capture-app
dad290fdb0868f15b2ed01268a4fb18d5d17d4cb
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/org/dhis2/data/user/UserComponent.java
arneroen/dhis2-android-capture-app
dad290fdb0868f15b2ed01268a4fb18d5d17d4cb
[ "BSD-3-Clause" ]
4
2019-12-04T13:24:24.000Z
2020-01-23T15:05:29.000Z
app/src/main/java/org/dhis2/data/user/UserComponent.java
arneroen/dhis2-android-capture-app
dad290fdb0868f15b2ed01268a4fb18d5d17d4cb
[ "BSD-3-Clause" ]
null
null
null
40.097701
97
0.846496
9,214
package org.dhis2.data.user; import androidx.annotation.NonNull; import org.dhis2.data.dagger.PerUser; import org.dhis2.data.service.ReservedValuesWorkerComponent; import org.dhis2.data.service.ReservedValuesWorkerModule; import org.dhis2.data.service.SyncDataWorkerComponent; import org.dhis2.data.service.SyncDataWorkerModule; import org.dhis2.data.service.SyncGranularRxComponent; import org.dhis2.data.service.SyncGranularRxModule; import org.dhis2.data.service.SyncInitWorkerComponent; import org.dhis2.data.service.SyncInitWorkerModule; import org.dhis2.data.service.SyncMetadataWorkerComponent; import org.dhis2.data.service.SyncMetadataWorkerModule; import org.dhis2.usescases.about.AboutComponent; import org.dhis2.usescases.about.AboutModule; import org.dhis2.usescases.datasets.dataSetTable.DataSetTableComponent; import org.dhis2.usescases.datasets.dataSetTable.DataSetTableModule; import org.dhis2.usescases.datasets.dataSetTable.dataSetSection.DataValueComponent; import org.dhis2.usescases.datasets.dataSetTable.dataSetSection.DataValueModule; import org.dhis2.usescases.datasets.datasetDetail.DataSetDetailComponent; import org.dhis2.usescases.datasets.datasetDetail.DataSetDetailModule; import org.dhis2.usescases.datasets.datasetInitial.DataSetInitialComponent; import org.dhis2.usescases.datasets.datasetInitial.DataSetInitialModule; import org.dhis2.usescases.enrollment.EnrollmentComponent; import org.dhis2.usescases.enrollment.EnrollmentModule; import org.dhis2.usescases.events.ScheduledEventComponent; import org.dhis2.usescases.events.ScheduledEventModule; import org.dhis2.usescases.eventsWithoutRegistration.eventCapture.EventCaptureComponent; import org.dhis2.usescases.eventsWithoutRegistration.eventCapture.EventCaptureModule; import org.dhis2.usescases.eventsWithoutRegistration.eventInitial.EventInitialComponent; import org.dhis2.usescases.eventsWithoutRegistration.eventInitial.EventInitialModule; import org.dhis2.usescases.eventsWithoutRegistration.eventSummary.EventSummaryComponent; import org.dhis2.usescases.eventsWithoutRegistration.eventSummary.EventSummaryModule; import org.dhis2.usescases.main.MainComponent; import org.dhis2.usescases.main.MainModule; import org.dhis2.usescases.main.program.ProgramComponent; import org.dhis2.usescases.main.program.ProgramModule; import org.dhis2.usescases.programEventDetail.ProgramEventDetailComponent; import org.dhis2.usescases.programEventDetail.ProgramEventDetailModule; import org.dhis2.usescases.programStageSelection.ProgramStageSelectionComponent; import org.dhis2.usescases.programStageSelection.ProgramStageSelectionModule; import org.dhis2.usescases.qrCodes.QrComponent; import org.dhis2.usescases.qrCodes.QrModule; import org.dhis2.usescases.qrCodes.eventsworegistration.QrEventsWORegistrationComponent; import org.dhis2.usescases.qrCodes.eventsworegistration.QrEventsWORegistrationModule; import org.dhis2.usescases.qrReader.QrReaderComponent; import org.dhis2.usescases.qrReader.QrReaderModule; import org.dhis2.usescases.reservedValue.ReservedValueComponent; import org.dhis2.usescases.reservedValue.ReservedValueModule; import org.dhis2.usescases.searchTrackEntity.SearchTEComponent; import org.dhis2.usescases.searchTrackEntity.SearchTEModule; import org.dhis2.usescases.settings.SyncManagerComponent; import org.dhis2.usescases.settings.SyncManagerModule; import org.dhis2.usescases.sms.SmsComponent; import org.dhis2.usescases.sms.SmsModule; import org.dhis2.usescases.sync.SyncComponent; import org.dhis2.usescases.sync.SyncModule; import org.dhis2.usescases.teiDashboard.TeiDashboardComponent; import org.dhis2.usescases.teiDashboard.TeiDashboardModule; import org.dhis2.usescases.teiDashboard.nfc_data.NfcDataWriteComponent; import org.dhis2.usescases.teiDashboard.nfc_data.NfcDataWriteModule; import org.dhis2.usescases.teiDashboard.teiProgramList.TeiProgramListComponent; import org.dhis2.usescases.teiDashboard.teiProgramList.TeiProgramListModule; import org.dhis2.usescases.videoLibrary.VideoComponent; import org.dhis2.usescases.videoLibrary.VideoModule; import org.dhis2.utils.optionset.OptionSetComponent; import org.dhis2.utils.optionset.OptionSetModule; import dagger.Subcomponent; @PerUser @Subcomponent(modules = UserModule.class) public interface UserComponent { @NonNull MainComponent plus(@NonNull MainModule mainModule); @NonNull ProgramEventDetailComponent plus(@NonNull ProgramEventDetailModule programEventDetailModule); @NonNull SearchTEComponent plus(@NonNull SearchTEModule searchTEModule); @NonNull TeiDashboardComponent plus(@NonNull TeiDashboardModule dashboardModule); @NonNull QrComponent plus(@NonNull QrModule qrModule); @NonNull QrEventsWORegistrationComponent plus(@NonNull QrEventsWORegistrationModule qrModule); @NonNull TeiProgramListComponent plus(@NonNull TeiProgramListModule teiProgramListModule); @NonNull ProgramComponent plus(@NonNull ProgramModule programModule); @NonNull EventInitialComponent plus(EventInitialModule eventInitialModule); @NonNull EventSummaryComponent plus(EventSummaryModule eventInitialModule); @NonNull SyncManagerComponent plus(SyncManagerModule syncManagerModule); @NonNull ProgramStageSelectionComponent plus(ProgramStageSelectionModule programStageSelectionModule); @NonNull QrReaderComponent plus(QrReaderModule qrReaderModule); @NonNull AboutComponent plus(AboutModule aboutModule); @NonNull VideoComponent plus(VideoModule videoModule); @NonNull DataSetDetailComponent plus(DataSetDetailModule dataSetDetailModel); @NonNull DataSetInitialComponent plus(DataSetInitialModule dataSetInitialModule); @NonNull DataSetTableComponent plus(DataSetTableModule dataSetTableModule); @NonNull DataValueComponent plus(DataValueModule dataValueModule); @NonNull ReservedValueComponent plus(ReservedValueModule reservedValueModule); @NonNull SyncDataWorkerComponent plus(SyncDataWorkerModule syncDataWorkerModule); @NonNull SyncMetadataWorkerComponent plus(SyncMetadataWorkerModule syncDataWorkerModule); @NonNull ReservedValuesWorkerComponent plus(ReservedValuesWorkerModule reservedValuesWorkerModule); @NonNull EventCaptureComponent plus(EventCaptureModule eventCaptureModule); @NonNull SmsComponent plus(SmsModule smsModule); NfcDataWriteComponent plus(NfcDataWriteModule nfcModule); @NonNull SyncGranularRxComponent plus(SyncGranularRxModule syncGranularRxModule); @NonNull SyncComponent plus(SyncModule syncModule); @NonNull SyncInitWorkerComponent plus(SyncInitWorkerModule syncInitWorkerModule); @NonNull EnrollmentComponent plus(EnrollmentModule enrollmentModule); @NonNull ScheduledEventComponent plus(ScheduledEventModule scheduledEventModule); @NonNull OptionSetComponent plus(OptionSetModule optionSetModule); }
3e15b64a427774c3260127493699b9c8b810ebf1
739
java
Java
src/main/java/de/dth/mdr/validator/enums/EnumDateFormat.java
samply/common-mdrvalidator
7325bc0cb24df0b373932c1c58f4fd5f9ee947f6
[ "Apache-2.0" ]
null
null
null
src/main/java/de/dth/mdr/validator/enums/EnumDateFormat.java
samply/common-mdrvalidator
7325bc0cb24df0b373932c1c58f4fd5f9ee947f6
[ "Apache-2.0" ]
3
2022-01-03T14:37:24.000Z
2022-01-03T14:37:43.000Z
src/main/java/de/dth/mdr/validator/enums/EnumDateFormat.java
samply/common-mdrvalidator
7325bc0cb24df0b373932c1c58f4fd5f9ee947f6
[ "Apache-2.0" ]
null
null
null
17.186047
62
0.634641
9,215
package de.dth.mdr.validator.enums; import org.apache.commons.lang.StringUtils; /** * Date format types, as known from MDR. */ public enum EnumDateFormat { /** * A date defined in the session locale format. */ LOCAL_DATE, /** * ISO 8601 date. */ ISO_8601, /** * DIN 5008 date. */ DIN_5008, /** * A date defined in the session locale format, with days. */ LOCAL_DATE_WITH_DAYS, /** * ISO 8601 date, with days. */ ISO_8601_WITH_DAYS, /** * DIN 5008 date, with days. */ DIN_5008_WITH_DAYS, /** * DIN 5008 date, only with years. */ DIN_5008_ONLY_YEAR; public static EnumDateFormat valueOfTrimmed(String format) { return valueOf(StringUtils.trim(format)); } }
3e15b6bf6a5bb6b23318521f9f14b8d412ea69bf
1,463
java
Java
src/main/java/br/dev/amvs/jasked/jpa/domain/Role.java
marcossales/jasked
9a7d7147290e2c04d2469432d83a37c31c08f485
[ "MIT" ]
null
null
null
src/main/java/br/dev/amvs/jasked/jpa/domain/Role.java
marcossales/jasked
9a7d7147290e2c04d2469432d83a37c31c08f485
[ "MIT" ]
null
null
null
src/main/java/br/dev/amvs/jasked/jpa/domain/Role.java
marcossales/jasked
9a7d7147290e2c04d2469432d83a37c31c08f485
[ "MIT" ]
null
null
null
17.626506
63
0.666439
9,216
package br.dev.amvs.jasked.jpa.domain; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the role database table. * */ @Entity @Table(name = "role", schema = "jasked") @NamedQuery(name="Role.findAll", query="SELECT r FROM Role r") public class Role implements Identifiable<Integer> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String description; private String name; public Role() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Role other = (Role) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return this.name; } }
3e15b793cc19a00dd4e070d5d727bd9acaed26fd
44,296
java
Java
JavaSource/org/unitime/timetable/solver/studentsct/StudentSolver.java
sktoo/timetabling-system-
1806aded50c3486ea4ba6d168b64ea17070400f2
[ "Apache-2.0" ]
null
null
null
JavaSource/org/unitime/timetable/solver/studentsct/StudentSolver.java
sktoo/timetabling-system-
1806aded50c3486ea4ba6d168b64ea17070400f2
[ "Apache-2.0" ]
null
null
null
JavaSource/org/unitime/timetable/solver/studentsct/StudentSolver.java
sktoo/timetabling-system-
1806aded50c3486ea4ba6d168b64ea17070400f2
[ "Apache-2.0" ]
null
null
null
37.634664
195
0.642947
9,217
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.solver.studentsct; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cpsolver.ifs.assignment.DefaultSingleAssignment; import org.cpsolver.ifs.model.Constraint; import org.cpsolver.ifs.solution.Solution; import org.cpsolver.ifs.solver.ParallelSolver; import org.cpsolver.ifs.util.CSVFile; import org.cpsolver.ifs.util.Callback; import org.cpsolver.ifs.util.DataProperties; import org.cpsolver.ifs.util.DistanceMetric; import org.cpsolver.ifs.util.Progress; import org.cpsolver.ifs.util.ProgressWriter; import org.cpsolver.studentsct.StudentSectioningLoader; import org.cpsolver.studentsct.StudentSectioningModel; import org.cpsolver.studentsct.StudentSectioningSaver; import org.cpsolver.studentsct.StudentSectioningXMLLoader; import org.cpsolver.studentsct.StudentSectioningXMLSaver; import org.cpsolver.studentsct.model.Course; import org.cpsolver.studentsct.model.CourseRequest; import org.cpsolver.studentsct.model.Enrollment; import org.cpsolver.studentsct.model.FreeTimeRequest; import org.cpsolver.studentsct.model.Offering; import org.cpsolver.studentsct.model.Request; import org.cpsolver.studentsct.model.Section; import org.cpsolver.studentsct.model.Student; import org.cpsolver.studentsct.online.expectations.NeverOverExpected; import org.cpsolver.studentsct.online.expectations.OverExpectedCriterion; import org.cpsolver.studentsct.report.SectionConflictTable; import org.cpsolver.studentsct.report.StudentSectioningReport; import org.unitime.localization.impl.Localization; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.gwt.resources.StudentSectioningMessages; import org.unitime.timetable.gwt.shared.CourseRequestInterface; import org.unitime.timetable.gwt.shared.SectioningException; import org.unitime.timetable.model.CourseOffering; import org.unitime.timetable.model.TravelTime; import org.unitime.timetable.model.dao.CourseOfferingDAO; import org.unitime.timetable.model.dao.SessionDAO; import org.unitime.timetable.onlinesectioning.AcademicSessionInfo; import org.unitime.timetable.onlinesectioning.OnlineSectioningAction; import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog.Entity; import org.unitime.timetable.onlinesectioning.custom.CourseDetailsProvider; import org.unitime.timetable.onlinesectioning.match.CourseMatcher; import org.unitime.timetable.onlinesectioning.match.StudentMatcher; import org.unitime.timetable.onlinesectioning.model.XCourse; import org.unitime.timetable.onlinesectioning.model.XCourseId; import org.unitime.timetable.onlinesectioning.model.XCourseRequest; import org.unitime.timetable.onlinesectioning.model.XEnrollment; import org.unitime.timetable.onlinesectioning.model.XEnrollments; import org.unitime.timetable.onlinesectioning.model.XExpectations; import org.unitime.timetable.onlinesectioning.model.XOffering; import org.unitime.timetable.onlinesectioning.model.XStudent; import org.unitime.timetable.onlinesectioning.model.XStudentId; import org.unitime.timetable.onlinesectioning.model.XTime; import org.unitime.timetable.solver.remote.BackupFileFilter; import org.unitime.timetable.util.Constants; import org.unitime.timetable.util.MemoryCounter; /** * @author Tomas Muller */ public class StudentSolver extends ParallelSolver<Request, Enrollment> implements StudentSolverProxy { private static StudentSectioningMessages MSG = Localization.create(StudentSectioningMessages.class); private static Log sLog = LogFactory.getLog(StudentSolver.class); private int iDebugLevel = Progress.MSGLEVEL_INFO; private boolean iWorking = false; private Date iLoadedDate = null; private StudentSolverDisposeListener iDisposeListener = null; private long iLastTimeStamp = System.currentTimeMillis(); private boolean iIsPassivated = false; private Map iProgressBeforePassivation = null; private Map<String, String> iCurrentSolutionInfoBeforePassivation = null; private Map<String, String> iBestSolutionInfoBeforePassivation = null; private File iPassivationFolder = null; private String iPassivationPuid = null; private Thread iWorkThread = null; private transient Map<Long, XCourse> iCourseInfoCache = null; private Map<String, Object> iOnlineProperties = new HashMap<String, Object>(); public StudentSolver(DataProperties properties, StudentSolverDisposeListener disposeListener) { super(properties); iDisposeListener = disposeListener; } public Date getLoadedDate() { if (iLoadedDate==null && !isPassivated()) { List<Progress.Message> log = Progress.getInstance(currentSolution().getModel()).getLog(); if (log!=null && !log.isEmpty()) { iLoadedDate = log.get(0).getDate(); } } return iLoadedDate; } public String getLog() { return Progress.getInstance(currentSolution().getModel()).getHtmlLog(iDebugLevel, true); } public String getLog(int level, boolean includeDate) { return Progress.getInstance(currentSolution().getModel()).getHtmlLog(level, includeDate); } public String getLog(int level, boolean includeDate, String fromStage) { return Progress.getInstance(currentSolution().getModel()).getHtmlLog(level, includeDate, fromStage); } public void setDebugLevel(int level) { iDebugLevel = level; } public int getDebugLevel() { return iDebugLevel; } public boolean isWorking() { if (isRunning()) return true; return iWorking; } public void restoreBest() { currentSolution().restoreBest(); } public void saveBest() { currentSolution().saveBest(); if (currentSolution().getBestInfo() != null) currentSolution().getBestInfo().putAll(currentSolution().getModel().getExtendedInfo(currentSolution().getAssignment())); } public Map getProgress() { if (isPassivated()) return iProgressBeforePassivation; try { Hashtable ret = new Hashtable(); Progress p = Progress.getInstance(super.currentSolution().getModel()); ret.put("STATUS",p.getStatus()); ret.put("PHASE",p.getPhase()); ret.put("PROGRESS",new Long(p.getProgress())); ret.put("MAX_PROGRESS",new Long(p.getProgressMax())); ret.put("VERSION", Constants.getVersion()); return ret; } catch (Exception e) { sLog.error(e.getMessage(),e); return null; } } public void setProperties(DataProperties properties) { activateIfNeeded(); this.getProperties().putAll(properties); } public void dispose() { disposeNoInherit(true); } private void disposeNoInherit(boolean unregister) { super.dispose(); if (currentSolution()!=null && currentSolution().getModel()!=null) Progress.removeInstance(currentSolution().getModel()); setInitalSolution((org.cpsolver.ifs.solution.Solution)null); if (unregister && iDisposeListener!=null) iDisposeListener.onDispose(); clearCourseInfoTable(); } public String getHost() { return "local"; } public String getUser() { return getProperties().getProperty("General.OwnerPuid"); } public Object exec(Object[] cmd) throws Exception { Class[] types = new Class[(cmd.length-3)/2]; Object[] args = new Object[(cmd.length-3)/2]; for (int i=0;i<types.length;i++) { types[i]=(Class)cmd[2*i+3]; args[i]=cmd[2*i+4]; } return getClass().getMethod((String)cmd[0],types).invoke(this, args); } public Map<String,String> currentSolutionInfo() { if (isPassivated()) return iCurrentSolutionInfoBeforePassivation; java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { return super.currentSolution().getExtendedInfo(); } finally { lock.unlock(); } } public Map<String,String> bestSolutionInfo() { if (isPassivated()) return iBestSolutionInfoBeforePassivation; java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { return super.currentSolution().getBestInfo(); } finally { lock.unlock(); } } protected void onFinish() { super.onFinish(); try { iWorking = true; if (currentSolution().getBestInfo()!=null) currentSolution().restoreBest(); if (currentSolution().getBestInfo()!=null && getProperties().getPropertyBoolean("General.Save",false)) { StudentSectioningSaver saver = new StudentSectioningDatabaseSaver(this); java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { saver.save(); } catch (Exception e) { Progress.getInstance(currentSolution().getModel()).error(e.getMessage(),e); } finally { lock.unlock(); } } if (getProperties().getPropertyBoolean("General.Unload",false)) { dispose(); } else { Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ..."); } } finally { iWorking = false; } } protected void onStop() { super.onStop(); if (currentSolution().getBestInfo()!=null) currentSolution().restoreBest(); } public void save() { iWorking = true; StudentSectioningSaver saver = new StudentSectioningDatabaseSaver(this); saver.setCallback(getSavingDoneCallback()); iWorkThread = new Thread(saver); iWorkThread.setPriority(THREAD_PRIORITY); iWorkThread.start(); } public void load(DataProperties properties) { setProperties(properties); StudentSectioningModel model = new StudentSectioningModel(getProperties()); Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out)); iWorking = true; setInitalSolution(new Solution(model, new DefaultSingleAssignment<Request, Enrollment>())); initSolver(); StudentSectioningLoader loader = new StudentSectioningDatabaseLoader(model, currentSolution().getAssignment()); loader.setCallback(getLoadingDoneCallback()); iWorkThread = new Thread(loader); iWorkThread.setPriority(THREAD_PRIORITY); iWorkThread.start(); } public void reload(DataProperties properties) { if (currentSolution()==null || currentSolution().getModel()==null) { load(properties); return; } Callback callBack = getReloadingDoneCallback(); setProperties(properties); StudentSectioningModel model = new StudentSectioningModel(getProperties()); iWorking = true; Progress.changeInstance(currentSolution().getModel(),model); setInitalSolution(new Solution(model, new DefaultSingleAssignment<Request, Enrollment>())); initSolver(); StudentSectioningLoader loader = new StudentSectioningDatabaseLoader(model, currentSolution().getAssignment()); loader.setCallback(callBack); iWorkThread = new Thread(loader); iWorkThread.start(); } public Callback getLoadingDoneCallback() { return new LoadingDoneCallback(); } public Callback getReloadingDoneCallback() { return new ReloadingDoneCallback(); } public Callback getSavingDoneCallback() { return new SavingDoneCallback(); } protected void afterSave() { } protected void afterLoad() { } protected void afterFinalSectioning() { } public class ReloadingDoneCallback implements Callback { Map<Long, Map<Long, Enrollment>> iCurrentAssignmentTable = new Hashtable<Long, Map<Long,Enrollment>>(); Map<Long, Map<Long, Enrollment>> iBestAssignmentTable = new Hashtable<Long, Map<Long,Enrollment>>(); Map<Long, Map<Long, Enrollment>> iInitialAssignmentTable = new Hashtable<Long, Map<Long,Enrollment>>(); String iSolutionId = null; Progress iProgress = null; public ReloadingDoneCallback() { iSolutionId = getProperties().getProperty("General.SolutionId"); for (Request request: currentSolution().getModel().variables()) { Enrollment enrollment = currentSolution().getAssignment().getValue(request); if (enrollment != null) { Map<Long, Enrollment> assignments = iCurrentAssignmentTable.get(request.getStudent().getId()); if (assignments == null) { assignments = new Hashtable<Long, Enrollment>(); iCurrentAssignmentTable.put(request.getStudent().getId(), assignments); } assignments.put(request.getId(), enrollment); } if (request.getBestAssignment() != null) { Map<Long, Enrollment> assignments = iBestAssignmentTable.get(request.getStudent().getId()); if (assignments == null) { assignments = new Hashtable<Long, Enrollment>(); iBestAssignmentTable.put(request.getStudent().getId(), assignments); } assignments.put(request.getId(), request.getBestAssignment()); } if (request.getInitialAssignment() != null) { Map<Long, Enrollment> assignments = iInitialAssignmentTable.get(request.getStudent().getId()); if (assignments == null) { assignments = new Hashtable<Long, Enrollment>(); iInitialAssignmentTable.put(request.getStudent().getId(), assignments); } assignments.put(request.getId(), request.getInitialAssignment()); } } } private Enrollment getEnrollment(Request request, Enrollment enrollment) { if (request instanceof FreeTimeRequest) { return ((FreeTimeRequest)request).createEnrollment(); } else { CourseRequest cr = (CourseRequest)request; Set<Section> sections = new HashSet<Section>(); for (Section s: enrollment.getSections()) { Section section = cr.getSection(s.getId()); if (section == null) { iProgress.warn("WARNING: Section "+s.getName()+" is not available for "+cr.getName()); return null; } sections.add(section); } return cr.createEnrollment(currentSolution().getAssignment(), sections); } } private void assign(Enrollment enrollment) { Map<Constraint<Request, Enrollment>, Set<Enrollment>> conflictConstraints = currentSolution().getModel().conflictConstraints(currentSolution().getAssignment(), enrollment); if (conflictConstraints.isEmpty()) { currentSolution().getAssignment().assign(0, enrollment); } else { iProgress.warn("Unable to assign "+enrollment.variable().getName()+" := "+enrollment.getName()); iProgress.warn("&nbsp;&nbsp;Reason:"); for (Constraint<Request, Enrollment> c: conflictConstraints.keySet()) { Set<Enrollment> vals = conflictConstraints.get(c); for (Enrollment enrl: vals) { iProgress.warn("&nbsp;&nbsp;&nbsp;&nbsp;"+enrl.getRequest().getName()+" = "+enrl.getName()); } iProgress.debug("&nbsp;&nbsp;&nbsp;&nbsp;in constraint "+c); } } } private void unassignAll() { for (Request request: currentSolution().getModel().variables()) { currentSolution().getAssignment().unassign(0l, request); } } public void execute() { iProgress = Progress.getInstance(currentSolution().getModel()); Map<Long, Map<Long, Request>> requests = new Hashtable<Long, Map<Long,Request>>(); for (Request request: currentSolution().getModel().variables()) { Map<Long, Request> r = requests.get(request.getStudent().getId()); if (r == null) { r = new Hashtable<Long, Request>(); requests.put(request.getStudent().getId(), r); } r.put(request.getId(), request); } if (!iBestAssignmentTable.isEmpty()) { iProgress.setPhase("Creating best assignment ...", iBestAssignmentTable.size()); unassignAll(); for (Map.Entry<Long, Map<Long, Enrollment>> e1: iBestAssignmentTable.entrySet()) { Map<Long, Request> r = requests.get(e1.getKey()); iProgress.incProgress(); if (r == null) continue; for (Map.Entry<Long, Enrollment> e2: e1.getValue().entrySet()) { Request request = r.get(e2.getKey()); if (request == null) continue; Enrollment enrollment = getEnrollment(request, e2.getValue()); if (enrollment!=null) assign(enrollment); } } currentSolution().saveBest(); } if (!iInitialAssignmentTable.isEmpty()) { iProgress.setPhase("Creating initial assignment ...", iInitialAssignmentTable.size()); for (Map.Entry<Long, Map<Long, Enrollment>> e1: iInitialAssignmentTable.entrySet()) { Map<Long, Request> r = requests.get(e1.getKey()); iProgress.incProgress(); if (r == null) continue; for (Map.Entry<Long, Enrollment> e2: e1.getValue().entrySet()) { Request request = r.get(e2.getKey()); if (request == null) continue; Enrollment enrollment = getEnrollment(request, e2.getValue()); if (enrollment!=null) request.setInitialAssignment(enrollment); } } } if (!iCurrentAssignmentTable.isEmpty()) { iProgress.setPhase("Creating current assignment ...", iCurrentAssignmentTable.size()); unassignAll(); for (Map.Entry<Long, Map<Long, Enrollment>> e1: iCurrentAssignmentTable.entrySet()) { Map<Long, Request> r = requests.get(e1.getKey()); iProgress.incProgress(); if (r == null) continue; for (Map.Entry<Long, Enrollment> e2: e1.getValue().entrySet()) { Request request = r.get(e2.getKey()); if (request == null) continue; Enrollment enrollment = getEnrollment(request, e2.getValue()); if (enrollment!=null) assign(enrollment); } } } iCurrentAssignmentTable.clear(); iBestAssignmentTable.clear(); iInitialAssignmentTable.clear(); iProgress = null; if (iSolutionId!=null) getProperties().setProperty("General.SolutionId",iSolutionId); iLoadedDate = new Date(); iWorking = false; afterLoad(); Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ..."); } } public class LoadingDoneCallback implements Callback { public void execute() { iLoadedDate = new Date(); iWorking = false; afterLoad(); Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ..."); if (getProperties().getPropertyBoolean("General.StartSolver",false)) start(); } } public class SavingDoneCallback implements Callback { public void execute() { iWorking = false; afterSave(); Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ..."); } } public static interface StudentSolverDisposeListener { public void onDispose(); } public boolean backup(File folder, String puid) { folder.mkdirs(); if (currentSolution()==null) return false; java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { getProperties().setProperty("Xml.SaveBest", "true"); getProperties().setProperty("Xml.SaveInitial", "true"); getProperties().setProperty("Xml.SaveCurrent", "true"); File outXmlFile = new File(folder,"sct_"+puid+BackupFileFilter.sXmlExtension); File outPropertiesFile = new File(folder,"sct_"+puid+BackupFileFilter.sPropertiesExtension); try { new StudentSectioningXMLSaver(this).save(outXmlFile); for (Iterator i=getProperties().entrySet().iterator();i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); if (!(entry.getKey() instanceof String)) { sLog.error("Configuration key "+entry.getKey()+" is not of type String ("+entry.getKey().getClass()+")"); i.remove(); } else if (!(entry.getValue() instanceof String)) { sLog.error("Value of configuration key "+entry.getKey()+" is not of type String ("+entry.getValue()+" is of type "+entry.getValue().getClass()+")"); i.remove(); } } FileOutputStream fos = null; try { fos = new FileOutputStream(outPropertiesFile); getProperties().store(fos,"Backup file"); fos.flush(); fos.close(); fos=null; } finally { try { if (fos!=null) fos.close(); } catch (IOException e) {} } return true; } catch (Exception e) { sLog.error(e.getMessage(),e); if (outXmlFile.exists()) outXmlFile.delete(); if (outPropertiesFile.exists()) outPropertiesFile.delete(); } } finally { lock.unlock(); } return false; } public boolean restore(File folder, String puid) { return restore(folder, puid, false); } public boolean restore(File folder, String puid, boolean removeFiles) { sLog.debug("restore(folder="+folder+","+puid+",sct)"); File inXmlFile = new File(folder,"sct_"+puid+BackupFileFilter.sXmlExtension); File inPropertiesFile = new File(folder,"sct_"+puid+BackupFileFilter.sPropertiesExtension); StudentSectioningModel model = null; try { if (isRunning()) stopSolver(); disposeNoInherit(false); FileInputStream fis = null; try { fis = new FileInputStream(inPropertiesFile); getProperties().load(fis); } finally { if (fis!=null) fis.close(); } model = new StudentSectioningModel(getProperties()); Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out)); setInitalSolution(new Solution(model, new DefaultSingleAssignment<Request, Enrollment>())); initSolver(); getProperties().setProperty("Xml.LoadBest", "true"); getProperties().setProperty("Xml.LoadInitial", "true"); getProperties().setProperty("Xml.LoadCurrent", "true"); StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(model, currentSolution().getAssignment()); loader.setInputFile(inXmlFile); loader.setCallback(new Callback() { public void execute() { saveBest(); } }); loader.load(); Progress.getInstance(model).setStatus("Awaiting commands ..."); if (removeFiles) { inXmlFile.delete(); inPropertiesFile.delete(); } return true; } catch (Exception e) { sLog.error(e.getMessage(),e); if (model!=null) Progress.removeInstance(model); } return false; } public void clear() { java.util.concurrent.locks.Lock lock = currentSolution().getLock().writeLock(); lock.lock(); try { for (Request request: currentSolution().getModel().variables()) { currentSolution().getAssignment().unassign(0, request); } currentSolution().clearBest(); } finally { lock.unlock(); } } public Long getSessionId() { return getProperties().getPropertyLong("General.SessionId",null); } public Solution<Request, Enrollment> currentSolution() { activateIfNeeded(); return super.currentSolution(); } public void start() { activateIfNeeded(); super.start(); } public synchronized boolean isPassivated() { return iIsPassivated; } public synchronized long timeFromLastUsed() { return System.currentTimeMillis()-iLastTimeStamp; } public synchronized boolean activateIfNeeded() { iLastTimeStamp = System.currentTimeMillis(); if (!isPassivated()) return false; sLog.debug("<activate "+iPassivationPuid+">"); iIsPassivated = false; System.gc(); sLog.debug(" -- memory usage before activation:"+org.unitime.commons.Debug.getMem()); restore(iPassivationFolder, iPassivationPuid, true); System.gc(); sLog.debug(" -- memory usage after activation:"+org.unitime.commons.Debug.getMem()); return true; } public synchronized boolean passivate(File folder, String puid) { if (isPassivated() || super.currentSolution()==null || super.currentSolution().getModel()==null) return false; sLog.debug("<passivate "+puid+">"); System.gc(); sLog.debug(" -- memory usage before passivation:"+org.unitime.commons.Debug.getMem()); iProgressBeforePassivation = getProgress(); if (iProgressBeforePassivation!=null) iProgressBeforePassivation.put("STATUS","Pasivated"); iCurrentSolutionInfoBeforePassivation = currentSolutionInfo(); iBestSolutionInfoBeforePassivation = bestSolutionInfo(); iPassivationFolder = folder; iPassivationPuid = puid; backup(iPassivationFolder, iPassivationPuid); disposeNoInherit(false); System.gc(); sLog.debug(" -- memory usage after passivation:"+org.unitime.commons.Debug.getMem()); iIsPassivated = true; return true; } public synchronized boolean passivateIfNeeded(File folder, String puid) { long inactiveTimeToPassivate = 60000l * ApplicationProperty.SolverPasivationTime.intValue(); if (isPassivated() || inactiveTimeToPassivate <= 0 || timeFromLastUsed() < inactiveTimeToPassivate || isWorking()) return false; return passivate(folder, puid); } public Date getLastUsed() { return new Date(iLastTimeStamp); } public void interrupt() { try { if (iSolverThread != null) { iStop = true; if (iSolverThread.isAlive() && !iSolverThread.isInterrupted()) iSolverThread.interrupt(); } if (iWorkThread != null && iWorkThread.isAlive() && !iWorkThread.isInterrupted()) { iWorkThread.interrupt(); } } catch (Exception e) { sLog.error("Unable to interrupt the solver, reason: " + e.getMessage(), e); } } public Map<String,String> statusSolutionInfo() { if (isPassivated()) return (iBestSolutionInfoBeforePassivation == null ? iCurrentSolutionInfoBeforePassivation : iBestSolutionInfoBeforePassivation); java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { Map<String,String> info = super.currentSolution().getBestInfo(); try { if (info == null || getSolutionComparator().isBetterThanBestSolution(super.currentSolution())) info = super.currentSolution().getModel().getInfo(super.currentSolution().getAssignment()); } catch (ConcurrentModificationException e) {} return info; } finally { lock.unlock(); } } private AcademicSessionInfo iSession = null; @Override public AcademicSessionInfo getAcademicSession() { if (iSession == null) { org.hibernate.Session hibSession = SessionDAO.getInstance().createNewSession(); try { iSession = new AcademicSessionInfo(SessionDAO.getInstance().get(getSessionId(), hibSession)); iSession.setSectioningEnabled(false); } finally { hibSession.close(); } } return iSession; } private DistanceMetric iDistanceMetric = null; @Override public DistanceMetric getDistanceMetric() { if (iDistanceMetric == null) { iDistanceMetric = new DistanceMetric(getProperties()); TravelTime.populateTravelTimes(iDistanceMetric); } return iDistanceMetric; } @Override public DataProperties getConfig() { return getProperties(); } private Map<Long, XCourse> getCourseInfoTable() { if (iCourseInfoCache == null) { org.hibernate.Session hibSession = CourseOfferingDAO.getInstance().createNewSession(); try { iCourseInfoCache = new Hashtable<Long, XCourse>(); for (CourseOffering course: (List<CourseOffering>)hibSession.createQuery( "from CourseOffering x where x.subjectArea.session.uniqueId = :sessionId" ).setLong("sessionId", getSessionId()).setCacheable(true).list()) { iCourseInfoCache.put(course.getUniqueId(), new XCourse(course)); } } finally { hibSession.close(); } } return iCourseInfoCache; } private void clearCourseInfoTable() { iCourseInfoCache = null; } @Override public Collection<XCourseId> findCourses(String query, Integer limit, CourseMatcher matcher) { if (matcher != null) matcher.setServer(this); List<XCourseId> ret = new ArrayList<XCourseId>(limit == null ? 100 : limit); String queryInLowerCase = query.toLowerCase(); for (XCourse c : getCourseInfoTable().values()) { if (c.matchCourseName(queryInLowerCase) && (matcher == null || matcher.match(c))) ret.add(c); if (limit != null && ret.size() == limit) return ret; } if (queryInLowerCase.length() > 2) { for (XCourse c : getCourseInfoTable().values()) { if (c.matchTitle(queryInLowerCase) && (matcher == null || matcher.match(c))) ret.add(c); if (limit != null && ret.size() == limit) return ret; } } return ret; } @Override public Collection<XCourseId> findCourses(CourseMatcher matcher) { if (matcher != null) matcher.setServer(this); List<XCourseId> ret = new ArrayList<XCourseId>(); for (XCourse c : getCourseInfoTable().values()) if (matcher.match(c)) ret.add(c); return ret; } @Override public Collection<XStudentId> findStudents(StudentMatcher matcher) { if (matcher != null) matcher.setServer(this); List<XStudentId> ret = new ArrayList<XStudentId>(); for (Student student: ((StudentSectioningModel)currentSolution().getModel()).getStudents()) { if (student.isDummy()) continue; XStudentId s = new XStudentId(student); if (!student.isDummy() && matcher.match(s)) ret.add(s); } return ret; } @Override public XCourse getCourse(Long courseId) { return getCourseInfoTable().get(courseId); } @Override public XCourse getCourse(String courseName) { for (Offering offering: ((StudentSectioningModel)currentSolution().getModel()).getOfferings()) for (Course course: offering.getCourses()) if (course.getName().equalsIgnoreCase(courseName)) return getCourse(course.getId()); return null; } @Override public XStudent getStudent(Long studentId) { for (Student student: ((StudentSectioningModel)currentSolution().getModel()).getStudents()) if (!student.isDummy() && student.getId() == studentId) return new XStudent(student, currentSolution().getAssignment()); return null; } @Override public XOffering getOffering(Long offeringId) { for (Offering offering: ((StudentSectioningModel)currentSolution().getModel()).getOfferings()) if (offering.getId() == offeringId) return new XOffering(offering, ((StudentSectioningModel)currentSolution().getModel()).getLinkedSections()); return null; } @Override public <X extends OnlineSectioningAction> X createAction(Class<X> clazz) { try { return clazz.newInstance(); } catch (InstantiationException e) { throw new SectioningException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new SectioningException(e.getMessage(), e); } } @Override public <E> E execute(OnlineSectioningAction<E> action, Entity user) throws SectioningException { long c0 = OnlineSectioningHelper.getCpuTime(); OnlineSectioningHelper h = new OnlineSectioningHelper(user); try { h.addMessageHandler(new OnlineSectioningHelper.DefaultMessageLogger(LogFactory.getLog(action.getClass().getName() + "." + action.name() + "[" + getAcademicSession().toCompactString() + "]"))); h.addAction(action, getAcademicSession()); E ret = action.execute(this, h); if (h.getAction() != null && !h.getAction().hasResult()) { if (ret == null) h.getAction().setResult(OnlineSectioningLog.Action.ResultType.NULL); else if (ret instanceof Boolean) h.getAction().setResult((Boolean)ret ? OnlineSectioningLog.Action.ResultType.TRUE : OnlineSectioningLog.Action.ResultType.FALSE); else h.getAction().setResult(OnlineSectioningLog.Action.ResultType.SUCCESS); } return ret; } catch (Exception e) { if (e instanceof SectioningException) { if (e.getCause() == null) { h.info("Execution failed: " + e.getMessage()); } else { h.warn("Execution failed: " + e.getMessage(), e.getCause()); } } else { h.error("Execution failed: " + e.getMessage(), e); } if (h.getAction() != null) { h.getAction().setResult(OnlineSectioningLog.Action.ResultType.FAILURE); if (e.getCause() != null && e instanceof SectioningException) h.getAction().addMessage(OnlineSectioningLog.Message.newBuilder() .setLevel(OnlineSectioningLog.Message.Level.FATAL) .setText(e.getCause().getClass().getName() + ": " + e.getCause().getMessage())); else h.getAction().addMessage(OnlineSectioningLog.Message.newBuilder() .setLevel(OnlineSectioningLog.Message.Level.FATAL) .setText(e.getMessage() == null ? "null" : e.getMessage())); } if (e instanceof SectioningException) throw (SectioningException)e; throw new SectioningException(MSG.exceptionUnknown(e.getMessage()), e); } finally { if (h.getAction() != null) h.getAction().setEndTime(System.currentTimeMillis()).setCpuTime(OnlineSectioningHelper.getCpuTime() - c0); sLog.debug("Executed: " + h.getLog() + " (" + h.getLog().toByteArray().length + " bytes)"); } } @Override public <E> void execute(OnlineSectioningAction<E> action, Entity user, ServerCallback<E> callback) throws SectioningException { try { callback.onSuccess(execute(action, user)); } catch (Throwable t) { callback.onFailure(t); } } @Override public void clearAll() { } @Override public void clearAllStudents() { } @Override public Lock readLock() { return new NoLock(); } @Override public Lock writeLock() { return new NoLock(); } @Override public Lock lockAll() { return new NoLock(); } @Override public Lock lockStudent(Long studentId, Collection<Long> offeringIds, boolean excludeLockedOfferings) { return new NoLock(); } @Override public Lock lockOffering(Long offeringId, Collection<Long> studentIds, boolean excludeLockedOffering) { return new NoLock(); } @Override public Lock lockRequest(CourseRequestInterface request) { return new NoLock(); } @Override public boolean isOfferingLocked(Long offeringId) { return false; } @Override public void lockOffering(Long offeringId) { } @Override public void unlockOffering(Long offeringId) { } @Override public Collection<Long> getLockedOfferings() { return null; } @Override public void releaseAllOfferingLocks() { } @Override public void persistExpectedSpaces(Long offeringId) { } @Override public List<Long> getOfferingsToPersistExpectedSpaces(long minimalAge) { return null; } @Override public void unload() { } public static class NoLock implements Lock { @Override public void release() { } } @Override public boolean needPersistExpectedSpaces(Long offeringId) { return false; } public byte[] exportXml() throws Exception { java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { File temp = File.createTempFile("student-" + getSessionId(), ".xml"); boolean anonymize = ApplicationProperty.SolverXMLExportNames.isFalse(); boolean idconv = ApplicationProperty.SolverXMLExportConvertIds.isTrue(); getProperties().setProperty("Xml.SaveBest", "true"); getProperties().setProperty("Xml.SaveInitial", "true"); getProperties().setProperty("Xml.SaveCurrent", "true"); if (anonymize) { getProperties().setProperty("Xml.ConvertIds", idconv ? "true" : "false"); getProperties().setProperty("Xml.SaveOnlineSectioningInfo", "true"); getProperties().setProperty("Xml.SaveStudentInfo", "false"); getProperties().setProperty("Xml.ShowNames", "false"); } StudentSectioningXMLSaver saver = new StudentSectioningXMLSaver(this); ByteArrayOutputStream ret = new ByteArrayOutputStream(); try { saver.save(temp); FileInputStream fis = new FileInputStream(temp); byte[] buf = new byte[16*1024]; int read = 0; while ((read=fis.read(buf, 0, buf.length))>0) ret.write(buf,0,read); ret.flush();ret.close(); fis.close(); } catch (Exception e) { sLog.error(e.getMessage(),e); } temp.delete(); if (anonymize) { getProperties().setProperty("Xml.ConvertIds", "false"); getProperties().setProperty("Xml.SaveOnlineSectioningInfo", "true"); getProperties().setProperty("Xml.SaveStudentInfo", "true"); getProperties().setProperty("Xml.ShowNames", "true"); } return ret.toByteArray(); } finally { lock.unlock(); } } @Override public boolean isMaster() { return true; } @Override public void releaseMasterLockIfHeld() { } @Override public Collection<XCourseRequest> getRequests(Long offeringId) { List<XCourseRequest> ret = new ArrayList<XCourseRequest>(); for (Offering offering: ((StudentSectioningModel)currentSolution().getModel()).getOfferings()) if (offering.getId() == offeringId) { for (Course course: offering.getCourses()) for (CourseRequest req: course.getRequests()) { if (!req.getStudent().isDummy()) ret.add(new XCourseRequest(req, currentSolution().getAssignment().getValue(req))); } break; } return ret; } @Override public XEnrollments getEnrollments(Long offeringId) { return new XEnrollments(offeringId, getRequests(offeringId)); } @Override public XExpectations getExpectations(Long offeringId) { for (Offering offering: ((StudentSectioningModel)currentSolution().getModel()).getOfferings()) if (offering.getId() == offeringId) return new XExpectations(offering); return null; } @Override public void update(XExpectations expectations) { } @Override public void remove(XStudent student) { } @Override public void update(XStudent student, boolean updateRequests) { } @Override public void remove(XOffering offering) { } @Override public void update(XOffering offering) { } @Override public XCourseRequest assign(XCourseRequest request, XEnrollment enrollment) { return request; } @Override public XCourseRequest waitlist(XCourseRequest request, boolean waitlist) { return request; } @Override public boolean checkDeadline(Long courseId, XTime sectionTime, Deadline type) { return true; } @Override public String getCourseDetails(Long courseId, CourseDetailsProvider provider) { XCourse course = getCourse(courseId); return course == null ? null : course.getDetails(getAcademicSession(), provider); } @Override public boolean isReady() { return true; } @Override public long getMemUsage() { return new MemoryCounter().estimate(this); } @Override public <E> E getProperty(String name, E defaultValue) { E ret = (E)iOnlineProperties.get(name); return ret == null ? defaultValue : ret; } @Override public <E> void setProperty(String name, E value) { if (value == null) iOnlineProperties.remove(name); else iOnlineProperties.put(name, value); } @Override public CSVFile getReport(DataProperties parameters) { try { String name = parameters.getProperty("report", SectionConflictTable.class.getName()); Class<StudentSectioningReport> clazz = (Class<StudentSectioningReport>) Class.forName(name); StudentSectioningReport report = clazz.getConstructor(StudentSectioningModel.class).newInstance(currentSolution().getModel()); return report.create(currentSolution().getAssignment(), parameters); } catch (SectioningException e) { throw e; } catch (Exception e) { throw new SectioningException(e.getMessage(), e); } } @Override public OverExpectedCriterion getOverExpectedCriterion() { return new NeverOverExpected(getConfig()); } }
3e15b84a3ab3b97cbe183ed38cb7033a7e48ad69
10,958
java
Java
src/mealmanagement/Forgot.java
MdShohanurRahman/Meal-management-System
03524767c94279030585fe9112ea093e9b0126df
[ "MIT" ]
1
2019-10-15T17:29:35.000Z
2019-10-15T17:29:35.000Z
src/mealmanagement/Forgot.java
MdShohanurRahman/Meal-management-System
03524767c94279030585fe9112ea093e9b0126df
[ "MIT" ]
null
null
null
src/mealmanagement/Forgot.java
MdShohanurRahman/Meal-management-System
03524767c94279030585fe9112ea093e9b0126df
[ "MIT" ]
null
null
null
47.437229
341
0.646377
9,218
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mealmanagement; import java.awt.Toolkit; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; /** * * @author Shohanur Rahman */ public class Forgot extends javax.swing.JFrame { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; public Forgot() { super("Forgot Page"); initComponents(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); } catch (ClassNotFoundException | SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } /** * 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() { jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 102, 102)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 0, 0), 2), "Forgot !!", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tekton Pro Cond", 0, 48), new java.awt.Color(255, 0, 0))); // NOI18N jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mealmanagement/ssearch.png.png"))); // NOI18N jButton1.setText("Search"); jButton1.setToolTipText(""); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("User Name "); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setText("Email Address"); jTextField3.setEditable(false); jTextField3.setBackground(new java.awt.Color(204, 204, 204)); jTextField3.setForeground(new java.awt.Color(255, 51, 0)); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("Password"); jTextField2.setEditable(false); jTextField2.setBackground(new java.awt.Color(204, 204, 204)); jTextField2.setForeground(new java.awt.Color(255, 51, 0)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel5) .addComponent(jLabel2)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(20, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1) .addGap(62, 62, 62)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(54, 54, 54) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(56, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(20, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Search(); }//GEN-LAST:event_jButton1ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed public void Search() { if (jTextField1.getText().isEmpty()) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(null, "Insert Email For Search"); } else { try { String sql = "select * from signup where email = ?"; ps = con.prepareStatement(sql); ps.setString(1, jTextField1.getText()); rs = ps.executeQuery(); if (rs.next()) { jTextField2.setText(rs.getString(1)); jTextField3.setText(rs.getString(2)); rs.close(); ps.close(); } else { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(null, "Incorrect Email Address"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Forgot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Forgot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Forgot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Forgot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Forgot().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration//GEN-END:variables }
3e15b85f8f16002f734d9debb91fbe5ee7e56f32
1,240
java
Java
strongbox-commons/src/main/java/org/carlspring/strongbox/util/ClassLoaderFactory.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
1
2018-10-15T20:49:56.000Z
2018-10-15T20:49:56.000Z
strongbox-commons/src/main/java/org/carlspring/strongbox/util/ClassLoaderFactory.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
null
null
null
strongbox-commons/src/main/java/org/carlspring/strongbox/util/ClassLoaderFactory.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
null
null
null
25.306122
94
0.609677
9,219
package org.carlspring.strongbox.util; import java.io.IOException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import java.util.Collection; import com.google.common.base.Throwables; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.springframework.util.Assert; /** * @author Przemyslaw Fusik */ public final class ClassLoaderFactory { private ClassLoaderFactory() { } @SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED") public static URLClassLoader urlClassLoaderFromPaths(ClassLoader parent, Collection<Path> paths) { Assert.notNull(paths, "paths collection cannot be null"); final URL[] urls; try { final URI[] uris = paths.stream().map(Path::toUri).toArray(size -> new URI[size]); urls = new URL[uris.length]; for (int i = 0; i < uris.length; i++) { urls[i] = uris[i].toURL(); } } catch (IOException e) { throw Throwables.propagate(e); } return new URLClassLoader(urls, parent); } }
3e15b8c197067aa52dcfcc4bf6f63c182bbbe4b8
1,695
java
Java
installer/src/main/java/org/apache/syncope/installer/enums/DBs.java
IsurangaPerera/syncope
3211023745b66a6571d529e0e353eac75ac2e839
[ "Apache-2.0" ]
2
2019-10-22T18:13:23.000Z
2019-10-27T16:41:35.000Z
installer/src/main/java/org/apache/syncope/installer/enums/DBs.java
IsurangaPerera/syncope
3211023745b66a6571d529e0e353eac75ac2e839
[ "Apache-2.0" ]
36
2015-10-05T12:21:18.000Z
2015-10-29T17:13:10.000Z
installer/src/main/java/org/apache/syncope/installer/enums/DBs.java
andrea-patricelli/syncope
223a64e26deff69a4ed8275d0f1348ca4e130a01
[ "Apache-2.0" ]
null
null
null
30.267857
71
0.656637
9,220
/* * 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.apache.syncope.installer.enums; public enum DBs { POSTGRES("postgres"), MYSQL("mysql"), MARIADB("mariadb"), SQLSERVER("sqlserver"), ORACLE("oracle"); DBs(final String name) { this.name = name; } private final String name; public String getName() { return name; } public static DBs fromDbName(final String containerName) { DBs db = null; if (POSTGRES.getName().equalsIgnoreCase(containerName)) { db = POSTGRES; } else if (MYSQL.getName().equalsIgnoreCase(containerName)) { db = MYSQL; } else if (MARIADB.getName().equalsIgnoreCase(containerName)) { db = MARIADB; } else if (ORACLE.getName().equalsIgnoreCase(containerName)) { db = ORACLE; } else { db = SQLSERVER; } return db; } }
3e15b8fecbde66ad859222c4b9b689730a724d85
487
java
Java
MavenWorkspace/bis-services-lib/bis-businessservices-lib/src/main/java/com/experian/bis/api/lib/businessservices/bean/request/LiensServiceRequest.java
taddhopkins/experian-java
024721d7cf893d5e94791438c1031d3231b4b6d9
[ "MIT" ]
3
2018-01-30T13:55:50.000Z
2020-10-04T10:15:58.000Z
MavenWorkspace/bis-services-lib/bis-businessservices-lib/src/main/java/com/experian/bis/api/lib/businessservices/bean/request/LiensServiceRequest.java
taddhopkins/experian-java
024721d7cf893d5e94791438c1031d3231b4b6d9
[ "MIT" ]
1,069
2020-10-15T14:09:35.000Z
2022-03-25T15:16:42.000Z
MavenWorkspace/bis-services-lib/bis-businessservices-lib/src/main/java/com/experian/bis/api/lib/businessservices/bean/request/LiensServiceRequest.java
taddhopkins/experian-java
024721d7cf893d5e94791438c1031d3231b4b6d9
[ "MIT" ]
35
2020-10-15T14:08:04.000Z
2022-03-25T15:13:02.000Z
21.173913
65
0.776181
9,221
package com.experian.bis.api.lib.businessservices.bean.request; public class LiensServiceRequest extends BusinessServiceRequest { private boolean lienSummary; private boolean lienDetail; public boolean isLienSummary() { return lienSummary; } public void setLienSummary(boolean lienSummary) { this.lienSummary = lienSummary; } public boolean isLienDetail() { return lienDetail; } public void setLienDetail(boolean lienDetail) { this.lienDetail = lienDetail; } }
3e15b9e780ea3a1306254b9262935566f556b8e5
844
java
Java
src/main/java/io/metadew/iesi/gcp/common/framework/FrameworkService.java
metadew/iesi-gcp
954742974a4806415905c17561cd3d573a620b0b
[ "ECL-2.0", "Apache-2.0", "MIT" ]
1
2020-10-14T20:15:31.000Z
2020-10-14T20:15:31.000Z
src/main/java/io/metadew/iesi/gcp/common/framework/FrameworkService.java
metadew/iesi-gcp
954742974a4806415905c17561cd3d573a620b0b
[ "ECL-2.0", "Apache-2.0", "MIT" ]
3
2021-12-09T22:46:59.000Z
2021-12-14T20:57:36.000Z
src/main/java/io/metadew/iesi/gcp/common/framework/FrameworkService.java
metadew/iesi-gcp
954742974a4806415905c17561cd3d573a620b0b
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
25.575758
128
0.68128
9,222
package io.metadew.iesi.gcp.common.framework; import io.metadew.iesi.gcp.common.tools.FolderTools; import java.io.File; import java.util.Map; public class FrameworkService { private static FrameworkService INSTANCE; public synchronized static FrameworkService getInstance() { if (INSTANCE == null) { INSTANCE = new FrameworkService(); } return INSTANCE; } private FrameworkService () { } public void clean(String serviceName) { FolderTools.deleteFolder(serviceName,true); } public void create(String serviceName) { for (Map.Entry<String, FrameworkFolder> entry : FrameworkConfiguration.getInstance().getFrameworkFolders().entrySet()) { FolderTools.createFolder(serviceName + File.separator + entry.getValue().getPath()); } } }
3e15bafb83f66def05e61a649c9e21686672166a
13,175
java
Java
streambuffer/src/main/java/com/sun/xml/stream/buffer/stax/StreamReaderBufferCreator.java
jbescos/metro-xmlstreambuffer
1dd797972a925d1e5278f0c2714793481f503ee3
[ "BSD-3-Clause" ]
null
null
null
streambuffer/src/main/java/com/sun/xml/stream/buffer/stax/StreamReaderBufferCreator.java
jbescos/metro-xmlstreambuffer
1dd797972a925d1e5278f0c2714793481f503ee3
[ "BSD-3-Clause" ]
null
null
null
streambuffer/src/main/java/com/sun/xml/stream/buffer/stax/StreamReaderBufferCreator.java
jbescos/metro-xmlstreambuffer
1dd797972a925d1e5278f0c2714793481f503ee3
[ "BSD-3-Clause" ]
null
null
null
35.704607
132
0.595142
9,223
/* * Copyright (c) 2005, 2019 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.xml.stream.buffer.stax; import com.sun.xml.stream.buffer.MutableXMLStreamBuffer; import org.jvnet.staxex.Base64Data; import org.jvnet.staxex.XMLStreamReaderEx; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.util.HashMap; import java.util.Map; /** * Create a buffer using an {@link XMLStreamReader}. * <p> * TODO: Implement the marking the stream on the element when an ID * attribute on the element is defined */ public class StreamReaderBufferCreator extends StreamBufferCreator { private int _eventType; private boolean _storeInScopeNamespacesOnElementFragment; private Map<String, Integer> _inScopePrefixes; /** * Create a stream reader buffer creator. * <p> * A stream buffer will be created for storing the infoset * from a stream reader. */ public StreamReaderBufferCreator() { } /** * Create a stream reader buffer creator using a mutable stream buffer. * <p> * @param buffer the mutable stream buffer. */ public StreamReaderBufferCreator(MutableXMLStreamBuffer buffer) { setBuffer(buffer); } /** * Create the buffer from a stream reader. * <p> * The stream reader must be positioned at the start of the document * or the start of an element. * <p> * If the stream is positioned at the start of the document then the * whole document is stored and after storing the stream will be positioned * at the end of the document. * <p> * If the stream is positioned at the start of an element then the * element and all its children will be stored and after storing the stream * will be positioned at the next event after the end of the element. * <p> * @return the mutable stream buffer. * @throws XMLStreamException if the stream reader is not positioned at * the start of the document or at an element. */ public MutableXMLStreamBuffer create(XMLStreamReader reader) throws XMLStreamException { if (_buffer == null) { createBuffer(); } store(reader); return getXMLStreamBuffer(); } /** * Creates the buffer from a stream reader that is an element fragment. * <p> * The stream reader will be moved to the position of the next start of * an element if the stream reader is not already positioned at the start * of an element. * <p> * The element and all its children will be stored and after storing the stream * will be positioned at the next event after the end of the element. * <p> * @param storeInScopeNamespaces true if in-scope namespaces of the element * fragment should be stored. * @return the mutable stream buffer. * @throws XMLStreamException if the stream reader cannot be positioned at * the start of an element. */ public MutableXMLStreamBuffer createElementFragment(XMLStreamReader reader, boolean storeInScopeNamespaces) throws XMLStreamException { if (_buffer == null) { createBuffer(); } if (!reader.hasNext()) { return _buffer; } _storeInScopeNamespacesOnElementFragment = storeInScopeNamespaces; _eventType = reader.getEventType(); if (_eventType != XMLStreamReader.START_ELEMENT) { do { _eventType = reader.next(); } while(_eventType != XMLStreamReader.START_ELEMENT && _eventType != XMLStreamReader.END_DOCUMENT); } if (storeInScopeNamespaces) { _inScopePrefixes = new HashMap<String,Integer>(); } storeElementAndChildren(reader); return getXMLStreamBuffer(); } private void store(XMLStreamReader reader) throws XMLStreamException { if (!reader.hasNext()) { return; } _eventType = reader.getEventType(); switch (_eventType) { case XMLStreamReader.START_DOCUMENT: storeDocumentAndChildren(reader); break; case XMLStreamReader.START_ELEMENT: storeElementAndChildren(reader); break; default: throw new XMLStreamException("XMLStreamReader not positioned at a document or element"); } increaseTreeCount(); } private void storeDocumentAndChildren(XMLStreamReader reader) throws XMLStreamException { storeStructure(T_DOCUMENT); _eventType = reader.next(); while (_eventType != XMLStreamReader.END_DOCUMENT) { switch (_eventType) { case XMLStreamReader.START_ELEMENT: storeElementAndChildren(reader); continue; case XMLStreamReader.COMMENT: storeComment(reader); break; case XMLStreamReader.PROCESSING_INSTRUCTION: storeProcessingInstruction(reader); break; } _eventType = reader.next(); } storeStructure(T_END); } private void storeElementAndChildren(XMLStreamReader reader) throws XMLStreamException { if (reader instanceof XMLStreamReaderEx) { storeElementAndChildrenEx((XMLStreamReaderEx)reader); } else { storeElementAndChildrenNoEx(reader); } } private void storeElementAndChildrenEx(XMLStreamReaderEx reader) throws XMLStreamException { int depth = 1; if (_storeInScopeNamespacesOnElementFragment) { storeElementWithInScopeNamespaces(reader); } else { storeElement(reader); } while(depth > 0) { _eventType = reader.next(); switch (_eventType) { case XMLStreamReader.START_ELEMENT: depth++; storeElement(reader); break; case XMLStreamReader.END_ELEMENT: depth--; storeStructure(T_END); break; case XMLStreamReader.NAMESPACE: storeNamespaceAttributes(reader); break; case XMLStreamReader.ATTRIBUTE: storeAttributes(reader); break; case XMLStreamReader.SPACE: case XMLStreamReader.CHARACTERS: case XMLStreamReader.CDATA: { CharSequence c = reader.getPCDATA(); if (c instanceof Base64Data) { storeStructure(T_TEXT_AS_OBJECT); //Instead of clone the Base64Data, the original Base64Data instance is used here to preserve the DataHandler storeContentObject(c); } else { storeContentCharacters(T_TEXT_AS_CHAR_ARRAY, reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()); } break; } case XMLStreamReader.COMMENT: storeComment(reader); break; case XMLStreamReader.PROCESSING_INSTRUCTION: storeProcessingInstruction(reader); break; } } /* * Move to next item after the end of the element * that has been stored */ _eventType = reader.next(); } private void storeElementAndChildrenNoEx(XMLStreamReader reader) throws XMLStreamException { int depth = 1; if (_storeInScopeNamespacesOnElementFragment) { storeElementWithInScopeNamespaces(reader); } else { storeElement(reader); } while(depth > 0) { _eventType = reader.next(); switch (_eventType) { case XMLStreamReader.START_ELEMENT: depth++; storeElement(reader); break; case XMLStreamReader.END_ELEMENT: depth--; storeStructure(T_END); break; case XMLStreamReader.NAMESPACE: storeNamespaceAttributes(reader); break; case XMLStreamReader.ATTRIBUTE: storeAttributes(reader); break; case XMLStreamReader.SPACE: case XMLStreamReader.CHARACTERS: case XMLStreamReader.CDATA: { storeContentCharacters(T_TEXT_AS_CHAR_ARRAY, reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()); break; } case XMLStreamReader.COMMENT: storeComment(reader); break; case XMLStreamReader.PROCESSING_INSTRUCTION: storeProcessingInstruction(reader); break; } } /* * Move to next item after the end of the element * that has been stored */ _eventType = reader.next(); } private void storeElementWithInScopeNamespaces(XMLStreamReader reader) { storeQualifiedName(T_ELEMENT_LN, reader.getPrefix(), reader.getNamespaceURI(), reader.getLocalName()); if (reader.getNamespaceCount() > 0) { storeNamespaceAttributes(reader); } if (reader.getAttributeCount() > 0) { storeAttributes(reader); } } private void storeElement(XMLStreamReader reader) { storeQualifiedName(T_ELEMENT_LN, reader.getPrefix(), reader.getNamespaceURI(), reader.getLocalName()); if (reader.getNamespaceCount() > 0) { storeNamespaceAttributes(reader); } if (reader.getAttributeCount() > 0) { storeAttributes(reader); } } /** * A low level method a create a structure element explicitly. This is useful when xsb is * created from a fragment's XMLStreamReader and inscope namespaces can be passed using * this method. Note that there is no way to enumerate namespaces from XMLStreamReader. * * For e.g: Say the SOAP message is as follows * <pre>{@code * <S:Envelope xmlns:n1=".."><S:Body><ns2:A> ...} * </pre> * when xsb is to be created using a reader that is at {@code <ns2:A>} tag, the inscope * namespace like 'n1' can be passed using this method. * * WARNING: Instead of using this, try other methods(if you don't know what you are * doing). * * @param ns an array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }. */ public void storeElement(String nsURI, String localName, String prefix, String[] ns) { storeQualifiedName(T_ELEMENT_LN, prefix, nsURI, localName); storeNamespaceAttributes(ns); } /** * A low level method a create a structure element explicitly. This is * required to support {@link #storeElement} method. * * WARNING: Instead of using this, try other methods(if you don't know what * you are doing). */ public void storeEndElement() { storeStructure(T_END); } private void storeNamespaceAttributes(XMLStreamReader reader) { int count = reader.getNamespaceCount(); for (int i = 0; i < count; i++) { storeNamespaceAttribute(reader.getNamespacePrefix(i), reader.getNamespaceURI(i)); } } /** * @param ns an array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }. */ private void storeNamespaceAttributes(String[] ns) { for (int i = 0; i < ns.length; i=i+2) { storeNamespaceAttribute(ns[i], ns[i+1]); } } private void storeAttributes(XMLStreamReader reader) { int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { storeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i), reader.getAttributeLocalName(i), reader.getAttributeType(i), reader.getAttributeValue(i)); } } private void storeComment(XMLStreamReader reader) { storeContentCharacters(T_COMMENT_AS_CHAR_ARRAY, reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()); } private void storeProcessingInstruction(XMLStreamReader reader) { storeProcessingInstruction(reader.getPITarget(), reader.getPIData()); } }
3e15bbc77f96cc571d84eb1cb38032bbbd7fb45e
72,199
java
Java
common/src/main/java/com/pg85/otg/customobjects/bo3/BO3Config.java
Sascha-T/OTG-v4-CM-fix
20e216fe57139b4d8454319bc75ca6943a4b0c35
[ "MIT" ]
1
2018-12-06T11:47:18.000Z
2018-12-06T11:47:18.000Z
common/src/main/java/com/pg85/otg/customobjects/bo3/BO3Config.java
Sascha-T/OTG-v4-CM-fix
20e216fe57139b4d8454319bc75ca6943a4b0c35
[ "MIT" ]
null
null
null
common/src/main/java/com/pg85/otg/customobjects/bo3/BO3Config.java
Sascha-T/OTG-v4-CM-fix
20e216fe57139b4d8454319bc75ca6943a4b0c35
[ "MIT" ]
null
null
null
51.755556
442
0.678195
9,224
package com.pg85.otg.customobjects.bo3; import com.pg85.otg.LocalMaterialData; import com.pg85.otg.OTG; import com.pg85.otg.configuration.CustomObjectConfigFile; import com.pg85.otg.configuration.CustomObjectConfigFunction; import com.pg85.otg.configuration.WorldConfig.ConfigMode; import com.pg85.otg.configuration.io.SettingsReaderOTGPlus; import com.pg85.otg.configuration.io.SettingsWriterOTGPlus; import com.pg85.otg.configuration.standard.WorldStandardValues; import com.pg85.otg.customobjects.CustomObject; import com.pg85.otg.customobjects.CustomObjectCoordinate; import com.pg85.otg.customobjects.bo3.BO3Settings.OutsideSourceBlock; import com.pg85.otg.customobjects.bo3.BO3Settings.SpawnHeightEnum; import com.pg85.otg.exception.InvalidConfigException; import com.pg85.otg.logging.LogMarker; import com.pg85.otg.util.BoundingBox; import com.pg85.otg.util.ChunkCoordinate; import com.pg85.otg.util.MaterialSet; import com.pg85.otg.util.Rotation; import com.pg85.otg.util.minecraftTypes.DefaultMaterial; import com.pg85.otg.util.minecraftTypes.DefaultStructurePart; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class BO3Config extends CustomObjectConfigFile { // OTG + public boolean isOTGPlus = false; public int branchFrequency; // Define a group that this BO3 belongs to and a range in chunks that members of this group should have to each other public String branchFrequencyGroup = ""; private int minX = Integer.MAX_VALUE; private int maxX = Integer.MIN_VALUE; private int minY = Integer.MAX_VALUE; private int maxY = Integer.MIN_VALUE; private int minZ = Integer.MAX_VALUE; private int maxZ = Integer.MIN_VALUE; private ArrayList<String> inheritedBO3s; // These are used in CustomObjectStructure when determining the minimum area in chunks that // this branching structure needs to be able to spawn public int MinimumSizeTop = -1; public int MinimumSizeBottom = -1; public int MinimumSizeLeft = -1; public int MinimumSizeRight = -1; public int timesSpawned = 0; private Map<ChunkCoordinate, BlockFunction> HeightMap = null; private boolean inheritedBO3Loaded = false; // Adjusts the height by this number before spawning. Handy when using "highestblock" for lowering BO3s that have a lot of ground under them included public int heightOffset; // OTG+ CustomStructures only public Rotation inheritBO3Rotation = Rotation.NORTH; // If this is set to true then any air blocks in the bo3 will not be spawned public boolean removeAir = true; // Defaults to false. Set to true if this BO3 should spawn at the player spawn point. When the server starts one of the structures that has IsSpawnPoint set to true is selected randomly and is spawned, the others never get spawned.) public boolean isSpawnPoint = false; // Replaces all the non-air blocks that are above this BO3 or its smoothing area with the given block material (should be WATER or AIR or NONE), also applies to smoothing areas although it intentionally leaves some of the terrain above them intact. WATER can be used in combination with SpawnUnderWater to fill any air blocks underneath waterlevel with water (and any above waterlevel with air). public String replaceAbove = ""; // Replaces all non-air blocks underneath the BO3 (but not its smoothing area) with the designated material until a solid block is found. public String replaceBelow = ""; // Defaults to true. If set to true then every block in the BO3 of the materials defined in ReplaceWithGroundBlock or ReplaceWithSurfaceBlock will be replaced by the GroundBlock or SurfaceBlock materials configured for the biome the block is spawned in. public boolean replaceWithBiomeBlocks = true; // Replaces all the blocks of the given material in the BO3 with the GroundBlock configured for the biome it spawns in public String replaceWithGroundBlock = "DIRT"; // Replaces all the blocks of the given material in the BO3 with the SurfaceBlock configured for the biome it spawns in public String replaceWithSurfaceBlock = "GRASS"; // Define a group that this BO3 belongs to and a range in chunks that members of this group should have to each other public String bo3Group = ""; // If this is set to true then this BO3 can spawn on top of or inside other BO3's public boolean canOverride = false; // Copies the blocks and branches of an existing BO3 into this one public String inheritBO3 = ""; // Should the smoothing area go to the top or the bottom blocks in the bo3? public boolean smoothStartTop = false; public boolean smoothStartWood = false; // The size of the smoothing area public int smoothRadius = 0; // The materials used for the smoothing area public String smoothingSurfaceBlock = ""; public String smoothingGroundBlock = ""; // If true then root BO3 smoothing and height settings are used for all children public boolean overrideChildSettings = true; public boolean overrideParentHeight = false; // Used to make sure that dungeons can only spawn underneath other structures public boolean mustBeBelowOther = false; public String replacesBO3 = ""; public String mustBeInside = ""; public String cannotBeInside = ""; public int smoothHeightOffset = 0; public boolean CanSpawnOnWater = true; public boolean SpawnOnWaterOnly = false; public boolean SpawnUnderWater = false; public boolean SpawnAtWaterLevel = false; public Map<ChunkCoordinate, Stack<CustomObjectCoordinate>> CachedObjectsToSpawn = null; public Map<ChunkCoordinate, ArrayList<Object[]>> CachedSmoothingAreasToSpawn = null; private String worldName; BlockFunction[] blocksOTGPlus = null; public BO3Check[] bo3ChecksOTGPlus = new BO3Check[1]; private BranchFunction[] branchesOTGPlus = new BranchFunction[1]; private ModDataFunction[] modDataOTGPlus = new ModDataFunction[1]; private SpawnerFunction[] spawnerDataOTGPlus = new SpawnerFunction[1]; private ParticleFunction[] particleDataOTGPlus = new ParticleFunction[1]; private EntityFunction[] entityDataOTGPlus = new EntityFunction[1]; String directoryName = null; public int getXOffset() { return minX < -8 ? -minX : maxX > 7 ? -minX : 8; } public int getZOffset() { return minZ < -7 ? -minZ : maxZ > 8 ? -minZ : 7; } public int getminX() { return minX + this.getXOffset(); // + xOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getmaxX() { return maxX + this.getXOffset(); // + xOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getminY() { return minY; } public int getmaxY() { return maxY; } public int getminZ() { return minZ + this.getZOffset(); // + zOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getmaxZ() { return maxZ + this.getZOffset(); // + zOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public ArrayList<String> getInheritedBO3s() { return inheritedBO3s; } public Map<ChunkCoordinate, BlockFunction> getHeightMap(BO3 start) { if(HeightMap == null) { HeightMap = new HashMap<ChunkCoordinate, BlockFunction>(); BlockFunction[] blocks = getBlocks(); // make heightmap containing the highest or lowest blocks in this chunk for(int x = 0; x <= 15; x ++) { for(int z = 0; z <= 15; z ++) { // Check if this is the highest block in the BO3 at these x-z coordinates for(BlockFunction block2 : blocks) { if(block2.x < 0 || block2.x > 15 || block2.z < 0 || block2.z > 15) { throw new RuntimeException(); } if(x == block2.x && z == block2.z) { boolean isSmoothAreaAnchor = false; if(block2 instanceof RandomBlockFunction) { for(LocalMaterialData material : ((RandomBlockFunction)block2).blocks) { // TODO: Material should never be null, fix the code in RandomBlockFunction.load() that causes this. if(material == null) { continue; } if(material.isSmoothAreaAnchor(start.getSettings().overrideChildSettings && overrideChildSettings ? start.getSettings().smoothStartWood : smoothStartWood, start.getSettings().SpawnUnderWater)) { isSmoothAreaAnchor = true; break; } } } if( isSmoothAreaAnchor || ( !(block2 instanceof RandomBlockFunction) && block2.material.isSmoothAreaAnchor(start.getSettings().overrideChildSettings && overrideChildSettings ? start.getSettings().smoothStartWood : smoothStartWood, start.getSettings().SpawnUnderWater) ) ) { if( (!(start.getSettings().overrideChildSettings && overrideChildSettings ? start.getSettings().smoothStartTop : smoothStartTop) && block2.y == getminY()) || ((start.getSettings().overrideChildSettings && overrideChildSettings ? start.getSettings().smoothStartTop : smoothStartTop) && (HeightMap.get(ChunkCoordinate.fromChunkCoords(block2.x, block2.z)) == null || block2.y > HeightMap.get(ChunkCoordinate.fromChunkCoords(block2.x, block2.z)).y)) ) { HeightMap.put(ChunkCoordinate.fromChunkCoords(x, z), block2); } } } } } } } return HeightMap; } public BlockFunction[] getBlocks() { return blocksOTGPlus; } public BranchFunction[] getbranches() { return branchesOTGPlus; } public ModDataFunction[] getModData() { return modDataOTGPlus; } public SpawnerFunction[] getSpawnerData() { return spawnerDataOTGPlus; } public ParticleFunction[] getParticleData() { return particleDataOTGPlus; } public BO3Check[] getBO3Checks() { return bo3ChecksOTGPlus; } public EntityFunction[] getEntityData() { return entityDataOTGPlus; } private void loadInheritedBO3() { if(this.inheritBO3 != null && this.inheritBO3.trim().length() > 0 && !inheritedBO3Loaded) { File currentFile = this.file.getParentFile(); worldName = currentFile.getName(); while(currentFile.getParentFile() != null && !currentFile.getName().toLowerCase().equals("worlds")) { worldName = currentFile.getName(); currentFile = currentFile.getParentFile(); if(worldName.toLowerCase().equals("globalobjects")) { worldName = null; break; } } CustomObject parentBO3 = OTG.getCustomObjectManager().getGlobalObjects().getObjectByName(this.inheritBO3, worldName); if(parentBO3 != null) { inheritedBO3Loaded = true; inheritedBO3s.addAll(((BO3)parentBO3).getSettings().getInheritedBO3s()); removeAir = ((BO3)parentBO3).getSettings().removeAir; replaceAbove = replaceAbove == null || replaceAbove.length() == 0 ? ((BO3)parentBO3).getSettings().replaceAbove : replaceAbove; replaceBelow = replaceBelow == null || replaceBelow.length() == 0 ? ((BO3)parentBO3).getSettings().replaceBelow : replaceBelow; CustomObjectCoordinate rotatedParentMaxCoords = CustomObjectCoordinate.getRotatedBO3Coords(((BO3)parentBO3).getSettings().maxX, ((BO3)parentBO3).getSettings().maxY, ((BO3)parentBO3).getSettings().maxZ, inheritBO3Rotation); CustomObjectCoordinate rotatedParentMinCoords = CustomObjectCoordinate.getRotatedBO3Coords(((BO3)parentBO3).getSettings().minX, ((BO3)parentBO3).getSettings().minY, ((BO3)parentBO3).getSettings().minZ, inheritBO3Rotation); int parentMaxX = rotatedParentMaxCoords.getX() > rotatedParentMinCoords.getX() ? rotatedParentMaxCoords.getX() : rotatedParentMinCoords.getX(); int parentMinX = rotatedParentMaxCoords.getX() < rotatedParentMinCoords.getX() ? rotatedParentMaxCoords.getX() : rotatedParentMinCoords.getX(); int parentMaxY = rotatedParentMaxCoords.getY() > rotatedParentMinCoords.getY() ? rotatedParentMaxCoords.getY() : rotatedParentMinCoords.getY(); int parentMinY = rotatedParentMaxCoords.getY() < rotatedParentMinCoords.getY() ? rotatedParentMaxCoords.getY() : rotatedParentMinCoords.getY(); int parentMaxZ = rotatedParentMaxCoords.getZ() > rotatedParentMinCoords.getZ() ? rotatedParentMaxCoords.getZ() : rotatedParentMinCoords.getZ(); int parentMinZ = rotatedParentMaxCoords.getZ() < rotatedParentMinCoords.getZ() ? rotatedParentMaxCoords.getZ() : rotatedParentMinCoords.getZ(); if(parentMaxX > this.maxX) { this.maxX = parentMaxX; } if(parentMinX < this.minX) { this.minX = parentMinX; } if(parentMaxY > this.maxY) { this.maxY = parentMaxY; } if(parentMinY < this.minY) { this.minY = parentMinY; } if(parentMaxZ > this.maxZ) { this.maxZ = parentMaxZ; } if(parentMinZ < this.minZ) { this.minZ = parentMinZ; } ArrayList<BlockFunction> newBlocks = new ArrayList<BlockFunction>(); if(this.blocksOTGPlus != null) { for(BlockFunction block : this.blocksOTGPlus) { newBlocks.add(block); } } for(BlockFunction block : ((BO3)parentBO3).getSettings().blocksOTGPlus.clone()) { newBlocks.add(block.rotate(inheritBO3Rotation)); } this.blocksOTGPlus = newBlocks.toArray(new BlockFunction[newBlocks.size()]); ArrayList<BranchFunction> newBranches = new ArrayList<BranchFunction>(); if(this.branchesOTGPlus != null) { for(BranchFunction branch : this.branchesOTGPlus) { newBranches.add(branch); } } for(BranchFunction branch : ((BO3)parentBO3).getSettings().branchesOTGPlus.clone()) { newBranches.add(branch.rotate(inheritBO3Rotation)); } this.branchesOTGPlus = newBranches.toArray(new BranchFunction[newBranches.size()]); ArrayList<ModDataFunction> newModData = new ArrayList<ModDataFunction>(); if(this.modDataOTGPlus != null) { for(ModDataFunction modData : this.modDataOTGPlus) { newModData.add(modData); } } for(ModDataFunction modData : ((BO3)parentBO3).getSettings().modDataOTGPlus.clone()) { newModData.add(modData.rotate(inheritBO3Rotation)); } this.modDataOTGPlus = newModData.toArray(new ModDataFunction[newModData.size()]); ArrayList<SpawnerFunction> newSpawnerData = new ArrayList<SpawnerFunction>(); if(this.spawnerDataOTGPlus != null) { for(SpawnerFunction spawnerData : this.spawnerDataOTGPlus) { newSpawnerData.add(spawnerData); } } for(SpawnerFunction spawnerData : ((BO3)parentBO3).getSettings().spawnerDataOTGPlus.clone()) { newSpawnerData.add(spawnerData.rotate(inheritBO3Rotation)); } this.spawnerDataOTGPlus = newSpawnerData.toArray(new SpawnerFunction[newSpawnerData.size()]); ArrayList<ParticleFunction> newParticleData = new ArrayList<ParticleFunction>(); if(this.particleDataOTGPlus != null) { for(ParticleFunction particleData : this.particleDataOTGPlus) { newParticleData.add(particleData); } } for(ParticleFunction particleData : ((BO3)parentBO3).getSettings().particleDataOTGPlus.clone()) { newParticleData.add(particleData.rotate(inheritBO3Rotation)); } this.particleDataOTGPlus = newParticleData.toArray(new ParticleFunction[newParticleData.size()]); ArrayList<EntityFunction> newEntityData = new ArrayList<EntityFunction>(); if(this.entityDataOTGPlus != null) { for(EntityFunction entityData : this.entityDataOTGPlus) { newEntityData.add(entityData); } } for(EntityFunction entityData : ((BO3)parentBO3).getSettings().entityDataOTGPlus.clone()) { newEntityData.add(entityData.rotate(inheritBO3Rotation)); } this.entityDataOTGPlus = newEntityData.toArray(new EntityFunction[newEntityData.size()]); ArrayList<BO3Check> newBO3Check = new ArrayList<BO3Check>(); if(this.bo3ChecksOTGPlus != null) { for(BO3Check bo3Check : this.bo3ChecksOTGPlus) { newBO3Check.add(bo3Check); } } for(BO3Check bo3Check : ((BO3)parentBO3).getSettings().bo3ChecksOTGPlus.clone()) { newBO3Check.add(bo3Check.rotate(inheritBO3Rotation)); } this.bo3ChecksOTGPlus = newBO3Check.toArray(new BO3Check[newBO3Check.size()]); inheritedBO3s.addAll(((BO3)parentBO3).getSettings().getInheritedBO3s()); } if(!inheritedBO3Loaded) { OTG.log(LogMarker.INFO, "could not load BO3 parent for InheritBO3: " + this.inheritBO3 + " in BO3 " + this.getName()); } } } private void readResources() throws InvalidConfigException { List<BlockFunction> tempBlocksList = new ArrayList<BlockFunction>(); List<BO3Check> tempChecksList = new ArrayList<BO3Check>(); List<BranchFunction> tempBranchesList = new ArrayList<BranchFunction>(); List<EntityFunction> tempEntitiesList = new ArrayList<EntityFunction>(); List<ModDataFunction> tempModDataList = new ArrayList<ModDataFunction>(); List<ParticleFunction> tempParticlesList = new ArrayList<ParticleFunction>(); List<SpawnerFunction> tempSpawnerList = new ArrayList<SpawnerFunction>(); if(isOTGPlus) { for (CustomObjectConfigFunction<BO3Config> res : reader.getConfigFunctions(this, true)) { if (res.isValid()) { if (res instanceof BlockFunction || res instanceof RandomBlockFunction) // TODO: check for RandomBlockFunction seems redundant here? { if(res instanceof RandomBlockFunction) { RandomBlockFunction newRes = new RandomBlockFunction(); newRes.blocks = ((RandomBlockFunction)res).blocks; newRes.blockChances = ((RandomBlockFunction)res).blockChances; newRes.blockCount = ((RandomBlockFunction)res).blockCount; newRes.x = ((RandomBlockFunction)res).x; newRes.y = ((RandomBlockFunction)res).y; newRes.z = ((RandomBlockFunction)res).z; newRes.metaDataTag = ((RandomBlockFunction)res).metaDataTag; newRes.metaDataTags = ((RandomBlockFunction)res).metaDataTags; newRes.metaDataName = ((RandomBlockFunction)res).metaDataName; newRes.metaDataNames = ((RandomBlockFunction)res).metaDataNames; newRes.material = ((RandomBlockFunction)res).material; tempBlocksList.add(newRes); } else { if(!this.removeAir || !((BlockFunction)res).material.toDefaultMaterial().equals(DefaultMaterial.AIR)) { BlockFunction newRes = new BlockFunction(); newRes.x = ((BlockFunction)res).x; newRes.y = ((BlockFunction)res).y; newRes.z = ((BlockFunction)res).z; newRes.metaDataTag = ((BlockFunction)res).metaDataTag; newRes.metaDataName = ((BlockFunction)res).metaDataName; newRes.material = ((BlockFunction)res).material; tempBlocksList.add(newRes); } } // Get the real size of this BO3 if(((BlockFunction)res).x < minX) { minX = ((BlockFunction)res).x; } if(((BlockFunction)res).x > maxX) { maxX = ((BlockFunction)res).x; } if(((BlockFunction)res).y < minY) { minY = ((BlockFunction)res).y; } if(((BlockFunction)res).y > maxY) { maxY = ((BlockFunction)res).y; } if(((BlockFunction)res).z < minZ) { minZ = ((BlockFunction)res).z; } if(((BlockFunction)res).z > maxZ) { maxZ = ((BlockFunction)res).z; } } else if (res instanceof BO3Check) { tempChecksList.add((BO3Check) res); } else if (res instanceof WeightedBranchFunction) { tempBranchesList.add((WeightedBranchFunction) res); } else if (res instanceof BranchFunction) { tempBranchesList.add((BranchFunction) res); } else if (res instanceof ModDataFunction) { tempModDataList.add((ModDataFunction) res); } else if (res instanceof SpawnerFunction) { tempSpawnerList.add((SpawnerFunction) res); } else if (res instanceof ParticleFunction) { tempParticlesList.add((ParticleFunction) res); } else if (res instanceof EntityFunction) { tempEntitiesList.add((EntityFunction) res); } } } if(minX == Integer.MAX_VALUE) { minX = -8; } if(maxX == Integer.MIN_VALUE) { maxX = -8; } if(minY == Integer.MAX_VALUE) { minY = 0; } if(maxY == Integer.MIN_VALUE) { maxY = 0; } if(minZ == Integer.MAX_VALUE) { minZ = -7; } if(maxZ == Integer.MIN_VALUE) { maxZ = -7; } // TODO: OTG+ Doesn't do CustomObject BO3's, only check for 16x16, not 32x32? boolean illegalBlock = false; for(BlockFunction block : tempBlocksList) { block.x += this.getXOffset(); block.z += this.getZOffset(); if(block.x > 15 || block.z > 15) { illegalBlock = true; } if(block.x < 0 || block.z < 0) { illegalBlock = true; } } blocksOTGPlus = tempBlocksList.toArray(new BlockFunction[tempBlocksList.size()]); boolean illegalBlockCheck = false; for(BO3Check bo3Check : tempChecksList) { // This is done when reading blocks so should also be done for blockchecks and moddata! bo3Check.x += this.getXOffset(); bo3Check.z += this.getZOffset(); if(bo3Check.x > 15 || bo3Check.z > 15) { illegalBlockCheck = true; } if(bo3Check.x < 0 || bo3Check.z < 0) { illegalBlockCheck = true; } } bo3ChecksOTGPlus = tempChecksList.toArray(new BO3Check[tempChecksList.size()]); boolean illegalModData = false; for(ModDataFunction modData : tempModDataList) { // This is done when reading blocks so should also be done for blockchecks and moddata! modData.x += this.getXOffset(); modData.z += this.getZOffset(); if(modData.x > 15 || modData.z > 15) { illegalModData = true; } if(modData.x < 0 || modData.z < 0) { illegalModData = true; } } modDataOTGPlus = tempModDataList.toArray(new ModDataFunction[tempModDataList.size()]); boolean illegalSpawnerData = false; for(SpawnerFunction spawnerData : tempSpawnerList) { // This is done when reading blocks so should also be done for blockchecks and moddata! spawnerData.x += this.getXOffset(); spawnerData.z += this.getZOffset(); if(spawnerData.x > 15 || spawnerData.z > 15) { illegalSpawnerData = true; } if(spawnerData.x < 0 || spawnerData.z < 0) { illegalSpawnerData = true; } } spawnerDataOTGPlus = tempSpawnerList.toArray(new SpawnerFunction[tempSpawnerList.size()]); boolean illegalParticleData = false; for(ParticleFunction particleData : tempParticlesList) { // This is done when reading blocks so should also be done for blockchecks and moddata! particleData.x += this.getXOffset(); particleData.z += this.getZOffset(); if(particleData.x > 15 || particleData.z > 15) { illegalParticleData = true; } if(particleData.x < 0 || particleData.z < 0) { illegalParticleData = true; } } particleDataOTGPlus = tempParticlesList.toArray(new ParticleFunction[tempParticlesList.size()]); boolean illegalEntityData = false; for(EntityFunction entityData : tempEntitiesList) { // This is done when reading blocks so should also be done for blockchecks and moddata! entityData.x += this.getXOffset(); entityData.z += this.getZOffset(); if(entityData.x > 15 || entityData.z > 15) { illegalEntityData = true; } if(entityData.x < 0 || entityData.z < 0) { illegalEntityData = true; } } entityDataOTGPlus = tempEntitiesList.toArray(new EntityFunction[tempEntitiesList.size()]); if(OTG.getPluginConfig().SpawnLog) { if(illegalBlock) { OTG.log(LogMarker.WARN, "Warning: BO3 contains Blocks or RandomBlocks that are placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalBlockCheck) { OTG.log(LogMarker.WARN, "Warning: BO3 contains BlockChecks that are placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalModData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains ModData that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalSpawnerData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains a Spawner() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalParticleData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains a Particle() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalEntityData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains an Entity() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } } // Store the blocks branchesOTGPlus = tempBranchesList.toArray(new BranchFunction[tempBranchesList.size()]); if(branchesOTGPlus.length > 0) // If this BO3 has branches then it must be max 16x16 { if(Math.abs(minX - maxX) > 15 || Math.abs(minZ - maxZ) > 15) { OTG.log(LogMarker.INFO, "BO3 " + this.name + " was too large, branching BO3's can be max 16x16 blocks."); throw new InvalidConfigException("BO3 " + this.name + " was too large, branching BO3's can be max 16x16 blocks."); } } else { if(Math.abs(minX - maxX) > 15 || Math.abs(minZ - maxZ) > 15) // If this BO3 is larger than 16x16 then it can only be used as a customObject { OTG.log(LogMarker.INFO, "BO3 " + this.name + " was too large, IsOTGPlus BO3's used as CustomStructure() can be max 16x16 blocks."); throw new InvalidConfigException("BO3 " + this.name + " was too large, IsOTGPlus BO3's used as CustomStructure() can be max 16x16 blocks."); } } }// else { // These lists are primarily used by non-OTG+ BO3's. For OTG+ BO3's these lists are used only when writing to the bo3, after that they are discarded. tempBlocksList = new ArrayList<BlockFunction>(); tempChecksList = new ArrayList<BO3Check>(); tempBranchesList = new ArrayList<BranchFunction>(); tempEntitiesList = new ArrayList<EntityFunction>(); tempModDataList = new ArrayList<ModDataFunction>(); tempParticlesList = new ArrayList<ParticleFunction>(); tempSpawnerList = new ArrayList<SpawnerFunction>(); BoundingBox box = BoundingBox.newEmptyBox(); for (CustomObjectConfigFunction<BO3Config> res : reader.getConfigFunctions(this, true)) { if (res instanceof BlockFunction) { BlockFunction block = (BlockFunction) res; box.expandToFit(block.x, block.y, block.z); tempBlocksList.add(block); } else if (res instanceof BO3Check) { tempChecksList.add((BO3Check) res); } else if (res instanceof WeightedBranchFunction) { tempBranchesList.add((WeightedBranchFunction) res); } else if (res instanceof BranchFunction) { tempBranchesList.add((BranchFunction) res); } else if (res instanceof EntityFunction) { tempEntitiesList.add((EntityFunction) res); } else if (res instanceof ParticleFunction) { tempParticlesList.add((ParticleFunction) res); } else if (res instanceof ModDataFunction) { tempModDataList.add((ModDataFunction) res); } else if (res instanceof SpawnerFunction) { tempSpawnerList.add((SpawnerFunction) res); } } // Store the blocks blocks[0] = tempBlocksList.toArray(new BlockFunction[tempBlocksList.size()]); bo3Checks[0] = tempChecksList.toArray(new BO3Check[tempChecksList.size()]); branches[0] = tempBranchesList.toArray(new BranchFunction[tempBranchesList.size()]); boundingBoxes[0] = box; entityFunctions[0] = tempEntitiesList.toArray(new EntityFunction[tempEntitiesList.size()]); particleFunctions[0] = tempParticlesList.toArray(new ParticleFunction[tempParticlesList.size()]); modDataFunctions[0] = tempModDataList.toArray(new ModDataFunction[tempModDataList.size()]); spawnerFunctions[0] = tempSpawnerList.toArray(new SpawnerFunction[tempSpawnerList.size()]); //} } /** * Gets the file this config will be written to. May be null if the config * will never be written. * @return The file. */ public File getFile() { return file; } // public String author; public String description; public ConfigMode settingsMode; public boolean tree; public int frequency; public double rarity; public boolean rotateRandomly; public SpawnHeightEnum spawnHeight; // Extra spawn height settings public int spawnHeightOffset; public int spawnHeightVariance; // Extrusion public BO3Settings.ExtrudeMode extrudeMode; public MaterialSet extrudeThroughBlocks; public int minHeight; public int maxHeight; public List<String> excludedBiomes; public MaterialSet sourceBlocks; public int maxPercentageOutsideSourceBlock; public OutsideSourceBlock outsideSourceBlock; public BlockFunction[][] blocks = new BlockFunction[4][]; // four // rotations public BO3Check[][] bo3Checks = new BO3Check[4][]; public int maxBranchDepth; public BranchFunction[][] branches = new BranchFunction[4][]; public BoundingBox[] boundingBoxes = new BoundingBox[4]; public ParticleFunction[][] particleFunctions = new ParticleFunction[4][]; public SpawnerFunction[][] spawnerFunctions = new SpawnerFunction[4][]; public ModDataFunction[][] modDataFunctions = new ModDataFunction[4][]; public EntityFunction[][] entityFunctions = new EntityFunction[4][]; /** * Creates a BO3Config from a file. * * @param reader The settings of the BO3. * @param directory The directory the BO3 is stored in. * @param otherObjects All other loaded objects by their name. */ public BO3Config(SettingsReaderOTGPlus reader, Map<String, CustomObject> otherObjectsInDirectory) throws InvalidConfigException { super(reader); readConfigSettings(); if(!isOTGPlus) { rotateBlocksAndChecks(); } } @Override protected void writeConfigSettings(SettingsWriterOTGPlus writer) throws IOException { // The object writer.bigTitle("BO3 object"); writer.comment("This is the config file of a custom object."); writer.comment("If you add this object correctly to your BiomeConfigs, it will spawn in the world."); writer.comment(""); writer.comment("This is the creator of this BO3 object"); writer.setting(BO3Settings.AUTHOR, author); writer.comment("A short description of this BO3 object"); writer.setting(BO3Settings.DESCRIPTION, description); writer.comment("The BO3 version, don't change this! It can be used by external applications to do a version check."); writer.setting(BO3Settings.VERSION, "3"); writer.comment("The settings mode, WriteAll, WriteWithoutComments or WriteDisable. See WorldConfig."); writer.setting(WorldStandardValues.SETTINGS_MODE_BO3, settingsMode); // Main settings writer.bigTitle("Main settings"); writer.comment("This needs to be set to true to spawn the object in the Tree and Sapling resources."); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.TREE, tree); writer.comment("When IsOTGPlus is set to false: The frequency of the BO3 from 1 to 200. Tries this many times to spawn this BO3 when using the CustomObject(...) resource."); writer.comment("Ignored by Tree(..), Sapling(..) and CustomStructure(..)"); writer.comment("When IsOTGPlus is set to true: This BO3 can only spawn at least Frequency chunks distance away from any other BO3 with the exact same name."); writer.comment("You can use this to make this BO3 spawn in groups or make sure that this BO3 only spawns once every X chunks."); writer.setting(BO3Settings.FREQUENCY, frequency); writer.comment("The rarity of the BO3 from 0 to 100. Each spawn attempt has rarity% chance to succeed when using the CustomObject(...) resource."); writer.comment("Ignored by Tree(..), Sapling(..) and CustomStructure(..)"); writer.comment("Ignored when IsOTGPlus:true, rarity is configured via the CustomStructure tag in the biome config."); writer.setting(BO3Settings.RARITY, rarity); writer.comment("If you set this to true, the BO3 will be placed with a random rotation."); writer.comment("Ignored when IsOTGPlus:true, this is broken for OTG+ atm, will fix this a.s.a.p."); writer.setting(BO3Settings.ROTATE_RANDOMLY, rotateRandomly); writer.comment("The spawn height of the BO3: randomY, highestBlock or highestSolidBlock."); writer.setting(BO3Settings.SPAWN_HEIGHT, spawnHeight); writer.comment("The offset from the spawn height to spawn this BO3"); writer.comment("Ex. SpawnHeight = highestSolidBlock, SpawnHeightOffset = 3; This object will spawn 3 blocks above the highest solid block"); writer.comment("Ignored when IsOTGPlus:true, use HeightOffset instead."); writer.setting(BO3Settings.SPAWN_HEIGHT_OFFSET, spawnHeightOffset); writer.comment("A random amount to offset the spawn location from the spawn offset height"); writer.comment("Ex. SpawnHeightOffset = 3, SpawnHeightVariance = 3; This object will spawn 3 to 6 blocks above the original spot it would have spawned"); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.SPAWN_HEIGHT_VARIANCE, spawnHeightVariance); writer.smallTitle("Height Limits for the BO3."); writer.comment("When in randomY mode used as the minimum Y or in atMinY mode as the actual Y to spawn this BO3 at."); writer.setting(BO3Settings.MIN_HEIGHT, minHeight); writer.comment("When in randomY mode used as the maximum Y to spawn this BO3 at."); writer.setting(BO3Settings.MAX_HEIGHT, maxHeight); writer.smallTitle("Extrusion settings"); writer.comment("The style of extrusion you wish to use - BottomDown, TopUp, None (Default)"); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.EXTRUDE_MODE, extrudeMode); writer.comment("The blocks to extrude your BO3 through"); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.EXTRUDE_THROUGH_BLOCKS, extrudeThroughBlocks); writer.comment("Objects can have other objects attacthed to it: branches. Branches can also"); writer.comment("have branches attached to it, which can also have branches, etc. This is the"); writer.comment("maximum branch depth for this objects."); writer.comment("Ignored when IsOTGPlus:true, branch depth is configured in the Branch() tag."); writer.setting(BO3Settings.MAX_BRANCH_DEPTH, maxBranchDepth); writer.comment("When spawned with the UseWorld keyword, this BO3 should NOT spawn in the following biomes."); writer.comment("If you write the BO3 name directly in the BiomeConfigs, this will be ignored."); writer.comment("Ignored when IsOTGPlus:true, biomes this BO3 should/shouldn't spawn in are configured via the CustomStructure() tag in the biome config(s)."); writer.setting(BO3Settings.EXCLUDED_BIOMES, excludedBiomes); // Sourceblock writer.bigTitle("Source block settings"); writer.comment("The block(s) the BO3 should spawn in."); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.SOURCE_BLOCKS, sourceBlocks); writer.comment("The maximum percentage of the BO3 that can be outside the SourceBlock."); writer.comment("The BO3 won't be placed on a location with more blocks outside the SourceBlock than this percentage."); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.MAX_PERCENTAGE_OUTSIDE_SOURCE_BLOCK, maxPercentageOutsideSourceBlock); writer.comment("What to do when a block is about to be placed outside the SourceBlock? (dontPlace, placeAnyway)"); writer.comment("Ignored when IsOTGPlus:true."); writer.setting(BO3Settings.OUTSIDE_SOURCE_BLOCK, outsideSourceBlock); writer.comment("OTG+ settings #"); writer.comment("Set this to true to enable the advanced customstructure features of OTG+."); writer.setting(BO3Settings.IS_OTG_PLUS, isOTGPlus); writer.comment("Copies the blocks and branches of an existing BO3 into this BO3. You can still add blocks and branches in this BO3, they will be added on top of the inherited blocks and branches."); writer.setting(BO3Settings.INHERITBO3, inheritBO3); writer.comment("Rotates the inheritedBO3's resources (blocks, spawners, checks etc) and branches, defaults to NORTH (no rotation)."); writer.setting(BO3Settings.INHERITBO3ROTATION, inheritBO3Rotation); writer.comment("Defaults to true, if true and this is the starting BO3 for this branching structure then this BO3's smoothing and height settings are used for all children (branches)."); writer.setting(BO3Settings.OVERRIDECHILDSETTINGS, overrideChildSettings); writer.comment("Defaults to false, if true then this branch uses it's own height settings (SpawnHeight, minHeight, maxHeight, spawnAtWaterLevel) instead of those defined in the starting BO3 for this branching structure."); writer.setting(BO3Settings.OVERRIDEPARENTHEIGHT, overrideParentHeight); writer.comment("If this is set to true then this BO3 can spawn on top of or inside an existing BO3. If this is set to false then this BO3 will use a bounding box to detect collisions with other BO3's, if a collision is detected then this BO3 won't spawn and the current branch is rolled back."); writer.setting(BO3Settings.CANOVERRIDE, canOverride); writer.comment("This branch can only spawn at least branchFrequency chunks (x,z) distance away from any other branch with the exact same name."); writer.setting(BO3Settings.BRANCH_FREQUENCY, branchFrequency); writer.comment("Define groups that this branch belongs to along with a minimum (x,z) range in chunks that this branch must have between it and any other members of this group if it is to be allowed to spawn. Syntax is \"GroupName:Frequency, GoupName2:Frequency2\" etc so for example a branch that belongs to 3 groups: \"BranchFrequencyGroup: Ships:10, Vehicles:5, FloatingThings:3\"."); writer.setting(BO3Settings.BRANCH_FREQUENCY_GROUP, branchFrequencyGroup); writer.comment("If this is set to true then this BO3 can only spawn underneath an existing BO3. Used to make sure that dungeons only appear underneath buildings."); writer.setting(BO3Settings.MUSTBEBELOWOTHER, mustBeBelowOther); writer.comment("Used with CanOverride: true. A comma-seperated list of BO3s, this BO3's bounding box must collide with one of the BO3's in the list or this BO3 fails to spawn and the current branch is rolled back."); writer.setting(BO3Settings.MUSTBEINSIDE, mustBeInside); writer.comment("Used with CanOverride: true. A comma-seperated list of BO3s, this BO3's bounding box cannot collide with any of the BO3's in the list or this BO3 fails to spawn and the current branch is rolled back."); writer.setting(BO3Settings.CANNOTBEINSIDE, cannotBeInside); writer.comment("Used with CanOverride: true. A comma-seperated list of BO3s, if this BO3's bounding box collides with any of the BO3's in the list then those BO3's won't spawn any blocks. This does not remove or roll back any BO3's."); writer.setting(BO3Settings.REPLACESBO3, replacesBO3); // Handy for interiors. You can create placeholder/detector BO3's using CanOverride:false, these Bo3's contain only dummy blocks to create a bounding box for measuring free space and checking for the presence of other BO3's, then if they can spawn place CanOverride:true branches on top. writer.comment("Defaults to true. Set to false if the BO3 is not allowed to spawn on a water block"); writer.setting(BO3Settings.CANSPAWNONWATER, CanSpawnOnWater); writer.comment("Defaults to false. Set to true if the BO3 is allowed to spawn only on a water block"); writer.setting(BO3Settings.SPAWNONWATERONLY, SpawnOnWaterOnly); writer.comment("Defaults to false. Set to true if the BO3 and its smoothing area should ignore water when looking for the highest block to spawn on. Defaults to false (things spawn on top of water)"); writer.setting(BO3Settings.SPAWNUNDERWATER, SpawnUnderWater); writer.comment("Defaults to false. Set to true if the BO3 should spawn at water level"); writer.setting(BO3Settings.SPAWNATWATERLEVEL, SpawnAtWaterLevel); writer.comment("Spawns the BO3 at a Y offset of this value. Handy when using highestBlock for lowering BO3s into the surrounding terrain when there are layers of ground included in the BO3, also handy when using SpawnAtWaterLevel to lower objects like ships into the water."); writer.setting(BO3Settings.HEIGHT_OFFSET, heightOffset); writer.comment("If set to true removes all AIR blocks from the BO3 so that it can be flooded or buried."); writer.setting(BO3Settings.REMOVEAIR, removeAir); writer.comment("Replaces all the non-air blocks that are above this BO3 or its smoothing area with the given block material (should be WATER or AIR or NONE), also applies to smoothing areas although OTG intentionally leaves some of the terrain above them intact. WATER can be used in combination with SpawnUnderWater to fill any air blocks underneath waterlevel with water (and any above waterlevel with air)."); writer.setting(BO3Settings.REPLACEABOVE, replaceAbove); writer.comment("Replaces all air blocks underneath the BO3 (but not its smoothing area) with the specified material until a solid block is found."); writer.setting(BO3Settings.REPLACEBELOW, replaceBelow); writer.comment("Defaults to true. If set to true then every block in the BO3 of the materials defined in ReplaceWithGroundBlock or ReplaceWithSurfaceBlock will be replaced by the GroundBlock or SurfaceBlock materials configured for the biome the block is spawned in."); writer.setting(BO3Settings.REPLACEWITHBIOMEBLOCKS, replaceWithBiomeBlocks); writer.comment("Defaults to DIRT, Replaces all the blocks of the given material in the BO3 with the GroundBlock configured for the biome it spawns in."); writer.setting(BO3Settings.REPLACEWITHGROUNDBLOCK, replaceWithGroundBlock); writer.comment("Defaults to GRASS, Replaces all the blocks of the given material in the BO3 with the SurfaceBlock configured for the biome it spawns in."); writer.setting(BO3Settings.REPLACEWITHSURFACEBLOCK, replaceWithSurfaceBlock); writer.comment("Makes the terrain around the BO3 slope evenly towards the edges of the BO3. The given value is the distance in blocks around the BO3 from where the slope should start and can be any positive number."); writer.setting(BO3Settings.SMOOTHRADIUS, smoothRadius); writer.comment("Moves the smoothing area up or down relative to the BO3 (at the points where the smoothing area is connected to the BO3). Handy when using SmoothStartTop: false and the BO3 has some layers of ground included, in that case we can set the HeightOffset to a negative value to lower the BO3 into the ground and we can set the SmoothHeightOffset to a positive value to move the smoothing area starting height up."); writer.setting(BO3Settings.SMOOTH_HEIGHT_OFFSET, smoothHeightOffset); writer.comment("Should the smoothing area be attached at the bottom or the top of the edges of the BO3? Defaults to false (bottom). Using this setting can make things slower so try to avoid using it and use SmoothHeightOffset instead if for instance you have a BO3 with some ground layers included. The only reason you should need to use this setting is if you have a BO3 with edges that have an irregular height (like some hills)."); writer.setting(BO3Settings.SMOOTHSTARTTOP, smoothStartTop); writer.comment("Should the smoothing area attach itself to \"log\" block or ignore them? Defaults to false (ignore logs)."); writer.setting(BO3Settings.SMOOTHSTARTWOOD, smoothStartWood); writer.comment("The block used for smoothing area surface blocks, defaults to biome SurfaceBlock."); writer.setting(BO3Settings.SMOOTHINGSURFACEBLOCK, smoothingSurfaceBlock); writer.comment("The block used for smoothing area ground blocks, defaults to biome GroundBlock."); writer.setting(BO3Settings.SMOOTHINGGROUNDBLOCK, smoothingGroundBlock); writer.comment("Define groups that this BO3 belongs to along with a minimum range in chunks that this BO3 must have between it and any other members of this group if it is to be allowed to spawn. Syntax is \"GroupName:Frequency, GoupName2:Frequency2\" etc so for example a BO3 that belongs to 3 groups: \"BO3Group: Ships:10, Vehicles:5, FloatingThings:3\"."); writer.setting(BO3Settings.BO3GROUP, bo3Group); writer.comment("Defaults to false. Set to true if this BO3 should spawn at the player spawn point. When the server starts the spawn point is determined and the BO3's for the biome it is in are loaded, one of these BO3s that has IsSpawnPoint set to true (if any) is selected randomly and is spawned at the spawn point regardless of its rarity (so even Rarity:0, IsSpawnPoint: true BO3's can get spawned as the spawn point!)."); writer.setting(BO3Settings.ISSPAWNPOINT, isSpawnPoint); // Blocks and other things writeResources(writer); } @Override protected void readConfigSettings() throws InvalidConfigException { isOTGPlus = readSettings(BO3Settings.IS_OTG_PLUS); if(isOTGPlus) { branchFrequency = readSettings(BO3Settings.BRANCH_FREQUENCY); branchFrequencyGroup = readSettings(BO3Settings.BRANCH_FREQUENCY_GROUP); heightOffset = readSettings(BO3Settings.HEIGHT_OFFSET); inheritBO3Rotation = readSettings(BO3Settings.INHERITBO3ROTATION); removeAir = readSettings(BO3Settings.REMOVEAIR); isSpawnPoint = readSettings(BO3Settings.ISSPAWNPOINT); replaceAbove = readSettings(BO3Settings.REPLACEABOVE); replaceBelow = readSettings(BO3Settings.REPLACEBELOW); replaceWithBiomeBlocks = readSettings(BO3Settings.REPLACEWITHBIOMEBLOCKS); replaceWithGroundBlock = readSettings(BO3Settings.REPLACEWITHGROUNDBLOCK); replaceWithSurfaceBlock = readSettings(BO3Settings.REPLACEWITHSURFACEBLOCK); bo3Group = readSettings(BO3Settings.BO3GROUP); canOverride = readSettings(BO3Settings.CANOVERRIDE); mustBeBelowOther = readSettings(BO3Settings.MUSTBEBELOWOTHER); mustBeInside = readSettings(BO3Settings.MUSTBEINSIDE); cannotBeInside = readSettings(BO3Settings.CANNOTBEINSIDE); replacesBO3 = readSettings(BO3Settings.REPLACESBO3); //smoothHeightOffset = readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET).equals("HeightOffset") ? heightOffset : Integer.parseInt(readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET)); smoothHeightOffset = readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET); CanSpawnOnWater = readSettings(BO3Settings.CANSPAWNONWATER); SpawnOnWaterOnly = readSettings(BO3Settings.SPAWNONWATERONLY); SpawnUnderWater = readSettings(BO3Settings.SPAWNUNDERWATER); SpawnAtWaterLevel = readSettings(BO3Settings.SPAWNATWATERLEVEL); inheritBO3 = readSettings(BO3Settings.INHERITBO3); overrideChildSettings = readSettings(BO3Settings.OVERRIDECHILDSETTINGS); overrideParentHeight = readSettings(BO3Settings.OVERRIDEPARENTHEIGHT); smoothRadius = readSettings(BO3Settings.SMOOTHRADIUS); smoothStartTop = readSettings(BO3Settings.SMOOTHSTARTTOP); smoothStartWood = readSettings(BO3Settings.SMOOTHSTARTWOOD); smoothingSurfaceBlock = readSettings(BO3Settings.SMOOTHINGSURFACEBLOCK); smoothingGroundBlock = readSettings(BO3Settings.SMOOTHINGGROUNDBLOCK); // Make sure that the BO3 wont try to spawn below Y 0 because of the height offset if(heightOffset < 0 && minHeight < -heightOffset) { minHeight = -heightOffset; } inheritedBO3s = new ArrayList<String>(); inheritedBO3s.add(this.getName()); // TODO: Make this cleaner? if(inheritBO3 != null && inheritBO3.trim().length() > 0) { inheritedBO3s.add(inheritBO3); } } author = readSettings(BO3Settings.AUTHOR); description = readSettings(BO3Settings.DESCRIPTION); settingsMode = readSettings(WorldStandardValues.SETTINGS_MODE_BO3); tree = readSettings(BO3Settings.TREE); frequency = readSettings(BO3Settings.FREQUENCY); rarity = readSettings(BO3Settings.RARITY); rotateRandomly = readSettings(BO3Settings.ROTATE_RANDOMLY); spawnHeight = readSettings(BO3Settings.SPAWN_HEIGHT); spawnHeightOffset = readSettings(BO3Settings.SPAWN_HEIGHT_OFFSET); spawnHeightVariance = readSettings(BO3Settings.SPAWN_HEIGHT_VARIANCE); extrudeMode = readSettings(BO3Settings.EXTRUDE_MODE); extrudeThroughBlocks = readSettings(BO3Settings.EXTRUDE_THROUGH_BLOCKS); minHeight = readSettings(BO3Settings.MIN_HEIGHT); maxHeight = readSettings(BO3Settings.MAX_HEIGHT); maxHeight = maxHeight < minHeight ? minHeight : maxHeight; maxBranchDepth = readSettings(BO3Settings.MAX_BRANCH_DEPTH); excludedBiomes = new ArrayList<String>(readSettings(BO3Settings.EXCLUDED_BIOMES)); sourceBlocks = readSettings(BO3Settings.SOURCE_BLOCKS); maxPercentageOutsideSourceBlock = readSettings(BO3Settings.MAX_PERCENTAGE_OUTSIDE_SOURCE_BLOCK); outsideSourceBlock = readSettings(BO3Settings.OUTSIDE_SOURCE_BLOCK); // Read the resources readResources(); this.reader = null; // Merge inherited resources if(isOTGPlus) { loadInheritedBO3(); } } void writeResources(SettingsWriterOTGPlus writer) throws IOException { writer.bigTitle("Blocks"); writer.comment("All the blocks used in the BO3 are listed here. Possible blocks:"); writer.comment("Block(x,y,z,id[.data][,nbtfile.nbt)"); writer.comment("RandomBlock(x,y,z,id[:data][,nbtfile.nbt],chance[,id[:data][,nbtfile.nbt],chance[,...]])"); writer.comment(" So RandomBlock(0,0,0,CHEST,chest.nbt,50,CHEST,anotherchest.nbt,100) will spawn a chest at"); writer.comment(" the BO3 origin, and give it a 50% chance to have the contents of chest.nbt, or, if that"); writer.comment(" fails, a 100% percent chance to have the contents of anotherchest.nbt."); writer.comment("MinecraftObject(x,y,z,name) (TODO: This may not work anymore and needs to be tested."); writer.comment(" Spawns an object in the Mojang NBT structure format. For example, "); writer.comment(" MinecraftObject(0,0,0," + DefaultStructurePart.IGLOO_BOTTOM.getPath() + ")"); writer.comment(" spawns the bottom part of an igloo."); for(BlockFunction func : Arrays.asList(blocks[0])) { writer.function(func); } writer.bigTitle("BO3 checks"); writer.comment("Ignored when IsOTGPlus:true."); writer.comment("Require a condition at a certain location in order for the BO3 to be spawned."); writer.comment("BlockCheck(x,y,z,BlockName[,BlockName[,...]]) - one of the blocks must be at the location"); writer.comment("BlockCheckNot(x,y,z,BlockName[,BlockName[,...]]) - all the blocks must not be at the location"); writer.comment("LightCheck(x,y,z,minLightLevel,maxLightLevel) - light must be between min and max (inclusive)"); writer.comment(""); writer.comment("You can use \"Solid\" as a BlockName for matching all solid blocks or \"All\" to match all blocks that aren't air."); writer.comment(""); writer.comment("Examples:"); writer.comment(" BlockCheck(0,-1,0,GRASS,DIRT) Require grass or dirt just below the object"); writer.comment(" BlockCheck(0,-1,0,Solid) Require any solid block just below the object"); writer.comment(" BlockCheck(0,-1,0,WOOL) Require any type of wool just below the object"); writer.comment(" BlockCheck(0,-1,0,WOOL:0) Require white wool just below the object"); writer.comment(" BlockCheckNot(0,-1,0,WOOL:0) Require that there is no white wool below the object"); writer.comment(" LightCheck(0,0,0,0,1) Require almost complete darkness just below the object"); for(BO3Check func : Arrays.asList(bo3Checks[0])) { writer.function(func); } writer.bigTitle("Branches"); writer.comment("Branches are child-BO3's that spawn if this BO3 is configured to spawn as a"); writer.comment("CustomStructure resource in a biome config. Branches can have branches,"); writer.comment("making complex structures possible. See the wiki for more details."); writer.comment(""); writer.comment("Regular Branches spawn each branch with an independent chance of spawning."); writer.comment("When IsOTGPlus is set to false: Branch(x,y,z,branchName,rotation,chance[,anotherBranchName,rotation,chance[,...]][IndividualChance])"); writer.comment("When IsOTGPlus is set to true: Branch(x,y,z,isRequiredBranch,branchName,rotation,chance,branchDepth[,anotherBranchName,rotation,chance,branchDepth[,...]][IndividualChance])"); writer.comment("branchName - name of the object to spawn."); writer.comment("rotation - NORTH, SOUTH, EAST or WEST."); writer.comment("IndividualChance - The chance each branch has to spawn, assumed to be 100 when left blank"); writer.comment("isRequiredBranch - If this is set to true then at least one of the branches in this BO3 must spawn at these x,y,z coordinates. If no branch can spawn there then this BO3 fails to spawn and its branch is rolled back."); writer.comment("isRequiredBranch:true branches must spawn or the current branch is rolled back entirely. This is useful for grouping BO3's that must spawn together, for instance a single room made of multiple BO3's/branches."); writer.comment("If all parts of the room are connected together via isRequiredBranch:true branches then either the entire room will spawns or no part of it will spawn."); writer.comment("*Note: When isRequiredBranch:true only one BO3 can be added per Branch() and it will automatically have a rarity of 100.0."); writer.comment("isRequiredBranch:false branches are used to make optional parts of structures, for instance the middle section of a tunnel that has a beginning, middle and end BO3/branch and can have a variable length by repeating the middle BO3/branch."); writer.comment("By making the start and end branches isRequiredBranch:true and the middle branch isRequiredbranch:false you can make it so that either:"); writer.comment("A. A tunnel spawns with at least a beginning and end branch"); writer.comment("B. A tunnel spawns with a beginning and end branch and as many middle branches as will fit in the available space."); writer.comment("C. No tunnel spawns at all because there wasn't enough space to spawn at least a beginning and end branch."); writer.comment("branchDepth - When creating a chain of branches that contains optional (isRequiredBranch:false) branches branch depth is configured for the first BO3 in the chain to determine the maximum length of the chain."); writer.comment("branchDepth - 1 is inherited by each isRequiredBranch:false branch in the chain. When branchDepth is zero isRequiredBranch:false branches cannot spawn and the chain ends. In the case of the tunnel this means the last middle branch would be"); writer.comment("rolled back and an IsRequiredBranch:true end branch could be spawned in its place to make sure the tunnel has a proper ending."); writer.comment("Instead of inheriting branchDepth - 1 from the parent branchDepth can be overridden by child branches if it is set higher than 0 (the default value)."); writer.comment("isRequiredBranch:true branches do inherit branchDepth and pass it on to their own branches, however they cannot be prevented from spawning by it and also don't subtract 1 from branchDepth when inheriting it."); writer.comment(""); writer.comment("Weighted Branches spawn branches with a dependent chance of spawning."); writer.comment("When IsOTGPlus is set to false: WeightedBranch(x,y,z,branchName,rotation,chance[,anotherBranchName,rotation,chance[,...]][MaxChanceOutOf])"); writer.comment("When IsOTGPlus is set to true: WeightedBranch(x,y,z,isRequiredBranch,branchName,rotation,chance,branchDepth[,anotherBranchName,rotation,chance,branchDepth[,...]][MaxChanceOutOf])"); writer.comment("*Note: isRequiredBranch must be set to false. It is not possible to use isRequiredBranch:true with WeightedBranch() since isRequired:true branches must spawn and automatically have a rarity of 100.0."); writer.comment("MaxChanceOutOf - The chance all branches have to spawn out of, assumed to be 100 when left blank"); for(BranchFunction func : Arrays.asList(branches[0])) { writer.function(func); } writer.bigTitle("Entities"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("An EntityFunction spawns an entity instead of a block. The entity is spawned only once when the BO3 is spawned."); writer.comment("Entities are persistent by default so they don't de-spawn when no player is near, they are only unloaded."); writer.comment("Usage: Entity(x,y,z,entityName,groupSize,NameTagOrNBTFileName) or Entity(x,y,z,mobName,groupSize)"); writer.comment("Use /otg entities to get a list of entities that can be used as entityName, this includes entities added by other mods and non-living entities."); writer.comment("NameTagOrNBTFileName can be either a nametag for the mob or an .txt file with nbt data (such as myentityinfo.txt)."); writer.comment("In the text file you can use the same mob spawning parameters used with the /summon command to equip the"); writer.comment("entity and give it custom attributes etc. You can copy the DATA part of a summon command including surrounding "); writer.comment("curly braces to a .txt file, for instance for: \"/summon Skeleton x y z {DATA}\""); for(EntityFunction func : Arrays.asList(entityFunctions[0])) { writer.function(func); } writer.bigTitle("Particles"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("Creates an invisible particle spawner at the given location that spawns particles every x milliseconds."); writer.comment("Usage: Particle(x,y,z,particleName,interval,velocityX,velocityY,velocityZ)"); writer.comment("velocityX, velocityY and velocityZ are optional."); writer.comment("Only vanilla particle names can be used, for 1.11.2 these are;"); writer.comment("explode, largeexplode, hugeexplosion, fireworksSpark, bubble, splash, wake, suspended"); writer.comment("depthsuspend, crit, magicCrit, smoke, largesmoke, spell, instantSpell, mobSpell"); writer.comment("mobSpellAmbient, witchMagic, dripWater, dripLava, angryVillager, happyVillager"); writer.comment("townaura, note, portal, enchantmenttable, flame, lava, footstep, cloud, reddust"); writer.comment("snowballpoof, snowshovel, slime, heart, barrier, iconcrack, blockcrack, blockdust"); writer.comment("droplet, take, mobappearance, dragonbreath, endRod, damageIndicator, sweepAttack"); writer.comment("fallingdust, totem, spit."); writer.comment("velocityX,velocityY,velocityZ - Spawn the enemy with the given velocity. If this is not filled in then a small random velocity is applied."); for(ParticleFunction func : Arrays.asList(particleFunctions[0])) { writer.function(func); } writer.bigTitle("Spawners"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("Creates an invisible entity spawner at the given location that spawns entities every x seconds."); writer.comment("Entities can only spawn if their spawn requirements are met (zombies/skeletons only spawn in the dark etc). Max entity count for the server is ignored, each spawner has its own maxCount setting."); writer.comment("Usage: Spawner(x,y,z,entityName,nbtFileName,groupSize,interval,spawnChance,maxCount,despawnTime,velocityX,velocityY,velocityZ,yaw,pitch)"); writer.comment("nbtFileName, despawnTime, velocityX, velocityY, velocityZ, yaw and pitch are optional"); writer.comment("Example Spawner(0, 0, 0, Villager, 1, 5, 100, 5) or Spawner(0, 0, 0, Villager, villager1.txt, 1, 5, 100, 5) or Spawner(0, 0, 0, Villager, 1, 5, 100, 5, 30, 1, 1, 1, 0, 0)"); writer.comment("entityName - Name of the entity to spawn, use /otg entities to get a list of entities that can be used as entityName, this includes entities added by other mods and non-living entities."); writer.comment("nbtFileName - A .txt file with nbt data (such as myentityinfo.txt)."); writer.comment("In the text file you can use the same mob spawning parameters used with the /summon command to equip the"); writer.comment("entity and give it custom attributes etc. You can copy the DATA part of a summon command including surrounding "); writer.comment("curly braces to a .txt file, for instance for: \"/summon Skeleton x y z {DATA}\""); writer.comment("groupSize - Number of entities that should spawn for each successful spawn attempt."); writer.comment("interval - Time in seconds between each spawn attempt."); writer.comment("spawnChance - For each spawn attempt, the chance between 0-100 that the spawn attempt will succeed."); writer.comment("maxCount - The maximum amount of this kind of entity that can exist within 32 blocks. If there are already maxCount or more entities of this type in a 32 radius this spawner will not spawn anything."); writer.comment("despawnTime - After despawnTime seconds, if there is no player within 32 blocks of the entity it will despawn.."); writer.comment("velocityX,velocityY,velocityZ,yaw,pitch - Spawn the enemy with the given velocity and angle, handy for making traps and launchers (shooting arrows and fireballs etc)."); for(SpawnerFunction func : Arrays.asList(spawnerFunctions[0])) { writer.function(func); } // ModData writer.bigTitle("ModData"); writer.comment("Forge only."); writer.comment("Use the ModData() tag to include data that other mods can use"); writer.comment("Mod makers can use ModData and the /otg GetModData command to test IMC communications between OTG"); writer.comment("and their mod."); writer.comment("Normal users can use it to spawn some mobs and blocks on command."); writer.comment("ModData(x,y,z,\"ModName\", \"MyModDataAsText\""); writer.comment("Example: ModData(x,y,z,MyCystomNPCMod,SpawnBobHere/WithAPotato/And50Health)"); writer.comment("Try not to use exotic/reserved characters, like brackets and comma's etc, this stuff isn't fool-proof."); writer.comment("Also, use this only to store IDs/object names etc for your mod, DO NOT include things like character dialogue,"); writer.comment("messages on signs, loot lists etc in this file. As much as possible just store id's/names here and store all the data related to those id's/names in your own mod."); writer.comment("OTG has some built in ModData commands for basic mob and block spawning."); writer.comment("These are mostly just a demonstration for mod makers to show how ModData."); writer.comment("can be used by other mods."); writer.comment("For mob spawning in OTG use: ModData(x,y,z,OTG,mob/MobType/Count/Persistent/Name)"); writer.comment("mob: Makes OTG recognise this as a mob spawning command."); writer.comment("MobType: Lower-case, no spaces. Any vanilla mob like dragon, skeleton, wither, villager etc"); writer.comment("Count: The number of mobs to spawn"); writer.comment("Persistent (true/false): Should the mobs never de-spawn? If set to true the mob will get a"); writer.comment("name-tag ingame so you can recognise it."); writer.comment("Name: A name-tag for the monster/npc."); writer.comment("Example: ModData(0,0,0,OTG,villager/1/true/Bob)"); writer.comment("To spawn blocks using ModData use: ModData(x,y,z,OTG,block/material)"); writer.comment("block: Makes OTG recognise this as a block spawning command."); writer.comment("material: id or text, custom blocks can be added using ModName:MaterialName."); writer.comment("To send all ModData within a radius in chunks around the player to the specified mod"); writer.comment("use this console command: /otg GetModData ModName Radius"); writer.comment("ModName: name of the mod, for OTG commands use OTG "); writer.comment("Radius (optional): Radius in chunks around the player."); for(ModDataFunction func : Arrays.asList(modDataFunctions[0])) { writer.function(func); } } @Override protected void correctSettings() { } @Override protected void renameOldSettings() { // Stub method - there are no old setting to convert yet (: } // Not used for OTG+ CustomStructures /** * Rotates all the blocks and all the checks */ public void rotateBlocksAndChecks() { for (int i = 1; i < 4; i++) { // Blocks (blocks[i - 1] is previous rotation) blocks[i] = new BlockFunction[blocks[i - 1].length]; for (int j = 0; j < blocks[i].length; j++) { blocks[i][j] = blocks[i - 1][j].rotate(); } // BO3 checks bo3Checks[i] = new BO3Check[bo3Checks[i - 1].length]; for (int j = 0; j < bo3Checks[i].length; j++) { bo3Checks[i][j] = bo3Checks[i - 1][j].rotate(); } // Branches branches[i] = new BranchFunction[branches[i - 1].length]; for (int j = 0; j < branches[i].length; j++) { branches[i][j] = branches[i - 1][j].rotate(); } // Bounding box boundingBoxes[i] = boundingBoxes[i - 1].rotate(); entityFunctions[i] = new EntityFunction[entityFunctions[i - 1].length]; for (int j = 0; j < entityFunctions[i].length; j++) { entityFunctions[i][j] = entityFunctions[i - 1][j].rotate(); } particleFunctions[i] = new ParticleFunction[particleFunctions[i - 1].length]; for (int j = 0; j < particleFunctions[i].length; j++) { particleFunctions[i][j] = particleFunctions[i - 1][j].rotate(); } spawnerFunctions[i] = new SpawnerFunction[spawnerFunctions[i - 1].length]; for (int j = 0; j < spawnerFunctions[i].length; j++) { spawnerFunctions[i][j] = spawnerFunctions[i - 1][j].rotate(); } modDataFunctions[i] = new ModDataFunction[modDataFunctions[i - 1].length]; for (int j = 0; j < modDataFunctions[i].length; j++) { modDataFunctions[i][j] = modDataFunctions[i - 1][j].rotate(); } } } }
3e15bbe014800e2c0038e83cb1a649e3ea50236a
506
java
Java
src/enums/Result.java
phoenix-oosd/EVTC-Log-Parser
dbd36710802f77350ade637d40c82c0a68e34a72
[ "MIT" ]
15
2017-01-30T16:49:36.000Z
2021-02-11T11:19:07.000Z
src/enums/Result.java
phoenix-oosd/EVTC-Log-Parser
dbd36710802f77350ade637d40c82c0a68e34a72
[ "MIT" ]
4
2017-01-31T13:06:25.000Z
2017-02-25T00:00:26.000Z
src/enums/Result.java
phoenix-oosd/EVTC-Log-Parser
dbd36710802f77350ade637d40c82c0a68e34a72
[ "MIT" ]
6
2017-02-22T15:17:17.000Z
2018-04-03T01:21:28.000Z
12.65
40
0.543478
9,225
package enums; public enum Result { // Constants NORMAL(0), CRIT(1), GLANCE(2), BLOCK(3), EVADE(4), INTERRUPT(5), ABSORB(6), BLIND(7), KILLING_BLOW(8); // Fields private int ID; // Constructors private Result(int ID) { this.ID = ID; } // Public Methods public static Result getEnum(int ID) { for (Result r : values()) { if (r.getID() == ID) { return r; } } return null; } // Getters public int getID() { return ID; } }
3e15bd02d6e9eb124fadabe2432e0605a398c6ef
340
java
Java
dashboard/src/main/java/org/consumersunion/stories/common/shared/dto/ResourceLink.java
stori-es/stories
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
2
2016-06-02T22:29:19.000Z
2019-06-12T18:51:01.000Z
dashboard/src/main/java/org/consumersunion/stories/common/shared/dto/ResourceLink.java
stori-es/stories
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
43
2016-04-05T19:01:50.000Z
2016-12-22T00:35:19.000Z
dashboard/src/main/java/org/consumersunion/stories/common/shared/dto/ResourceLink.java
stori-es/stori_es
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
null
null
null
16.190476
53
0.605882
9,226
package org.consumersunion.stories.common.shared.dto; public class ResourceLink { private String href; public ResourceLink(String href) { this.href = href; } ResourceLink() { } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
3e15bdd6d87818aefd3740b53e314b7369c92e07
613
java
Java
subprojects/38k.tef/src/main/java/tef/ui/http/TefHttpServer.java
openNaEF/openNaEF
c88f0e17adc8d3f266787846911787f9b8aa3b0d
[ "Apache-2.0" ]
13
2017-05-23T01:50:10.000Z
2018-11-28T01:45:11.000Z
subprojects/38k.tef/src/main/java/tef/ui/http/TefHttpServer.java
openNaEF/openNaEF
c88f0e17adc8d3f266787846911787f9b8aa3b0d
[ "Apache-2.0" ]
null
null
null
subprojects/38k.tef/src/main/java/tef/ui/http/TefHttpServer.java
openNaEF/openNaEF
c88f0e17adc8d3f266787846911787f9b8aa3b0d
[ "Apache-2.0" ]
null
null
null
26.652174
84
0.745514
9,227
package tef.ui.http; import lib38k.logger.Logger; import lib38k.net.httpd.HttpConnection; import lib38k.net.httpd.HttpServer; import java.net.Socket; public class TefHttpServer extends HttpServer { public static final String PLUGIN_CONFIG_FILE_NAME = "TefHttpPluginsConfig.xml"; public static final String EXTRA_RESPONSE_STATUS_HEADER_FIELD_NAME = "X-TEF-Response-Status"; public TefHttpServer(Config config, Logger logger) { super(config, logger); } protected HttpConnection newConnection(Socket socket) { return new TefHttpConnection(this, socket); } }
3e15be2668f70b4b91dce320c41d7954518dd4b2
103
java
Java
test/sematest/invalid/array_access_with_wrong_type.java
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
3
2019-08-09T00:57:22.000Z
2020-06-18T23:03:05.000Z
test/sematest/invalid/array_access_with_wrong_type.java
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
null
null
null
test/sematest/invalid/array_access_with_wrong_type.java
Azegor/mjc
8b7eaca7e2079378d99a2a6fc7f6076976922dab
[ "MIT" ]
null
null
null
17.166667
42
0.504854
9,228
class A { public static void main(String[] args) { A[] a = new A[1]; a[true] = new A(); } }
3e15be616db3ec55e4a79bbd9697d0d12b4e4459
238
java
Java
src/application/Piece.java
dacostal/echec
cb05c91ecafbdc188f4e574b103aa2bd8ef9a73d
[ "MIT" ]
null
null
null
src/application/Piece.java
dacostal/echec
cb05c91ecafbdc188f4e574b103aa2bd8ef9a73d
[ "MIT" ]
null
null
null
src/application/Piece.java
dacostal/echec
cb05c91ecafbdc188f4e574b103aa2bd8ef9a73d
[ "MIT" ]
null
null
null
17
74
0.764706
9,229
package application; import java.util.List; public abstract class Piece { protected String couleur; public String getCouleur() { return this.couleur; } public abstract List<Case> getLegalMoves(Echiquier board, Case position); }
3e15be806242fe3edfd02fc4d710bd0ce713833a
935
java
Java
CS100s/CS161/ClassLabs/Lab12a/Iface/NestedRectsController.java
AndrewZurn/sju-compsci-archive
3ea0e4f0db8453a011fc7511140df788dde5aae2
[ "Apache-2.0" ]
null
null
null
CS100s/CS161/ClassLabs/Lab12a/Iface/NestedRectsController.java
AndrewZurn/sju-compsci-archive
3ea0e4f0db8453a011fc7511140df788dde5aae2
[ "Apache-2.0" ]
null
null
null
CS100s/CS161/ClassLabs/Lab12a/Iface/NestedRectsController.java
AndrewZurn/sju-compsci-archive
3ea0e4f0db8453a011fc7511140df788dde5aae2
[ "Apache-2.0" ]
null
null
null
30.16129
72
0.634225
9,230
import objectdraw.*; import java.awt.*; // creates a set of NestedRects and allows them to be dragged or removed // according to the action of the mouse public class NestedRectsController extends FrameWindowController { // dimensions of NestedRects private static final double WIDTH = 200, HEIGHT = 100; private NestedRects rects; // draw a new set of NestedRects where the mouse was pressed public void onMousePress(Location point) { rects = new NestedRects( point.getX(), point.getY(), WIDTH, HEIGHT, canvas ); rects.setColor(Color.BLUE); } // move the rects with the mouse public void onMouseDrag(Location point) { rects.moveTo(point.getX(), point.getY()); } // remove the rects from the canvas public void onMouseRelease(Location point) { // rects.removeFromCanvas(); } }
3e15be973dc5bc3911245f16e27c4a8de71950a7
12,776
java
Java
HammerCore/src/main/java/uk/co/drnaylor/minecraft/hammer/core/commands/CommandCore.java
dualspiral/Hammer
e165da6092f32c3afb9ed436a31aacfbd1c4c903
[ "MIT" ]
4
2015-03-03T08:32:29.000Z
2017-07-18T18:46:49.000Z
HammerCore/src/main/java/uk/co/drnaylor/minecraft/hammer/core/commands/CommandCore.java
dualspiral/Hammer
e165da6092f32c3afb9ed436a31aacfbd1c4c903
[ "MIT" ]
7
2015-10-27T18:11:03.000Z
2016-08-06T11:56:03.000Z
HammerCore/src/main/java/uk/co/drnaylor/minecraft/hammer/core/commands/CommandCore.java
dualspiral/Hammer
e165da6092f32c3afb9ed436a31aacfbd1c4c903
[ "MIT" ]
2
2015-03-15T03:36:16.000Z
2015-07-10T12:25:48.000Z
38.95122
146
0.637132
9,231
/* * This file is part of Hammer, licensed under the MIT License (MIT). * * Copyright (c) 2015 Daniel Naylor * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package uk.co.drnaylor.minecraft.hammer.core.commands; import java.text.Format; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.*; import ninja.leaping.configurate.ConfigurationNode; import uk.co.drnaylor.minecraft.hammer.core.HammerConstants; import uk.co.drnaylor.minecraft.hammer.core.HammerCore; import uk.co.drnaylor.minecraft.hammer.core.audit.AuditEntry; import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.ArgumentParseException; import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.ArgumentMap; import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.FlagParser; import uk.co.drnaylor.minecraft.hammer.core.commands.parsers.IParser; import uk.co.drnaylor.minecraft.hammer.core.data.HammerPlayerInfo; import uk.co.drnaylor.minecraft.hammer.core.exceptions.HammerException; import uk.co.drnaylor.minecraft.hammer.core.handlers.DatabaseConnection; import uk.co.drnaylor.minecraft.hammer.core.text.HammerText; import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextBuilder; import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextColours; import uk.co.drnaylor.minecraft.hammer.core.wrappers.WrappedCommandSource; import uk.co.drnaylor.minecraft.hammer.core.wrappers.WrappedPlayer; public abstract class CommandCore { static final Format dateFormatter; static final ResourceBundle messageBundle = ResourceBundle.getBundle("assets.hammer.messages", Locale.getDefault()); Collection<String> permissionNodes = new ArrayList<>(); private final boolean isAsync; private final List<ParserEntry> parsersList; final HammerCore core; static { dateFormatter = new SimpleDateFormat(messageBundle.getString("hammer.display.date")); } CommandCore(HammerCore core) { this.core = core; RunAsync a = this.getClass().getAnnotation(RunAsync.class); this.isAsync = a != null && a.isAsync(); this.parsersList = createArgumentParserList(); } protected abstract List<ParserEntry> createArgumentParserList(); private Optional<ArgumentMap> getArguments(List<String> arguments) throws HammerException, ArgumentParseException { ListIterator<String> lis = arguments.listIterator(); ArgumentMap am = new ArgumentMap(); for (ParserEntry pe : parsersList) { Optional o; try { o = pe.parser.parseArgument(lis); } catch (ArgumentParseException ape) { if (!ape.isDontSkip() && pe.isOptional) { o = Optional.empty(); } else { // Re-throw throw new ArgumentParseException(pe.name, ape); } } if (o.isPresent()) { am.put(pe.name, o.get()); } else { // Is it optional? if (pe.isOptional) { pe.parser.onFailedButOptional(lis); } else { return Optional.empty(); } } } return Optional.of(am); } protected abstract boolean requiresDatabase(); /** * Executes the specific routines in this command core with the specified source. * * @param source The {@link WrappedCommandSource} that is executing the command. * @param arguments The arguments of the command * @param conn If the command requires database access, holds a {@link DatabaseConnection} object. Otherwise, null. * @return Whether the command succeeded * @throws HammerException Thrown if an exception is thrown in the command core. */ protected abstract boolean executeCommand(WrappedCommandSource source, ArgumentMap arguments, DatabaseConnection conn) throws HammerException; protected abstract String commandName(); /** * Gets the usage of this command * * @return The {@link HammerText} */ public final HammerText getUsageMessage() { // Get the command name. StringBuilder args = new StringBuilder("/").append(commandName()); for (ParserEntry parserEntry : this.parsersList) { args.append(" "); String n = parserEntry.name; if (parserEntry.parser instanceof FlagParser) { n = ((FlagParser) parserEntry.parser).getFlagEntries(); } if (parserEntry.isOptional) { args.append("[").append(n).append("]"); } else { args.append("<").append(n).append(">"); } } return new HammerTextBuilder().add(args.toString(), HammerTextColours.YELLOW).build(); } public final Collection<String> getRequiredPermissions() { return permissionNodes; } /** * Entry point into any command core * * @param source The {@link WrappedCommandSource} that is executing the command * @param arguments The arguments of the command * @return Whether the command succeeded * @throws HammerException Thrown if an exception is thrown in the command core */ public final boolean executeCommand(final WrappedCommandSource source, final List<String> arguments) throws HammerException { // Permission check for (String p : this.getRequiredPermissions()) { if (!source.hasPermission(p)) { sendNoPermsMessage(source); return true; } } /* * This runner allows us to run commands async, if the class is marked with the {@link RunAsync} annotation */ CommandRunner r = new CommandRunner() { @Override public boolean runCommand(ArgumentMap args) throws HammerException { // Command execution. if (requiresDatabase()) { try (DatabaseConnection conn = core.getDatabaseConnection()) { return executeCommand(source, args, conn); } catch (HammerException ex) { throw ex; } catch (Exception ex) { ex.printStackTrace(); throw new HammerException("An unspecified error occurred", ex); } } else { return executeCommand(source, args, null); } } @Override public void run() { try { Optional<ArgumentMap> arg = constructArgumentMap(source, arguments); if (arg.isPresent()) { runCommand(arg.get()); } else { sendUsageMessage(source); } } catch (HammerException ex) { source.sendMessage(ex.getMessage()); } } }; // Get the class and check for the RunAsync annotation. if (isAsync) { core.getWrappedServer().getScheduler().runAsyncNow(r); return true; } Optional<ArgumentMap> arg; try { arg = constructArgumentMap(source, arguments); if (arg.isPresent()) { return r.runCommand(arg.get()); } else { sendUsageMessage(source); return true; } } catch (HammerException ex) { source.sendMessage(ex.getMessage()); } return true; } private Optional<ArgumentMap> constructArgumentMap(final WrappedCommandSource source, List<String> args) throws HammerException { try { return getArguments(args); } catch (ArgumentParseException e) { source.sendMessage(new HammerTextBuilder().add("[Hammer] ", HammerTextColours.RED).add(e.getHammerTextMessage()).build()); return Optional.empty(); } } /** * Creates and sends a templated message * * @param player The {@link WrappedCommandSource} to send the message to * @param messageKey The message key in the resource bundle * @param isError Whether to create an error message or not * @param useStub Whether to use the [Hammer] tag * @param replacements The replacements in the templated message */ final void sendTemplatedMessage(WrappedCommandSource player, String messageKey, boolean isError, boolean useStub, String... replacements) { sendMessage(player, MessageFormat.format(messageBundle.getString(messageKey), (Object[]) replacements), isError, useStub); } /** * Sends a message to the {@link WrappedCommandSource} * * @param player The player to send a message to * @param message The message to send * @param isError Whether the message is an error * @param useStub Whether to use the [Hammer] tag */ final void sendMessage(WrappedCommandSource player, String message, boolean isError, boolean useStub) { HammerTextBuilder hb; if (useStub) { hb = isError ? createErrorMessageStub() : createNormalMessageStub(); } else { hb = new HammerTextBuilder(); } hb.add(" " + message, isError ? HammerTextColours.RED : HammerTextColours.GREEN); player.sendMessage(hb.build()); } /** * Sends the usage message to the {@link WrappedCommandSource}. * * @param source The source. */ final void sendUsageMessage(WrappedCommandSource source) { String f = String.format(" %s ", messageBundle.getString("hammer.player.commandUsage")); HammerTextBuilder hb = createErrorMessageStub().add(f, HammerTextColours.RED) .add(this.getUsageMessage()); source.sendMessage(hb.build()); } final void sendNoPermsMessage(WrappedCommandSource target) { sendTemplatedMessage(target, "hammer.player.noperms", true, true); } protected final String getName(UUID name, DatabaseConnection conn) throws HammerException { WrappedPlayer playerTarget = core.getWrappedServer().getPlayer(name); String playerName; if (playerTarget == null) { // Do we have them in the Hammer DB? HammerPlayerInfo p = conn.getPlayerHandler().getPlayer(name); if (p == null) { playerName = "Unknown Player"; } else { playerName = p.getName(); } } else { playerName = playerTarget.getName(); } return playerName; } protected final void insertAuditEntry(AuditEntry entry, DatabaseConnection conn) throws HammerException { core.getAuditHelper().insertAuditEntry(entry, conn); } private HammerTextBuilder createErrorMessageStub() { return new HammerTextBuilder().add(HammerConstants.textTag, HammerTextColours.RED); } private HammerTextBuilder createNormalMessageStub() { return new HammerTextBuilder().add(HammerConstants.textTag, HammerTextColours.GREEN); } private interface CommandRunner extends Runnable { boolean runCommand(ArgumentMap args) throws HammerException; } protected final class ParserEntry { public final String name; public final IParser parser; public final boolean isOptional; public ParserEntry(String name, IParser parser, boolean isOptional) { this.name = name; this.parser = parser; this.isOptional = isOptional; } } }
3e15bea777a86a6b3a20a6b4ae1330ed13587beb
2,261
java
Java
src/test/java/com/mijecu25/sqlplus/compiler/core/statement/TestStatement.java
mijecu25/sql-plus
0ae16e276952caa17aa5603df3aa4cb50a69d137
[ "MIT" ]
1
2016-02-26T01:32:10.000Z
2016-02-26T01:32:10.000Z
src/test/java/com/mijecu25/sqlplus/compiler/core/statement/TestStatement.java
mijecu25/sql-plus
0ae16e276952caa17aa5603df3aa4cb50a69d137
[ "MIT" ]
22
2016-02-26T03:03:27.000Z
2016-09-05T01:29:12.000Z
src/test/java/com/mijecu25/sqlplus/compiler/core/statement/TestStatement.java
mijecu25/sql-plus
0ae16e276952caa17aa5603df3aa4cb50a69d137
[ "MIT" ]
null
null
null
24.576087
109
0.638655
9,232
package com.mijecu25.sqlplus.compiler.core.statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Test Statement * * @author Miguel Velez - miguelvelezmj25 * @version 0.1.0.4 */ public class TestStatement { // private static StatementConcrete statement; protected static Properties properties; protected static Connection connection; @BeforeClass public static void initialize() throws SQLException { TestStatement.properties = new Properties(); TestStatement.properties.put("user", System.getProperty("user.name")); TestStatement.connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/", properties); // TestStatement.statement = new TestStatement().new StatementConcrete(); } @AfterClass public static void terminate() throws SQLException { TestStatement.connection.close(); } /** * Implementation of abstract class to test the abstract class. * * @author Miguel Velez - miguelvelezmj25 * @version 0.1.0.1 */ private class StatementConcrete extends Statement { public StatementConcrete() { super(); } public StatementConcrete(String statement) { super(); } @Override public void execute(Connection connection) throws SQLException { // Abstract method } @Override public void printResult() { // Abstract method } } @Test public void testStatement1() { StatementConcrete statement = new StatementConcrete("statement"); Assert.assertNotNull(statement); } @Test public void testStatement3() { StatementConcrete statement = new StatementConcrete(); Assert.assertNotNull(statement); } @Test public void testBuildHorizontalBorder() { String line = Statement.buildHorizontalBorder(5); Assert.assertNotNull(line); } // TODO test execute }
3e15beb320c5a76037a6a45b5328bb1c804c5582
2,444
java
Java
server/impl/src/main/java/com/walmartlabs/concord/server/process/ProcessStatusHistoryEntry.java
codyaverett/concord
7f1b093407271c10880c767a922e68d95c7087ac
[ "Apache-2.0" ]
1
2021-06-16T03:03:43.000Z
2021-06-16T03:03:43.000Z
server/impl/src/main/java/com/walmartlabs/concord/server/process/ProcessStatusHistoryEntry.java
codyaverett/concord
7f1b093407271c10880c767a922e68d95c7087ac
[ "Apache-2.0" ]
null
null
null
server/impl/src/main/java/com/walmartlabs/concord/server/process/ProcessStatusHistoryEntry.java
codyaverett/concord
7f1b093407271c10880c767a922e68d95c7087ac
[ "Apache-2.0" ]
null
null
null
29.804878
92
0.637889
9,233
package com.walmartlabs.concord.server.process; /*- * ***** * Concord * ----- * Copyright (C) 2017 - 2018 Walmart 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. * ===== */ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import java.util.Date; import java.util.Map; import java.util.UUID; @JsonInclude(Include.NON_EMPTY) public class ProcessStatusHistoryEntry implements Serializable { private final UUID id; private final ProcessStatus status; private final Map<String, Object> payload; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX") private final Date changeDate; @JsonCreator public ProcessStatusHistoryEntry(@JsonProperty("id") UUID id, @JsonProperty("status") ProcessStatus status, @JsonProperty("changeDate") Date changeDate, @JsonProperty("payload") Map<String, Object> payload) { this.id = id; this.status = status; this.changeDate = changeDate; this.payload = payload; } public UUID getId() { return id; } public ProcessStatus getStatus() { return status; } public Date getChangeDate() { return changeDate; } public Map<String, Object> getPayload() { return payload; } @Override public String toString() { return "ProcessStatusHistoryEntry{" + "id=" + id + ", status='" + status + '\'' + ", changeDate=" + changeDate + ", payload='" + payload + '\'' + '}'; } }
3e15bee9b4b91edce7ac672b563d467647c76fae
3,005
java
Java
test/ch/tsphp/tinsphp/inference_engine/test/integration/testutils/TestSymbolFactory.java
TinsPHP/tins-inference-engine
3d013370b9a0e3d4f8d5535a077a3210b5d8efef
[ "Apache-2.0" ]
1
2021-03-20T17:00:41.000Z
2021-03-20T17:00:41.000Z
test/ch/tsphp/tinsphp/inference_engine/test/integration/testutils/TestSymbolFactory.java
TinsPHP/tins-inference-engine
3d013370b9a0e3d4f8d5535a077a3210b5d8efef
[ "Apache-2.0" ]
null
null
null
test/ch/tsphp/tinsphp/inference_engine/test/integration/testutils/TestSymbolFactory.java
TinsPHP/tins-inference-engine
3d013370b9a0e3d4f8d5535a077a3210b5d8efef
[ "Apache-2.0" ]
null
null
null
36.204819
118
0.734775
9,234
/* * This file is part of the TinsPHP project published under the Apache License 2.0 * For the full copyright and license information, please have a look at LICENSE in the * root folder or visit the project's website http://tsphp.ch/wiki/display/TINS/License */ /* * This class is based on the class TestSymbolFactory from the TSPHP project. * TSPHP is also published under the Apache License 2.0 * For more information see http://tsphp.ch/wiki/display/TSPHP/License */ package ch.tsphp.tinsphp.inference_engine.test.integration.testutils; import ch.tsphp.common.IScope; import ch.tsphp.common.ITSPHPAst; import ch.tsphp.common.symbols.ISymbol; import ch.tsphp.tinsphp.common.scopes.IScopeHelper; import ch.tsphp.tinsphp.common.symbols.IMethodSymbol; import ch.tsphp.tinsphp.common.symbols.IModifierHelper; import ch.tsphp.tinsphp.common.symbols.IVariableSymbol; import ch.tsphp.tinsphp.common.utils.ITypeHelper; import ch.tsphp.tinsphp.symbols.SymbolFactory; import java.util.ArrayList; import java.util.List; public class TestSymbolFactory extends SymbolFactory { private List<ICreateSymbolListener> listeners = new ArrayList<>(); public TestSymbolFactory( IScopeHelper theScopeHelper, IModifierHelper theModifierHelper, ITypeHelper theTypeHelper) { super(theScopeHelper, theModifierHelper, theTypeHelper); } //TODO rstoll TINS-161 inference OOP // @Override // public IInterfaceTypeSymbol createInterfaceTypeSymbol(ITSPHPAst modifier, ITSPHPAst identifier, // IScope currentScope) { // IInterfaceTypeSymbol symbol = super.createInterfaceTypeSymbol(modifier, identifier, currentScope); // updateListener(symbol); // return symbol; // } // // @Override // public IClassTypeSymbol createClassTypeSymbol(ITSPHPAst classModifierAst, ITSPHPAst identifier, // IScope currentScope) { // IClassTypeSymbol symbol = super.createClassTypeSymbol(classModifierAst, identifier, currentScope); // updateListener(symbol); // return symbol; // } @Override public IMethodSymbol createMethodSymbol(ITSPHPAst methodModifier, ITSPHPAst returnTypeModifier, ITSPHPAst identifier, IScope currentScope) { IMethodSymbol symbol = super.createMethodSymbol(methodModifier, returnTypeModifier, identifier, currentScope); updateListener(symbol); return symbol; } @Override public IVariableSymbol createVariableSymbol(ITSPHPAst typeModifierAst, ITSPHPAst variableId) { IVariableSymbol symbol = super.createVariableSymbol(typeModifierAst, variableId); updateListener(symbol); return symbol; } public void registerListener(ICreateSymbolListener listener) { listeners.add(listener); } private void updateListener(ISymbol symbol) { for (ICreateSymbolListener listener : listeners) { listener.setNewlyCreatedSymbol(symbol); } } }
3e15bfaedb7db8984354956e5821419949948d69
631
java
Java
src/main/java/de/ropemc/api/wrapper/net/minecraft/entity/item/EntityTNTPrimed.java
RopeMC/RopeMC
b464fb9a67e410355a6a498f2d6a2d3b0d022b3d
[ "MIT" ]
8
2017-10-01T17:32:54.000Z
2022-02-12T17:14:19.000Z
src/main/java/de/ropemc/api/wrapper/net/minecraft/entity/item/EntityTNTPrimed.java
RopeMC/RopeMC
b464fb9a67e410355a6a498f2d6a2d3b0d022b3d
[ "MIT" ]
null
null
null
src/main/java/de/ropemc/api/wrapper/net/minecraft/entity/item/EntityTNTPrimed.java
RopeMC/RopeMC
b464fb9a67e410355a6a498f2d6a2d3b0d022b3d
[ "MIT" ]
1
2020-03-09T13:57:29.000Z
2020-03-09T13:57:29.000Z
21.758621
67
0.763867
9,235
package de.ropemc.api.wrapper.net.minecraft.entity.item; import de.ropemc.api.wrapper.net.minecraft.entity.EntityLivingBase; import de.ropemc.api.wrapper.net.minecraft.nbt.NBTTagCompound; import de.ropemc.api.wrapper.WrappedClass; @WrappedClass("net.minecraft.entity.item.EntityTNTPrimed") public interface EntityTNTPrimed { boolean canBeCollidedWith(); boolean canTriggerWalking(); void entityInit(); void explode(); float getEyeHeight(); EntityLivingBase getTntPlacedBy(); void onUpdate(); void readEntityFromNBT(NBTTagCompound var0); void writeEntityToNBT(NBTTagCompound var0); }
3e15bfbec6ae1a3fb980c7607edcc908ccb080ac
661
java
Java
2021/04/15/125ValidPalindrome/Solution.java
PseudoCowboy/lose-love-algorithm
82aefb31956239d6b890ec81fac844beff7174c0
[ "MIT" ]
2
2021-04-14T18:37:54.000Z
2021-04-15T09:13:01.000Z
2021/04/15/125ValidPalindrome/Solution.java
PseudoCowboy/lose-love-algorithm
82aefb31956239d6b890ec81fac844beff7174c0
[ "MIT" ]
20
2021-04-07T07:56:15.000Z
2021-05-05T10:37:16.000Z
2021/04/15/125ValidPalindrome/Solution.java
PseudoCowboy/streak-algorithm
82aefb31956239d6b890ec81fac844beff7174c0
[ "MIT" ]
null
null
null
22.793103
97
0.515885
9,236
public class Solution { public boolean isPalindrome(String s) { int start = 0; int end = s.length() - 1; while (start < end) { if (isChar(s.charAt(start)) && isChar(s.charAt(end))) { if (Character.toLowerCase(s.charAt(start++)) != Character.toLowerCase(s.charAt(end--))) { return false; } } else { if (!isChar(s.charAt(start))) { start++; } if (!isChar(s.charAt(end))) { end--; } } } return true; } private boolean isChar(char c) { if (Character.isLetter(c) || Character.isDigit(c)) { return true; } return false; } }
3e15c0bd25c448fc0663abf176acdc3db4e7204e
24,346
java
Java
app/src/main/java/com/bin/david/smarttable/GridModeActivity.java
jyjung5759/smartTable
bef5510047ab9efd39242234eb85e93539589af6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bin/david/smarttable/GridModeActivity.java
jyjung5759/smartTable
bef5510047ab9efd39242234eb85e93539589af6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/bin/david/smarttable/GridModeActivity.java
jyjung5759/smartTable
bef5510047ab9efd39242234eb85e93539589af6
[ "Apache-2.0" ]
null
null
null
40.78057
141
0.586708
9,237
package com.bin.david.smarttable; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.os.Bundle; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Toast; import com.bin.david.form.core.SmartTable; import com.bin.david.form.core.TableConfig; import com.bin.david.form.data.CellInfo; import com.bin.david.form.data.column.Column; import com.bin.david.form.data.column.ColumnInfo; import com.bin.david.form.data.format.IFormat; import com.bin.david.form.data.format.bg.BaseBackgroundFormat; import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat; import com.bin.david.form.data.format.bg.ICellBackgroundFormat; import com.bin.david.form.data.format.count.ICountFormat; import com.bin.david.form.data.format.draw.BitmapDrawFormat; import com.bin.david.form.data.format.draw.ImageResDrawFormat; import com.bin.david.form.data.format.draw.MultiLineDrawFormat; import com.bin.david.form.data.format.draw.TextImageDrawFormat; import com.bin.david.form.data.format.grid.BaseAbstractGridFormat; import com.bin.david.form.data.format.grid.BaseGridFormat; import com.bin.david.form.data.format.tip.MultiLineBubbleTip; import com.bin.david.form.data.format.title.TitleImageDrawFormat; import com.bin.david.form.data.style.FontStyle; import com.bin.david.form.data.table.TableData; import com.bin.david.form.listener.OnColumnClickListener; import com.bin.david.form.listener.OnColumnItemClickListener; import com.bin.david.form.utils.DensityUtils; import com.bin.david.smarttable.bean.ChildData; import com.bin.david.smarttable.bean.TableStyle; import com.bin.david.smarttable.bean.TanBean; import com.bin.david.smarttable.bean.UserInfo; import com.bin.david.smarttable.view.BaseCheckDialog; import com.bin.david.smarttable.view.BaseDialog; import com.bin.david.smarttable.view.QuickChartDialog; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; import com.daivd.chart.component.axis.BaseAxis; import com.daivd.chart.component.base.IAxis; import com.daivd.chart.component.base.IComponent; import com.daivd.chart.core.LineChart; import com.daivd.chart.data.ChartData; import com.daivd.chart.data.LineData; import com.daivd.chart.data.style.PointStyle; import com.daivd.chart.provider.component.cross.VerticalCross; import com.daivd.chart.provider.component.level.LevelLine; import com.daivd.chart.provider.component.mark.BubbleMarkView; import com.daivd.chart.provider.component.point.Point; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import static com.bumptech.glide.request.RequestOptions.bitmapTransform; public class GridModeActivity extends AppCompatActivity implements View.OnClickListener{ private SmartTable<UserInfo> table; private BaseCheckDialog<TableStyle> chartDialog; private QuickChartDialog quickChartDialog; private Map<String,Bitmap> map = new HashMap<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_table); quickChartDialog = new QuickChartDialog(); FontStyle.setDefaultTextSize(DensityUtils.sp2px(this,15)); //设置全局字体大小 table = (SmartTable<UserInfo>) findViewById(R.id.table); final List<UserInfo> testData = new ArrayList<>(); Random random = new Random(); List<TanBean> tanBeans = TanBean.initDatas(); //测试 从其他地方获取url int urlSize = tanBeans.size(); for(int i = 0;i <100; i++) { UserInfo userData = new UserInfo("用户\n"+i+"\nceh", random.nextInt(70), System.currentTimeMillis() - random.nextInt(70)*3600*1000*24,true,new ChildData("测试"+i)); userData.setUrl(tanBeans.get(i%urlSize).getUrl()); testData.add(userData); } final Column<String> nameColumn = new Column<>("姓名", "name"); nameColumn.setAutoCount(true); final Column<Integer> ageColumn = new Column<>("年龄", "age",new MultiLineDrawFormat<Integer>(100)); ageColumn.setFixed(true); ageColumn.setAutoCount(true); int imgSize = DensityUtils.dp2px(this,25); final Column<String> avatarColumn = new Column<>("头像", "url", new BitmapDrawFormat<String>(imgSize,imgSize) { @Override protected Bitmap getBitmap(final String s, String value, int position) { if(map.get(s)== null) { Glide.with(GridModeActivity.this).asBitmap().load(s) .apply(bitmapTransform(new CenterCrop())).into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) { map.put(s, bitmap); table.invalidate(); } }); } return map.get(s); } }); avatarColumn.setFixed(true); Column < String > column4 = new Column<>("测试多重查询", "childData.child"); column4.setAutoCount(true); final IFormat<Long> format = new IFormat<Long>() { @Override public String format(Long aLong) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(aLong); return calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH); } }; final Column<Long> timeColumn = new Column<>("时间", "time",format); timeColumn.setCountFormat(new ICountFormat<Long, Long>() { private long maxTime; @Override public void count(Long aLong) { if(aLong > maxTime){ maxTime = aLong; } } @Override public Long getCount() { return maxTime; } @Override public String getCountString() { return format.format(maxTime); } @Override public void clearCount() { maxTime =0; } }); int size = DensityUtils.dp2px(this,15); Column<Boolean> column5 = new Column<>("勾选1", "isCheck", new ImageResDrawFormat<Boolean>(size,size) { @Override protected Context getContext() { return GridModeActivity.this; } @Override protected int getResourceID(Boolean isCheck, String value, int position) { if(isCheck){ return R.mipmap.check; } return 0; } }); Column<Boolean> column6 = new Column<>("勾选2", "isCheck", new TextImageDrawFormat<Boolean>(size,size, TextImageDrawFormat.LEFT,10) { @Override protected Context getContext() { return GridModeActivity.this; } @Override protected int getResourceID(Boolean isCheck, String value, int position) { if(isCheck){ return R.mipmap.clock_fill; } return 0; } }); Column<Boolean> column7 = new Column<>("勾选3", "isCheck", new TextImageDrawFormat<Boolean>(size,size, TextImageDrawFormat.RIGHT,10) { @Override protected Context getContext() { return GridModeActivity.this; } @Override protected int getResourceID(Boolean isCheck, String value, int position) { if(isCheck){ return R.mipmap.activity_fill; } return 0; } }); Column<Boolean> column8 = new Column<>("勾选4", "isCheck", new TextImageDrawFormat<Boolean>(size,size, TextImageDrawFormat.TOP,10) { @Override protected Context getContext() { return GridModeActivity.this; } @Override protected int getResourceID(Boolean isCheck, String value, int position) { if(isCheck){ return R.mipmap.brush_fill; } return 0; } }); Column<Boolean> column9 = new Column<>("勾选5", "isCheck", new TextImageDrawFormat<Boolean>(size,size, TextImageDrawFormat.BOTTOM,10) { @Override protected Context getContext() { return GridModeActivity.this; } @Override protected int getResourceID(Boolean isCheck, String value, int position) { if(isCheck){ return R.mipmap.collection_fill; } return 0; } }); Column totalColumn1 = new Column("总项1",nameColumn,ageColumn); Column totalColumn2 = new Column("总项2",nameColumn,ageColumn,timeColumn); Column totalColumn = new Column("总项",nameColumn,totalColumn1,totalColumn2,timeColumn); final TableData<UserInfo> tableData = new TableData<>("测试",testData,nameColumn, avatarColumn,column4,column5,column6,column7,column8,column9,totalColumn,totalColumn1,totalColumn2,timeColumn); tableData.setShowCount(true); table.getConfig().setShowTableTitle(true); tableData.setOnItemClickListener(new TableData.OnItemClickListener() { @Override public void onClick(Column column, String value, Object o, int col, int row) { Log.e("smartTable","val"+value); } }); table.getConfig().setColumnTitleBackground(new BaseBackgroundFormat(getResources().getColor(R.color.windows_bg))); table.getConfig().setCountBackground(new BaseBackgroundFormat(getResources().getColor(R.color.windows_bg))); tableData.setTitleDrawFormat(new TitleImageDrawFormat(size,size, TitleImageDrawFormat.RIGHT,10) { @Override protected Context getContext() { return GridModeActivity.this; } @Override protected int getResourceID(Column column) { if(!column.isParent()){ if(tableData.getSortColumn() == column){ setDirection(TextImageDrawFormat.RIGHT); if(column.isReverseSort()){ return R.mipmap.sort_up; } return R.mipmap.sort_down; }else{ setDirection(TextImageDrawFormat.LEFT); if(column == nameColumn){ return R.mipmap.name; }else if(column == ageColumn){ return R.mipmap.age; }else if(column == timeColumn){ return R.mipmap.update; } } return 0; } setDirection(TextImageDrawFormat.LEFT); int level = tableData.getTableInfo().getMaxLevel()-column.getLevel(); if(level ==0){ return R.mipmap.level1; }else if(level ==1){ return R.mipmap.level2; } return 0; } }); ageColumn.setOnColumnItemClickListener(new OnColumnItemClickListener<Integer>() { @Override public void onClick(Column<Integer> column, String value, Integer integer, int position) { Toast.makeText(GridModeActivity.this,"点击了"+value,Toast.LENGTH_SHORT).show(); } }); FontStyle fontStyle = new FontStyle(); fontStyle.setTextColor(getResources().getColor(android.R.color.white)); MultiLineBubbleTip<Column> tip = new MultiLineBubbleTip<Column>(this,R.mipmap.round_rect,R.mipmap.triangle,fontStyle) { @Override public boolean isShowTip(Column column, int position) { if(column == nameColumn){ return true; } return false; } @Override public String[] format(Column column, int position) { UserInfo data = testData.get(position); String[] strings = {"批注","姓名:"+data.getName()}; return strings; } }; tip.setColorFilter(Color.parseColor("#FA8072")); tip.setAlpha(0.8f); table.getProvider().setTip(tip); table.setOnColumnClickListener(new OnColumnClickListener() { @Override public void onClick(ColumnInfo columnInfo) { if(!columnInfo.column.isParent()) { if(columnInfo.column == ageColumn){ showChartDialog(tableData.getTableName(),nameColumn.getDatas(),ageColumn.getDatas()); }else{ table.setSortColumn(columnInfo.column, !columnInfo.column.isReverseSort()); } } Toast.makeText(GridModeActivity.this,"点击了"+columnInfo.column.getColumnName(),Toast.LENGTH_SHORT).show(); } }); table.getConfig().setTableTitleStyle(new FontStyle(this,15,getResources().getColor(R.color.arc1)).setAlign(Paint.Align.CENTER)); ICellBackgroundFormat<CellInfo> backgroundFormat = new BaseCellBackgroundFormat<CellInfo>() { @Override public int getBackGroundColor(CellInfo cellInfo) { if(cellInfo.row %2 == 0) { return ContextCompat.getColor(GridModeActivity.this, R.color.content_bg); } return TableConfig.INVALID_COLOR; } }; table.getConfig().setTableGridFormat(new BaseGridFormat(){ @Override public void drawTableBorderGrid(Canvas canvas, int left, int top, int right, int bottom, Paint paint) { paint.setStrokeWidth(10); paint.setColor(Color.GREEN); canvas.drawRect(left,top,right,bottom,paint); } }); //设置网格 table.getConfig().setContentCellBackgroundFormat(backgroundFormat) .setTableGridFormat(new BaseAbstractGridFormat() { @Override protected boolean isShowVerticalLine(int col, int row, CellInfo cellInfo) { return col%2 ==0; } @Override protected boolean isShowHorizontalLine(int col, int row, CellInfo cellInfo) { return row%2 ==0; } @Override protected boolean isShowColumnTitleVerticalLine(int col, Column column) { return col%2 ==0; } }); table.setTableData(tableData); } @Override public void onClick(View view) { changedStyle(); } private void changedStyle() { if (chartDialog == null) { chartDialog = new BaseCheckDialog<>("表格设置", new BaseCheckDialog.OnCheckChangeListener<TableStyle>() { @Override public String getItemText(TableStyle chartStyle) { return chartStyle.value; } @Override public void onItemClick(TableStyle item, int position) { switch (item) { case FIXED_TITLE: fixedTitle(item); break; case FIXED_X_AXIS: fixedXAxis(item); break; case FIXED_Y_AXIS: fixedYAxis(item); break; case FIXED_FIRST_COLUMN: fixedFirstColumn(item); break; case FIXED_COUNT_ROW: fixedCountRow(item); break; case ZOOM: zoom(item); break; } } }); } ArrayList<TableStyle> items = new ArrayList<>(); items.add(TableStyle.FIXED_X_AXIS); items.add(TableStyle.FIXED_Y_AXIS); items.add(TableStyle.FIXED_TITLE); items.add(TableStyle.FIXED_FIRST_COLUMN); items.add(TableStyle.FIXED_COUNT_ROW); items.add(TableStyle.ZOOM); chartDialog.show(this, true, items); } private void zoom(TableStyle item) { quickChartDialog.showDialog(this, item, new String[]{"缩放", "不缩放"}, new QuickChartDialog.OnCheckChangeAdapter() { @Override public void onItemClick(String s, int position) { if (position == 0) { table.setZoom(true,3,1); } else if (position == 1) { table.setZoom(false,3,1); } table.invalidate(); } }); } private void fixedXAxis(TableStyle c) { quickChartDialog.showDialog(this, c, new String[]{"固定", "不固定"}, new QuickChartDialog.OnCheckChangeAdapter() { @Override public void onItemClick(String s, int position) { if (position == 0) { table.getConfig().setFixedXSequence(true); } else if (position == 1) { table.getConfig().setFixedXSequence(false); } table.invalidate(); } }); } private void fixedYAxis(TableStyle c) { quickChartDialog.showDialog(this, c, new String[]{"固定", "不固定"}, new QuickChartDialog.OnCheckChangeAdapter() { @Override public void onItemClick(String s, int position) { if (position == 0) { table.getConfig().setFixedYSequence(true); } else if (position == 1) { table.getConfig().setFixedYSequence(false); } table.invalidate(); } }); } private void fixedTitle(TableStyle c) { quickChartDialog.showDialog(this, c, new String[]{"固定", "不固定"}, new QuickChartDialog.OnCheckChangeAdapter() { @Override public void onItemClick(String s, int position) { if (position == 0) { table.getConfig().setFixedTitle(true); } else if (position == 1) { table.getConfig().setFixedTitle(false); } table.invalidate(); } }); } private void fixedFirstColumn(TableStyle c) { quickChartDialog.showDialog(this, c, new String[]{"固定", "不固定"}, new QuickChartDialog.OnCheckChangeAdapter() { @Override public void onItemClick(String s, int position) { if (position == 0) { table.getConfig().setFixedFirstColumn(true); } else if (position == 1) { table.getConfig().setFixedFirstColumn(false); } table.invalidate(); } }); } private void fixedCountRow(TableStyle c) { quickChartDialog.showDialog(this, c, new String[]{"固定", "不固定"}, new QuickChartDialog.OnCheckChangeAdapter() { @Override public void onItemClick(String s, int position) { if (position == 0) { table.getConfig().setFixedCountRow(true); } else if (position == 1) { table.getConfig().setFixedCountRow(false); } table.invalidate(); } }); } /** * 测试是否可以兼容之前smartChart * @param tableName * @param chartYDataList * @param list */ private void showChartDialog(String tableName,List<String> chartYDataList,List<Integer> list ){ View chartView = View.inflate(this,R.layout.dialog_chart,null); LineChart lineChart = (LineChart) chartView.findViewById(R.id.lineChart); lineChart.setLineModel(LineChart.CURVE_MODEL); Resources res = getResources(); com.daivd.chart.data.style.FontStyle.setDefaultTextSpSize(this,12); List<LineData> ColumnDatas = new ArrayList<>(); ArrayList<Double> tempList1 = new ArrayList<>(); ArrayList<String> ydataList = new ArrayList<>(); for(int i = 0;i <30;i++){ String value = chartYDataList.get(i); ydataList.add(value); } for(int i = 0;i <30;i++){ int value = list.get(i); tempList1.add(Double.valueOf(value)); } LineData columnData1 = new LineData(tableName,"", IAxis.AxisDirection.LEFT,getResources().getColor(R.color.arc1),tempList1); ColumnDatas.add(columnData1); ChartData<LineData> chartData2 = new ChartData<>("Area Chart",ydataList,ColumnDatas); lineChart.getChartTitle().setDirection(IComponent.TOP); lineChart.getLegend().setDirection(IComponent.BOTTOM); lineChart.setLineModel(LineChart.CURVE_MODEL); BaseAxis verticalAxis = lineChart.getLeftVerticalAxis(); BaseAxis horizontalAxis= lineChart.getHorizontalAxis(); //设置竖轴方向 verticalAxis.setAxisDirection(IAxis.AxisDirection.LEFT); //设置网格 verticalAxis.setDrawGrid(true); //设置横轴方向 horizontalAxis.setAxisDirection(IAxis.AxisDirection.BOTTOM); horizontalAxis.setDrawGrid(true); //设置线条样式 verticalAxis.getAxisStyle().setWidth(this,1); DashPathEffect effects = new DashPathEffect(new float[] { 1, 2, 4, 8}, 1); verticalAxis.getGridStyle().setWidth(this,1).setColor(res.getColor(R.color.arc_text)).setEffect(effects); horizontalAxis.getGridStyle().setWidth(this,1).setColor(res.getColor(R.color.arc_text)).setEffect(effects); lineChart.setZoom(true); //开启十字架 lineChart.getProvider().setOpenCross(true); lineChart.getProvider().setCross(new VerticalCross()); lineChart.getProvider().setShowText(true); //开启MarkView lineChart.getProvider().setOpenMark(true); //设置MarkView lineChart.getProvider().setMarkView(new BubbleMarkView(this)); //设置显示标题 lineChart.setShowChartName(true); //设置标题样式 com.daivd.chart.data.style.FontStyle fontStyle = lineChart.getChartTitle().getFontStyle(); fontStyle.setTextColor(res.getColor(R.color.arc_temp)); fontStyle.setTextSpSize(this,15); LevelLine levelLine = new LevelLine(30); DashPathEffect effects2 = new DashPathEffect(new float[] { 1, 2,2,4}, 1); levelLine.getLineStyle().setWidth(this,1).setColor(res.getColor(R.color.arc23)).setEffect(effects); levelLine.getLineStyle().setEffect(effects2); lineChart.getProvider().addLevelLine(levelLine); Point legendPoint = (Point) lineChart.getLegend().getPoint(); PointStyle style = legendPoint.getPointStyle(); style.setShape(PointStyle.SQUARE); lineChart.getProvider().setArea(true); lineChart.getHorizontalAxis().setRotateAngle(90); lineChart.setChartData(chartData2); lineChart.startChartAnim(400); BaseDialog dialog = new BaseDialog.Builder(this).setFillWidth(true).setContentView(chartView).create(); dialog.show(); } @Override protected void onDestroy() { super.onDestroy(); chartDialog = null; quickChartDialog = null; } }