hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
86ae55991d117fffc02766f5120406edc6d6cd4c
1,751
/* * Copyright 2019 Jonathan West * * 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.zhapi; import java.util.Date; /** * Contains status from the ZenHub API on how close are we to exhausting our * requests under the ZenHub rate limit. */ public class RateLimitStatus { private final int rateLimit_limit; private final int rateLimit_used; private final Date rateLimit_reset; public RateLimitStatus(int rateLimit_limit, int rateLimit_used, long rateLimit_reset) { this.rateLimit_limit = rateLimit_limit; this.rateLimit_used = rateLimit_used; this.rateLimit_reset = new Date(rateLimit_reset * 1000); // convert from epoch seconds to epoch msecs } public int getRateLimit_limit() { return rateLimit_limit; } public int getRateLimit_used() { return rateLimit_used; } public Date getRateLimit_reset() { return rateLimit_reset; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("rateLimit_limit: "); sb.append(rateLimit_limit); sb.append(" rateLimit_used: "); sb.append(rateLimit_used); sb.append(" rateLimit_reset: "); sb.append(rateLimit_reset); return sb.toString(); } }
27.793651
104
0.717304
8a633bebc10b2962026e09e7ef2361072de7beef
1,957
package com.netcracker.ncstore.service.data.order; import com.netcracker.ncstore.dto.OrderGetDTO; import com.netcracker.ncstore.dto.OrderGetPageDTO; import com.netcracker.ncstore.dto.UserIdProductIdDTO; import com.netcracker.ncstore.exception.OrderServiceNotFoundException; import com.netcracker.ncstore.exception.OrderServicePermissionException; import com.netcracker.ncstore.model.Order; import com.netcracker.ncstore.repository.OrderRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import java.util.UUID; @Service @Slf4j public class OrderDataService implements IOrderDataService { private final OrderRepository orderRepository; public OrderDataService(final OrderRepository orderRepository) { this.orderRepository = orderRepository; } @Override public Page<Order> getOrdersForUserWithPagination(final OrderGetPageDTO orderGetPageDTO) { return orderRepository.findByUserEmail(orderGetPageDTO.getEmail(), orderGetPageDTO.getPageable()); } @Override public Order getSpecificOrderForUser(OrderGetDTO orderGetDTO) throws OrderServiceNotFoundException, OrderServicePermissionException { UUID orderId = orderGetDTO.getOrderId(); Order order = orderRepository. findById(orderId).orElseThrow( () -> new OrderServiceNotFoundException("Requested order does not exist. ") ); if (order.getUser().getEmail().equals(orderGetDTO.getEmail())) { return order; } else { throw new OrderServicePermissionException("Requested order does not belong to provided user. "); } } @Override public boolean isUserOrderedProduct(final UserIdProductIdDTO userIdProductIdDTO) { return orderRepository.existsProductForUser(userIdProductIdDTO.getUserEmail(), userIdProductIdDTO.getProductId()); } }
39.14
137
0.758304
c1d3265c6b026a1fd9fb5c1e763b93575beb4bf7
364
package com.gmail.stefvanschiedev.buildinggame.utils.arena; /** * Represents the modes an arena can be in * * @since 2.1.0 */ public enum ArenaMode { /** * Represents a free for all match; only one person a plot * * @since 2.1.0 */ SOLO, /** * Represents a team match; with as many people as you want */ TEAM }
16.545455
63
0.593407
3e2b26fea08d193e8a772eeae8292e22a6e965db
383
package com.airbnb.lottie.parser; import com.airbnb.lottie.parser.moshi.JsonReader; public class FloatParser implements ValueParser<Float> { public static final FloatParser INSTANCE = new FloatParser(); private FloatParser() { } public Float parse(JsonReader jsonReader, float f) { return Float.valueOf(JsonUtils.valueFromObject(jsonReader) * f); } }
25.533333
72
0.733681
636dbe1a02d7654f110bebf5995117b5d1ddf2cf
318
package masterofgalaxy; import java.util.Random; public class RandomUtil { public static float nextFloat(Random random, float min, float max) { return min + (random.nextFloat() * (max - min)); } public static int nextSign(Random random) { return random.nextInt(1) == 1 ? 1 : -1; } }
22.714286
72
0.641509
07eb687f9df47713b41528c02ae1dc30ddad47a2
1,959
/** * */ package com.soartech.simjr.ui.actions; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import com.soartech.simjr.ui.SimulationMainFrame; /** * @author aron * */ public class LoadKmlFileAction extends AbstractSimulationAction { private static final long serialVersionUID = 8899798502611162716L; public LoadKmlFileAction(ActionManager actionManager) { super(actionManager, "Load KML file ..."); } /* (non-Javadoc) * @see com.soartech.simjr.ui.actions.AbstractSimulationAction#update() */ @Override public void update() { } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent arg0) { SimulationMainFrame frame = findService(SimulationMainFrame.class); if(frame == null) { return; } File cd = new File(System.getProperty("user.dir")); JFileChooser chooser = new JFileChooser(cd); chooser.addChoosableFileFilter(new FileFilter() { @Override public boolean accept(File f) { return !f.getName().startsWith(".") && (f.isDirectory() || f.getName().endsWith(".kml")); } @Override public String getDescription() { return "Google Earth KML files (*.kml)"; }}); if(chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION) { return; } // TODO: This action was never finished. Whatever we do here should // probably also be done for the OSM importer. //File file = chooser.getSelectedFile(); // frame.loadDockingLayoutFromFile(file.getAbsolutePath()); } }
25.441558
85
0.598775
740dd27329f7abd477b19649cf322c5b339a5b9e
4,024
package com.kristurek.polskatv.service.impl; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.kristurek.polskatv.service.PreferencesService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class PolskaTvPreferencesService implements PreferencesService { private SharedPreferences prefs; public PolskaTvPreferencesService(Context context) { this.prefs = PreferenceManager.getDefaultSharedPreferences(context); } @Override public void save(KEYS key, String value) { final SharedPreferences.Editor editor = prefs.edit(); editor.putString(key.getValue(), value); editor.apply(); } @Override public void save(KEYS key, boolean value) { final SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(key.getValue(), value); editor.apply(); } @Override public void save(KEYS key, int value) { final SharedPreferences.Editor editor = prefs.edit(); editor.putInt(key.getValue(), value); editor.apply(); } @Override public void save(KEYS key, float value) { final SharedPreferences.Editor editor = prefs.edit(); editor.putFloat(key.getValue(), value); editor.apply(); } @Override public void save(KEYS key, LinkedHashMap<String, String> value) { try { JSONArray arr = new JSONArray(); for (String index : value.keySet()) { JSONObject json = new JSONObject(); json.put("id", index); json.put("name", value.get(index)); arr.put(json); } final SharedPreferences.Editor editor = prefs.edit(); editor.putString(key.getValue(), arr.toString()); editor.apply(); } catch (JSONException e) { throw new RuntimeException(e.getMessage()); } } @Override public void save(KEYS key, HashSet<String> value) { final SharedPreferences.Editor editor = prefs.edit(); editor.putStringSet(key.getValue(), value); editor.apply(); } @Override public void clear(KEYS key) { final SharedPreferences.Editor editor = prefs.edit(); editor.remove(key.getValue()); editor.apply(); } @Override public boolean contains(KEYS key) { return prefs.contains(key.getValue()); } @Override public String get(KEYS key, String defaultValue) { return prefs.getString(key.getValue(), defaultValue); } @Override public boolean get(KEYS key, boolean defaultValue) { return prefs.getBoolean(key.getValue(), defaultValue); } @Override public int get(KEYS key, int defaultValue) { return prefs.getInt(key.getValue(), defaultValue); } @Override public float get(KEYS key, float defaultValue) { return prefs.getFloat(key.getValue(), defaultValue); } @Override public Map<String, String> get(KEYS key, LinkedHashMap<String, String> defaultValue) { try { String data = prefs.getString(key.getValue(), null); if (data == null) return defaultValue; LinkedHashMap<String, String> map = new LinkedHashMap<>(); JSONArray arr = new JSONArray(data); for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); map.put(json.getString("id"), json.getString("name")); } return map; } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } @Override public Set<String> get(KEYS key, HashSet<String> defaultValue) { return prefs.getStringSet(key.getValue(), defaultValue); } }
28.13986
90
0.622018
f3e51aea3cb964c0c83650b48dfad170f181ebdd
4,404
package net.minecraft.command.arguments; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import java.util.Arrays; import java.util.Collection; import net.minecraft.advancements.Advancement; import net.minecraft.command.CommandSource; import net.minecraft.entity.ai.attributes.Attribute; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.RecipeManager; import net.minecraft.loot.LootPredicateManager; import net.minecraft.loot.conditions.ILootCondition; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.TranslationTextComponent; public class ResourceLocationArgument implements ArgumentType<ResourceLocation> { private static final Collection<String> EXAMPLES = Arrays.asList("foo", "foo:bar", "012"); private static final DynamicCommandExceptionType ERROR_UNKNOWN_ADVANCEMENT = new DynamicCommandExceptionType((p_208676_0_) -> { return new TranslationTextComponent("advancement.advancementNotFound", p_208676_0_); }); private static final DynamicCommandExceptionType ERROR_UNKNOWN_RECIPE = new DynamicCommandExceptionType((p_208677_0_) -> { return new TranslationTextComponent("recipe.notFound", p_208677_0_); }); private static final DynamicCommandExceptionType ERROR_UNKNOWN_PREDICATE = new DynamicCommandExceptionType((p_208674_0_) -> { return new TranslationTextComponent("predicate.unknown", p_208674_0_); }); private static final DynamicCommandExceptionType ERROR_UNKNOWN_ATTRIBUTE = new DynamicCommandExceptionType((p_239091_0_) -> { return new TranslationTextComponent("attribute.unknown", p_239091_0_); }); public static ResourceLocationArgument id() { return new ResourceLocationArgument(); } public static Advancement getAdvancement(CommandContext<CommandSource> p_197198_0_, String p_197198_1_) throws CommandSyntaxException { ResourceLocation resourcelocation = p_197198_0_.getArgument(p_197198_1_, ResourceLocation.class); Advancement advancement = p_197198_0_.getSource().getServer().getAdvancements().getAdvancement(resourcelocation); if (advancement == null) { throw ERROR_UNKNOWN_ADVANCEMENT.create(resourcelocation); } else { return advancement; } } public static IRecipe<?> getRecipe(CommandContext<CommandSource> p_197194_0_, String p_197194_1_) throws CommandSyntaxException { RecipeManager recipemanager = p_197194_0_.getSource().getServer().getRecipeManager(); ResourceLocation resourcelocation = p_197194_0_.getArgument(p_197194_1_, ResourceLocation.class); return recipemanager.byKey(resourcelocation).orElseThrow(() -> { return ERROR_UNKNOWN_RECIPE.create(resourcelocation); }); } public static ILootCondition getPredicate(CommandContext<CommandSource> p_228259_0_, String p_228259_1_) throws CommandSyntaxException { ResourceLocation resourcelocation = p_228259_0_.getArgument(p_228259_1_, ResourceLocation.class); LootPredicateManager lootpredicatemanager = p_228259_0_.getSource().getServer().getPredicateManager(); ILootCondition ilootcondition = lootpredicatemanager.get(resourcelocation); if (ilootcondition == null) { throw ERROR_UNKNOWN_PREDICATE.create(resourcelocation); } else { return ilootcondition; } } public static Attribute getAttribute(CommandContext<CommandSource> p_239094_0_, String p_239094_1_) throws CommandSyntaxException { ResourceLocation resourcelocation = p_239094_0_.getArgument(p_239094_1_, ResourceLocation.class); return Registry.ATTRIBUTE.getOptional(resourcelocation).orElseThrow(() -> { return ERROR_UNKNOWN_ATTRIBUTE.create(resourcelocation); }); } public static ResourceLocation getId(CommandContext<CommandSource> p_197195_0_, String p_197195_1_) { return p_197195_0_.getArgument(p_197195_1_, ResourceLocation.class); } public ResourceLocation parse(StringReader p_parse_1_) throws CommandSyntaxException { return ResourceLocation.read(p_parse_1_); } public Collection<String> getExamples() { return EXAMPLES; } }
50.045455
139
0.788828
1b0b170e7a6c9d693826ef8ce07585908d71764b
332
package net.unit8.waitt.server.tomcat7; import org.apache.catalina.loader.WebappClassLoader; /** * */ public class Tomcat7WebappClassLoaderWrapper extends WebappClassLoader { public Tomcat7WebappClassLoaderWrapper(ClassLoader parent) { super(ClassLoaderFactoryHolder.getClassLoaderFactory().create(parent)); } }
25.538462
79
0.786145
490acac1216e8fcf4cafcf2a52a987974855548d
693
package ca.mimic.oauth2library; class Constants { public static final String GRANT_TYPE_REFRESH = "refresh_token"; public static final String GRANT_TYPE_PASSWORD = "password"; public static final String POST_GRANT_TYPE = "grant_type"; public static final String POST_USERNAME = "username"; public static final String POST_PASSWORD = "password"; public static final String POST_CLIENT_ID = "client_id"; public static final String POST_CLIENT_SECRET = "client_secret"; public static final String POST_SCOPE = "scope"; public static final String POST_REFRESH_TOKEN = "refresh_token"; public static final String HEADER_AUTHORIZATION = "Authorization"; }
40.764706
70
0.763348
477133e0f834cd260b2f8a8668d3a00130f5ce76
2,974
package com.springboot.hotelbookingsystem.models; public class OrderModel { private String checkin; private String checkout; private String cardNumber; private String expireDate; private String cvv; private double totalPrice; private Long roomId; private Long userId; private String address; private String city; private String province; private String postcode; private String country; private String roomunit; private String roomdescription; private String roomType; public String getCheckin() { return checkin; } public void setCheckin(String checkin) { this.checkin = checkin; } public String getCheckout() { return checkout; } public void setCheckout(String checkout) { this.checkout = checkout; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getExpireDate() { return expireDate; } public void setExpireDate(String expireDate) { this.expireDate = expireDate; } public String getCvv() { return cvv; } public void setCvv(String cvv) { this.cvv = cvv; } public Long getRoomId() { return roomId; } public void setRoomId(Long roomId) { this.roomId = roomId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getRoomunit() { return roomunit; } public void setRoomunit(String roomunit) { this.roomunit = roomunit; } public String getRoomdescription() { return roomdescription; } public void setRoomdescription(String roomdescription) { this.roomdescription = roomdescription; } public String getRoomType() { return roomType; } public void setRoomType(String roomType) { this.roomType = roomType; } }
19.959732
60
0.618695
dedc2dfa77f35657f93aab36e8619c25d1090aa3
874
package io.codebyexample.springbootrabbitmq.dataprovider; import io.codebyexample.springbootrabbitmq.configuration.RabbitConfiguration; import io.codebyexample.springbootrabbitmq.core.entities.Greeting; import io.codebyexample.springbootrabbitmq.util.GsonUtils; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author huypva */ @Component public class GreetingRabbitProducerImpl implements GreetingRabbitProducer { @Autowired RabbitConfiguration rabbitConfiguration; @Autowired RabbitTemplate rabbitTemplate; @Override public void sendGreeting(Greeting greeting) { rabbitTemplate.convertAndSend( rabbitConfiguration.exchangeName, rabbitConfiguration.routingKey, GsonUtils.toJson(greeting)); } }
29.133333
77
0.818078
59f8b5ac54f6707a9dac3b835fe866a8421eb78f
238
package ua.es.transit.kafka; import org.springframework.cloud.stream.annotation.Input; import org.springframework.messaging.SubscribableChannel; public interface IBrokerChannel { @Input("delay") SubscribableChannel inbound(); }
23.8
57
0.798319
f7032dd41d1f74bf959146425fd07def54f1317f
17,655
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.integtests; import org.gradle.integtests.fixtures.AbstractIntegrationTest; import org.gradle.integtests.fixtures.executer.ExecutionFailure; import org.gradle.integtests.fixtures.executer.ExecutionResult; import org.gradle.test.fixtures.file.TestFile; import org.junit.Test; import java.io.File; import static org.hamcrest.Matchers.startsWith; public class ProjectLoadingIntegrationTest extends AbstractIntegrationTest { @Test public void handlesSimilarlyNamedBuildFilesInSameDirectory() { TestFile buildFile1 = testFile("similarly-named build.gradle").write("task build"); TestFile buildFile2 = testFile("similarly_named_build_gradle").write("task 'other-build'"); usingBuildFile(buildFile1).withTasks("build").run(); usingBuildFile(buildFile2).withTasks("other-build").run(); usingBuildFile(buildFile1).withTasks("build").run(); } @Test public void handlesWhitespaceOnlySettingsAndBuildFiles() { testFile("settings.gradle").write(" \n "); testFile("build.gradle").write(" "); inTestDirectory().withTaskList().run(); } @Test public void canDetermineRootProjectAndDefaultProjectBasedOnCurrentDirectory() { File rootDir = getTestDirectory(); File childDir = new File(rootDir, "child"); testFile("settings.gradle").write("include('child')"); testFile("build.gradle").write("task('do-stuff')"); testFile("child/build.gradle").write("task('do-stuff')"); inDirectory(rootDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":do-stuff", ":child:do-stuff"); inDirectory(rootDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); inDirectory(childDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":child:do-stuff"); inDirectory(childDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); } @Test public void canDetermineRootProjectAndDefaultProjectBasedOnProjectDirectory() { File rootDir = getTestDirectory(); File childDir = new File(rootDir, "child"); testFile("settings.gradle").write("include('child')"); testFile("build.gradle").write("task('do-stuff')"); testFile("child/build.gradle").write("task('do-stuff')"); usingProjectDir(rootDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":do-stuff", ":child:do-stuff"); usingProjectDir(rootDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); usingProjectDir(childDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":child:do-stuff"); usingProjectDir(childDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); } @Test public void canDetermineRootProjectAndDefaultProjectBasedOnBuildFile() { testFile("settings.gradle").write("include('child')"); TestFile rootBuildFile = testFile("build.gradle"); rootBuildFile.write("task('do-stuff')"); TestFile childBuildFile = testFile("child/build.gradle"); childBuildFile.write("task('do-stuff')"); usingBuildFile(rootBuildFile).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":do-stuff", ":child:do-stuff"); usingBuildFile(rootBuildFile).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); usingBuildFile(childBuildFile).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":child:do-stuff"); usingBuildFile(childBuildFile).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); } @Test public void buildFailsWhenMultipleProjectsMeetDefaultProjectCriteria() { testFile("settings.gradle").writelns( "include 'child'", "project(':child').projectDir = rootProject.projectDir"); testFile("build.gradle").write("// empty"); ExecutionFailure result = inTestDirectory().withTasks("test").runWithFailure(); result.assertThatDescription(startsWith("Multiple projects in this build have project directory")); result = usingProjectDir(getTestDirectory()).withTasks("test").runWithFailure(); result.assertThatDescription(startsWith("Multiple projects in this build have project directory")); result = usingBuildFile(testFile("build.gradle")).withTasks("test").runWithFailure(); result.assertThatDescription(startsWith("Multiple projects in this build have build file")); } @Test public void buildFailsWhenSpecifiedBuildFileIsNotAFile() { TestFile file = testFile("unknown"); ExecutionFailure result = usingBuildFile(file).runWithFailure(); result.assertHasDescription("The specified build file '" + file + "' does not exist."); file.createDir(); result = usingBuildFile(file).runWithFailure(); result.assertHasDescription("The specified build file '" + file + "' is not a file."); } @Test public void buildFailsWhenSpecifiedProjectDirectoryIsNotADirectory() { TestFile file = testFile("unknown"); ExecutionFailure result = usingProjectDir(file).runWithFailure(); result.assertHasDescription("The specified project directory '" + file + "' does not exist."); file.createFile(); result = usingProjectDir(file).runWithFailure(); result.assertHasDescription("The specified project directory '" + file + "' is not a directory."); } @Test public void buildFailsWhenSpecifiedSettingsFileIsNotAFile() { TestFile file = testFile("unknown"); ExecutionFailure result = inTestDirectory().usingSettingsFile(file).runWithFailure(); result.assertHasDescription("The specified settings file '" + file + "' does not exist."); file.createDir(); result = inTestDirectory().usingSettingsFile(file).runWithFailure(); result.assertHasDescription("The specified settings file '" + file + "' is not a file."); } @Test public void buildFailsWhenSpecifiedSettingsFileDoesNotContainMatchingProject() { TestFile settingsFile = testFile("settings.gradle"); settingsFile.write("// empty"); TestFile projectDir = testFile("project dir"); TestFile buildFile = projectDir.file("build.gradle").createFile(); ExecutionFailure result = usingProjectDir(projectDir).usingSettingsFile(settingsFile).runWithFailure(); result.assertHasDescription(String.format("No projects in this build have project directory '%s'.", projectDir)); result = usingBuildFile(buildFile).usingSettingsFile(settingsFile).runWithFailure(); result.assertHasDescription(String.format("No projects in this build have build file '%s'.", buildFile)); } @Test public void settingsFileTakesPrecedenceOverBuildFileInSameDirectory() { testFile("settings.gradle").write("rootProject.buildFileName = 'root.gradle'"); testFile("root.gradle").write("task('do-stuff')"); TestFile buildFile = testFile("build.gradle"); buildFile.write("throw new RuntimeException()"); inTestDirectory().withTasks("do-stuff").run(); usingProjectDir(getTestDirectory()).withTasks("do-stuff").run(); } @Test public void settingsFileInParentDirectoryTakesPrecedenceOverBuildFile() { testFile("settings.gradle").writelns( "include 'child'", "project(':child').buildFileName = 'child.gradle'" ); TestFile subDirectory = getTestDirectory().file("child"); subDirectory.file("build.gradle").write("throw new RuntimeException()"); subDirectory.file("child.gradle").write("task('do-stuff')"); inDirectory(subDirectory).withSearchUpwards().withTasks("do-stuff").run(); usingProjectDir(subDirectory).withSearchUpwards().withTasks("do-stuff").run(); } @Test public void explicitBuildFileTakesPrecedenceOverSettingsFileInSameDirectory() { testFile("settings.gradle").write("rootProject.buildFileName = 'root.gradle'"); testFile("root.gradle").write("throw new RuntimeException()"); TestFile buildFile = testFile("build.gradle"); buildFile.write("task('do-stuff')"); usingBuildFile(buildFile).withTasks("do-stuff").run(); } @Test public void ignoresMultiProjectBuildInParentDirectoryWhichDoesNotMeetDefaultProjectCriteria() { testFile("settings.gradle").write("include 'another'"); testFile("gradle.properties").writelns("prop=value2", "otherProp=value"); TestFile subDirectory = getTestDirectory().file("subdirectory"); TestFile buildFile = subDirectory.file("build.gradle"); buildFile.writelns("task('do-stuff') {", "doLast {", "assert prop == 'value'", "assert !project.hasProperty('otherProp')", "}", "}"); testFile("subdirectory/gradle.properties").write("prop=value"); inDirectory(subDirectory).withSearchUpwards().withTasks("do-stuff").expectDeprecationWarning().run(); usingProjectDir(subDirectory).withSearchUpwards().withTasks("do-stuff").expectDeprecationWarning().run(); usingBuildFile(buildFile).withSearchUpwards().withTasks("do-stuff").expectDeprecationWarning().run(); } @Test public void deprecationWarningAppearsWhenNestedBuildHasNoSettingsFile() { testFile("settings.gradle").write("include 'another'"); TestFile subDirectory = getTestDirectory().file("sub"); TestFile subBuildFile = subDirectory.file("sub.gradle").write(""); subDirectory.file("build.gradle").write(""); ExecutionResult result = inDirectory(subDirectory).withSearchUpwards().withTasks("help").expectDeprecationWarning().run(); result.assertOutputContains("Support for nested build without a settings file was deprecated and will be removed in Gradle 5.0. You should create a empty settings file in " + subDirectory.getAbsolutePath()); result = usingBuildFile(subBuildFile).inDirectory(subDirectory).withSearchUpwards().withTasks("help").expectDeprecationWarning().run(); result.assertOutputContains("Support for nested build without a settings file was deprecated and will be removed in Gradle 5.0. You should create a empty settings file in " + subDirectory.getAbsolutePath()); result = usingProjectDir(subDirectory).withSearchUpwards().withTasks("help").expectDeprecationWarning().run(); result.assertOutputContains("Support for nested build without a settings file was deprecated and will be removed in Gradle 5.0. You should create a empty settings file in " + subDirectory.getAbsolutePath()); } @Test public void noDeprecationWarningAppearsWhenUsingRootProject() { testFile("settings.gradle").write("include 'another'"); TestFile subDirectory = getTestDirectory().file("sub"); subDirectory.file("build.gradle").write(""); usingProjectDir(getTestDirectory()).inDirectory(subDirectory).withSearchUpwards().withTasks("help").run(); } @Test public void noDeprecationWarningAppearsWhenSettingsFileIsSpecified() { testFile("settings.gradle").write("include 'another'"); TestFile subDirectory = getTestDirectory().file("sub"); TestFile subSettingsFile = subDirectory.file("renamed_settings.gradle").write(""); subDirectory.file("build.gradle").write(""); inDirectory(subDirectory).usingSettingsFile(subSettingsFile).withSearchUpwards().withTasks("help").run(); } @Test public void noDeprecationWarningAppearsWhenEnclosingBuildUsesAnotherBuildFile() { testFile("settings.gradle").write("include 'another'"); TestFile renamedBuildGradle = getTestDirectory().file("renamed_build.gradle").createFile(); usingBuildFile(renamedBuildGradle).inDirectory(getTestDirectory()).withSearchUpwards().withTasks("help").run(); } @Test public void multiProjectBuildCanHaveMultipleProjectsWithSameProjectDir() { testFile("settings.gradle").writelns( "include 'child1', 'child2'", "project(':child1').projectDir = new File(settingsDir, 'shared')", "project(':child2').projectDir = new File(settingsDir, 'shared')" ); testFile("shared/build.gradle").write("task('do-stuff')"); inTestDirectory().withTasks("do-stuff").run().assertTasksExecuted(":child1:do-stuff", ":child2:do-stuff"); } @Test public void multiProjectBuildCanHaveSeveralProjectsWithSameBuildFile() { testFile("settings.gradle").writelns( "include 'child1', 'child2'", "project(':child1').buildFileName = '../child.gradle'", "project(':child2').buildFileName = '../child.gradle'" ); testFile("child.gradle").write("task('do-stuff')"); inTestDirectory().withTasks("do-stuff").run().assertTasksExecuted(":child1:do-stuff", ":child2:do-stuff"); } @Test public void multiProjectBuildCanHaveSettingsFileAndRootBuildFileInSubDir() { TestFile buildFilesDir = getTestDirectory().file("root"); TestFile settingsFile = buildFilesDir.file("settings.gradle"); settingsFile.writelns( "includeFlat 'child'", "rootProject.projectDir = new File(settingsDir, '..')", "rootProject.buildFileName = 'root/build.gradle'" ); TestFile rootBuildFile = buildFilesDir.file("build.gradle"); rootBuildFile.write("task('do-stuff', dependsOn: ':child:task')"); TestFile childBuildFile = testFile("child/build.gradle"); childBuildFile.writelns("task('do-stuff')", "task('task')"); usingProjectDir(getTestDirectory()).usingSettingsFile(settingsFile).withTasks("do-stuff").run().assertTasksExecuted(":child:task", ":do-stuff", ":child:do-stuff").assertTaskOrder(":child:task", ":do-stuff"); usingBuildFile(rootBuildFile).withTasks("do-stuff").run().assertTasksExecuted(":child:task", ":do-stuff", ":child:do-stuff").assertTaskOrder(":child:task", ":do-stuff"); usingBuildFile(childBuildFile).usingSettingsFile(settingsFile).withTasks("do-stuff").run().assertTasksExecutedInOrder(":child:do-stuff"); } @Test public void multiProjectBuildCanHaveAllProjectsAsChildrenOfSettingsDir() { TestFile settingsFile = testFile("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, 'root')", "include 'sub'", "project(':sub').projectDir = new File(settingsDir, 'root/sub')" ); getTestDirectory().createDir("root").file("build.gradle").writelns("allprojects { task thing }"); inTestDirectory().withTasks(":thing").run().assertTasksExecuted(":thing"); inTestDirectory().withTasks(":sub:thing").run().assertTasksExecuted(":sub:thing"); } @Test public void usesRootProjectAsDefaultProjectWhenInSettingsDir() { TestFile settingsDir = testFile("gradle"); TestFile settingsFile = settingsDir.file("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, '../root')", "include 'sub'", "project(':sub').projectDir = new File(settingsDir, '../root/sub')" ); getTestDirectory().createDir("root").file("build.gradle").writelns("allprojects { task thing }"); inDirectory(settingsDir).withTasks("thing").run().assertTasksExecuted(":thing", ":sub:thing"); } @Test public void rootProjectDirectoryAndBuildFileDoNotHaveToExistWhenInSettingsDir() { TestFile settingsDir = testFile("gradle"); TestFile settingsFile = settingsDir.file("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, '../root')", "include 'sub'", "project(':sub').projectDir = new File(settingsDir, '../sub')" ); getTestDirectory().createDir("sub").file("build.gradle").writelns("task thing"); inDirectory(settingsDir).withTasks("thing").run().assertTasksExecuted(":sub:thing"); } @Test public void settingsFileGetsIgnoredWhenUsingSettingsOnlyDirectoryAsProjectDirectory() { TestFile settingsDir = testFile("gradle"); TestFile settingsFile = settingsDir.file("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, '../root')" ); getTestDirectory().createDir("root").file("build.gradle").writelns("task thing"); inTestDirectory().withArguments("-p", settingsDir.getAbsolutePath()).withTasks("thing").runWithFailure() .assertHasDescription("Task 'thing' not found in root project 'gradle'."); } }
47.205882
215
0.686038
bfa882f95780d503bd431de99671c6664f6648d1
1,309
/******************************************************************************* * Copyright (c) 2013-2017 Contributors to the Eclipse Foundation * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, * Version 2.0 which accompanies this distribution and is available at * http://www.apache.org/licenses/LICENSE-2.0.txt ******************************************************************************/ package mil.nga.giat.geowave.datastore.accumulo.minicluster; import org.apache.accumulo.shell.Shell; public class AccumuloMiniClusterShell { public static void main( final String[] args ) throws Exception { org.apache.log4j.Logger.getRootLogger().setLevel( org.apache.log4j.Level.WARN); final String instanceName = (System.getProperty("instanceName") != null) ? System.getProperty("instanceName") : "geowave"; final String password = (System.getProperty("password") != null) ? System.getProperty("password") : "password"; final String[] shellArgs = new String[] { "-u", "root", "-p", password, "-z", instanceName, "localhost:2181" }; Shell.main(shellArgs); } }
31.926829
113
0.634836
a445d86e4c32fd6482d54e4d21c595e3cd6a92ab
4,208
/** * MIT License * <p> * Copyright (c) 2017-2019 nuls.io * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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 io.nuls.contract.rpc.model; import io.nuls.contract.constant.ContractConstant; import io.nuls.contract.storage.po.TransactionInfoPo; import io.nuls.kernel.model.NulsDigestData; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author: PierreLuo * @date: 2018/7/23 */ @ApiModel(value = "ContractTransactionInfoDtoJSON") public class ContractTransactionInfoDto { private static final String CREATE_INFO = "contract create"; private static final String CALL_INFO = "contract call"; private static final String DELETE_INFO = "contract delete"; private static final String TRANSFER_INFO = "contract transfer"; @ApiModelProperty(name = "hash", value = "交易的hash值") private String txHash; @ApiModelProperty(name = "blockHeight", value = "区块高度") private long blockHeight; @ApiModelProperty(name = "time", value = "交易发起时间") private long time; @ApiModelProperty(name = "txType", value = "交易类型") private int txType; @ApiModelProperty(name = "status", value = "交易状态") private byte status; @ApiModelProperty(name = "info", value = "交易信息") private String info; public ContractTransactionInfoDto() { } public ContractTransactionInfoDto(TransactionInfoPo po) { if(po == null) { return; } this.txHash = po.getTxHash().getDigestHex(); this.blockHeight = po.getBlockHeight(); this.time = po.getTime(); this.txType = po.getTxType(); this.status = po.getStatus(); if(this.txType == ContractConstant.TX_TYPE_CREATE_CONTRACT) { this.info = CREATE_INFO; } else if(this.txType == ContractConstant.TX_TYPE_CALL_CONTRACT) { this.info = CALL_INFO; } else if(this.txType == ContractConstant.TX_TYPE_DELETE_CONTRACT) { this.info = DELETE_INFO; } else if(this.txType == ContractConstant.TX_TYPE_CONTRACT_TRANSFER) { this.info = TRANSFER_INFO; } } public String getTxHash() { return txHash; } public void setTxHash(String txHash) { this.txHash = txHash; } public long getBlockHeight() { return blockHeight; } public void setBlockHeight(long blockHeight) { this.blockHeight = blockHeight; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public int getTxType() { return txType; } public void setTxType(int txType) { this.txType = txType; } public byte getStatus() { return status; } public void setStatus(byte status) { this.status = status; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public int compareTo(long thatTime) { if(this.time > thatTime) { return -1; } else if(this.time < thatTime) { return 1; } return 0; } }
30.273381
81
0.663023
766127b48d4d8307a18f4d8b7de5fc31e4692886
36,383
/** * Copyright (c) 2017 Dell Inc., or its subsidiaries. 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 */ package io.pravega.controller.task.Stream; import com.google.common.annotations.VisibleForTesting; import io.pravega.client.EventStreamClientFactory; import io.pravega.client.stream.EventStreamWriter; import io.pravega.client.stream.EventWriterConfig; import io.pravega.common.Exceptions; import io.pravega.common.concurrent.Futures; import io.pravega.controller.server.SegmentHelper; import io.pravega.controller.server.eventProcessor.ControllerEventProcessorConfig; import io.pravega.controller.server.eventProcessor.ControllerEventProcessors; import io.pravega.controller.server.rpc.auth.AuthHelper; import io.pravega.controller.store.stream.OperationContext; import io.pravega.controller.store.stream.StoreException; import io.pravega.controller.store.stream.StreamMetadataStore; import io.pravega.controller.store.stream.TxnStatus; import io.pravega.controller.store.stream.Version; import io.pravega.controller.store.stream.VersionedTransactionData; import io.pravega.controller.store.stream.records.RecordHelper; import io.pravega.controller.store.stream.records.StreamSegmentRecord; import io.pravega.controller.store.task.TxnResource; import io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus; import io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus.Status; import io.pravega.controller.timeout.TimeoutService; import io.pravega.controller.timeout.TimeoutServiceConfig; import io.pravega.controller.timeout.TimerWheelTimeoutService; import io.pravega.controller.util.Config; import io.pravega.controller.util.RetryHelper; import io.pravega.shared.controller.event.AbortEvent; import io.pravega.shared.controller.event.CommitEvent; import java.time.Duration; import java.util.AbstractMap; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import io.pravega.shared.segment.StreamSegmentNameUtils; import lombok.Getter; import lombok.Synchronized; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import static io.pravega.controller.util.RetryHelper.RETRYABLE_PREDICATE; import static io.pravega.controller.util.RetryHelper.withRetriesAsync; /** * Collection of metadata update tasks on stream. * Task methods are annotated with @Task annotation. * <p> * Any update to the task method signature should be avoided, since it can cause problems during upgrade. * Instead, a new overloaded method may be created with the same task annotation name but a new version. */ @Slf4j public class StreamTransactionMetadataTasks implements AutoCloseable { /** * We derive the maximum execution timeout from the lease time. We assume * a maximum number of renewals for the txn and compute the maximum execution * time by multiplying the lease timeout by the maximum number of renewals. This * multiplier is currently hardcoded because we do not expect applications to change * it. The maximum execution timeout is only a safety mechanism for application that * should rarely be triggered. */ private static final int MAX_EXECUTION_TIME_MULTIPLIER = 1000; protected final String hostId; protected final ScheduledExecutorService executor; private final StreamMetadataStore streamMetadataStore; private final SegmentHelper segmentHelper; private final AuthHelper authHelper; @Getter @VisibleForTesting private final TimeoutService timeoutService; private volatile boolean ready; private final CountDownLatch readyLatch; private final CompletableFuture<EventStreamWriter<CommitEvent>> commitWriterFuture; private final CompletableFuture<EventStreamWriter<AbortEvent>> abortWriterFuture; @VisibleForTesting public StreamTransactionMetadataTasks(final StreamMetadataStore streamMetadataStore, final SegmentHelper segmentHelper, final ScheduledExecutorService executor, final String hostId, final TimeoutServiceConfig timeoutServiceConfig, final BlockingQueue<Optional<Throwable>> taskCompletionQueue, final AuthHelper authHelper) { this.hostId = hostId; this.executor = executor; this.streamMetadataStore = streamMetadataStore; this.segmentHelper = segmentHelper; this.authHelper = authHelper; this.timeoutService = new TimerWheelTimeoutService(this, timeoutServiceConfig, taskCompletionQueue); readyLatch = new CountDownLatch(1); this.commitWriterFuture = new CompletableFuture<>(); this.abortWriterFuture = new CompletableFuture<>(); } public StreamTransactionMetadataTasks(final StreamMetadataStore streamMetadataStore, final SegmentHelper segmentHelper, final ScheduledExecutorService executor, final String hostId, final TimeoutServiceConfig timeoutServiceConfig, final AuthHelper authHelper) { this(streamMetadataStore, segmentHelper, executor, hostId, timeoutServiceConfig, null, authHelper); } public StreamTransactionMetadataTasks(final StreamMetadataStore streamMetadataStore, final SegmentHelper segmentHelper, final ScheduledExecutorService executor, final String hostId, final AuthHelper authHelper) { this(streamMetadataStore, segmentHelper, executor, hostId, TimeoutServiceConfig.defaultConfig(), authHelper); } private void setReady() { ready = true; readyLatch.countDown(); } boolean isReady() { return ready; } @VisibleForTesting public boolean awaitInitialization(long timeout, TimeUnit timeUnit) throws InterruptedException { return readyLatch.await(timeout, timeUnit); } void awaitInitialization() throws InterruptedException { readyLatch.await(); } /** * Initializes stream writers for commit and abort streams. * This method should be called immediately after creating StreamTransactionMetadataTasks object. * * @param clientFactory Client factory reference. * @param config Controller event processor configuration. */ @Synchronized public void initializeStreamWriters(final EventStreamClientFactory clientFactory, final ControllerEventProcessorConfig config) { if (!commitWriterFuture.isDone()) { commitWriterFuture.complete(clientFactory.createEventWriter( config.getCommitStreamName(), ControllerEventProcessors.COMMIT_EVENT_SERIALIZER, EventWriterConfig.builder().build())); } if (!abortWriterFuture.isDone()) { abortWriterFuture.complete(clientFactory.createEventWriter( config.getAbortStreamName(), ControllerEventProcessors.ABORT_EVENT_SERIALIZER, EventWriterConfig.builder().build())); } this.setReady(); } @VisibleForTesting @Synchronized public void initializeStreamWriters(final EventStreamWriter<CommitEvent> commitWriter, final EventStreamWriter<AbortEvent> abortWriter) { this.commitWriterFuture.complete(commitWriter); this.abortWriterFuture.complete(abortWriter); this.setReady(); } /** * Create transaction. * * @param scope stream scope. * @param stream stream name. * @param lease Time for which transaction shall remain open with sending any heartbeat. * the scaling operation is initiated on the txn stream. * @param contextOpt operational context * @return transaction id. */ public CompletableFuture<Pair<VersionedTransactionData, List<StreamSegmentRecord>>> createTxn(final String scope, final String stream, final long lease, final OperationContext contextOpt) { final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt); return createTxnBody(scope, stream, lease, context); } /** * Transaction heartbeat, that increases transaction timeout by lease number of milliseconds. * * @param scope Stream scope. * @param stream Stream name. * @param txId Transaction identifier. * @param lease Amount of time in milliseconds by which to extend the transaction lease. * @param contextOpt operational context * @return Transaction metadata along with the version of it record in the store. */ public CompletableFuture<PingTxnStatus> pingTxn(final String scope, final String stream, final UUID txId, final long lease, final OperationContext contextOpt) { final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt); return pingTxnBody(scope, stream, txId, lease, context); } /** * Abort transaction. * * @param scope stream scope. * @param stream stream name. * @param txId transaction id. * @param version Expected version of the transaction record in the store. * @param contextOpt operational context * @return true/false. */ public CompletableFuture<TxnStatus> abortTxn(final String scope, final String stream, final UUID txId, final Version version, final OperationContext contextOpt) { final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt); return withRetriesAsync(() -> sealTxnBody(hostId, scope, stream, false, txId, version, context), RETRYABLE_PREDICATE, 3, executor); } /** * Commit transaction. * * @param scope stream scope. * @param stream stream name. * @param txId transaction id. * @param contextOpt optional context * @return true/false. */ public CompletableFuture<TxnStatus> commitTxn(final String scope, final String stream, final UUID txId, final OperationContext contextOpt) { final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt); return withRetriesAsync(() -> sealTxnBody(hostId, scope, stream, true, txId, null, context), RETRYABLE_PREDICATE, 3, executor); } /** * Creates txn on the specified stream. * * Post-condition: * 1. If txn creation succeeds, then * (a) txn node is created in the store, * (b) txn segments are successfully created on respective segment stores, * (c) txn is present in the host-txn index of current host, * (d) txn's timeout is being tracked in timeout service. * * 2. If process fails after creating txn node, but before responding to the client, then since txn is * present in the host-txn index, some other controller process shall abort the txn after maxLeaseValue * * 3. If timeout service tracks timeout of specified txn, * then txn is also present in the host-txn index of current process. * * Invariant: * The following invariants are maintained throughout the execution of createTxn, pingTxn and sealTxn methods. * 1. If timeout service tracks timeout of a txn, then txn is also present in the host-txn index of current process. * 2. If txn znode is updated, then txn is also present in the host-txn index of current process. * * @param scope scope name. * @param stream stream name. * @param lease txn lease. * @param ctx context. * @return identifier of the created txn. */ CompletableFuture<Pair<VersionedTransactionData, List<StreamSegmentRecord>>> createTxnBody(final String scope, final String stream, final long lease, final OperationContext ctx) { // Step 1. Validate parameters. CompletableFuture<Void> validate = validate(lease); long maxExecutionPeriod = Math.min(MAX_EXECUTION_TIME_MULTIPLIER * lease, Duration.ofDays(1).toMillis()); // 1. get latest epoch from history // 2. generateNewTransactionId.. this step can throw WriteConflictException // 3. txn id = 32 bit epoch + 96 bit counter // 4. if while creating txn epoch no longer exists, then we will get DataNotFoundException. // 5. Retry if we get WriteConflict or DataNotFoundException, from step 1. // Note: this is a low probability for either exceptions: // - WriteConflict, if multiple controllers are trying to get new range at the same time then we can get write conflict // - DataNotFoundException because it will only happen in rare case // when we generate the transactionid against latest epoch (if there is ongoing scale then this is new epoch) // and then epoch node is deleted as scale starts and completes. return validate.thenCompose(validated -> RetryHelper.withRetriesAsync(() -> streamMetadataStore.generateTransactionId(scope, stream, ctx, executor) .thenCompose(txnId -> { CompletableFuture<Void> addIndex = addTxnToIndex(scope, stream, txnId); // Step 3. Create txn node in the store. CompletableFuture<VersionedTransactionData> txnFuture = createTxnInStore(scope, stream, lease, ctx, maxExecutionPeriod, txnId, addIndex); // Step 4. Notify segment stores about new txn. CompletableFuture<List<StreamSegmentRecord>> segmentsFuture = txnFuture.thenComposeAsync(txnData -> streamMetadataStore.getSegmentsInEpoch(scope, stream, txnData.getEpoch(), ctx, executor), executor); CompletableFuture<Void> notify = segmentsFuture.thenComposeAsync(activeSegments -> notifyTxnCreation(scope, stream, activeSegments, txnId), executor).whenComplete((v, e) -> // Method notifyTxnCreation ensures that notification completes // even in the presence of n/w or segment store failures. log.trace("Txn={}, notified segments stores", txnId)); // Step 5. Start tracking txn in timeout service return notify.whenCompleteAsync((result, ex) -> { addTxnToTimeoutService(scope, stream, lease, maxExecutionPeriod, txnId, txnFuture); }, executor).thenApplyAsync(v -> { List<StreamSegmentRecord> segments = segmentsFuture.join().stream().map(x -> { long generalizedSegmentId = RecordHelper.generalizedSegmentId(x.segmentId(), txnId); int epoch = StreamSegmentNameUtils.getEpoch(generalizedSegmentId); int segmentNumber = StreamSegmentNameUtils.getSegmentNumber(generalizedSegmentId); return StreamSegmentRecord.builder().creationEpoch(epoch).segmentNumber(segmentNumber) .creationTime(x.getCreationTime()).keyStart(x.getKeyStart()).keyEnd(x.getKeyEnd()).build(); }).collect(Collectors.toList()); return new ImmutablePair<>(txnFuture.join(), segments); }, executor); }), e -> { Throwable unwrap = Exceptions.unwrap(e); return unwrap instanceof StoreException.WriteConflictException || unwrap instanceof StoreException.DataNotFoundException; }, 5, executor)); } private void addTxnToTimeoutService(String scope, String stream, long lease, long maxExecutionPeriod, UUID txnId, CompletableFuture<VersionedTransactionData> txnFuture) { Version version = null; long executionExpiryTime = System.currentTimeMillis() + maxExecutionPeriod; if (!txnFuture.isCompletedExceptionally()) { version = txnFuture.join().getVersion(); executionExpiryTime = txnFuture.join().getMaxExecutionExpiryTime(); } timeoutService.addTxn(scope, stream, txnId, version, lease, executionExpiryTime); log.trace("Txn={}, added to timeout service on host={}", txnId, hostId); } private CompletableFuture<VersionedTransactionData> createTxnInStore(String scope, String stream, long lease, OperationContext ctx, long maxExecutionPeriod, UUID txnId, CompletableFuture<Void> addIndex) { return addIndex.thenComposeAsync(ignore -> streamMetadataStore.createTransaction(scope, stream, txnId, lease, maxExecutionPeriod, ctx, executor), executor).whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed creating txn in store", txnId); } else { log.debug("Txn={}, created in store", txnId); } }); } private CompletableFuture<Void> addTxnToIndex(String scope, String stream, UUID txnId) { TxnResource resource = new TxnResource(scope, stream, txnId); // Step 2. Add txn to host-transaction index. return streamMetadataStore.addTxnToIndex(hostId, resource, null) .whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed adding txn to host-txn index of host={}", txnId, hostId); } else { log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId); } }); } @SuppressWarnings("ReturnCount") private CompletableFuture<Void> validate(long lease) { if (lease < Config.MIN_LEASE_VALUE) { return Futures.failedFuture(new IllegalArgumentException("lease should be greater than minimum lease")); } // If lease value is too large return error if (lease > timeoutService.getMaxLeaseValue()) { return Futures.failedFuture(new IllegalArgumentException("lease value too large, max value is " + timeoutService.getMaxLeaseValue())); } return CompletableFuture.completedFuture(null); } /** * Ping a txn thereby updating its timeout to current time + lease. * * Post-condition: * 1. If ping request completes successfully, then * (a) txn timeout is set to lease + current time in timeout service, * (b) txn version in timeout service equals version of txn node in store, * (c) if txn's timeout was not previously tracked in timeout service of current process, * then version of txn node in store is updated, thus fencing out other processes tracking timeout for this txn, * (d) txn is present in the host-txn index of current host, * * 2. If process fails before responding to the client, then since txn is present in the host-txn index, * some other controller process shall abort the txn after maxLeaseValue * * Store read/update operation is not invoked on receiving ping request for a txn that is being tracked in the * timeout service. Otherwise, if the txn is not being tracked in the timeout service, txn node is read from * the store and updated. * * @param scope scope name. * @param stream stream name. * @param txnId txn id. * @param lease txn lease. * @param ctx context. * @return ping status. */ CompletableFuture<PingTxnStatus> pingTxnBody(final String scope, final String stream, final UUID txnId, final long lease, final OperationContext ctx) { if (!timeoutService.isRunning()) { return CompletableFuture.completedFuture(createStatus(Status.DISCONNECTED)); } log.debug("Txn={}, updating txn node in store and extending lease", txnId); return fenceTxnUpdateLease(scope, stream, txnId, lease, ctx); } private PingTxnStatus createStatus(Status status) { return PingTxnStatus.newBuilder().setStatus(status).build(); } private CompletableFuture<PingTxnStatus> fenceTxnUpdateLease(final String scope, final String stream, final UUID txnId, final long lease, final OperationContext ctx) { // Step 1. Check whether lease value is within necessary bounds. // Step 2. Add txn to host-transaction index. // Step 3. Update txn node data in the store,thus updating its version // and fencing other processes from tracking this txn's timeout. // Step 4. Add this txn to timeout service and start managing timeout for this txn. return streamMetadataStore.getTransactionData(scope, stream, txnId, ctx, executor).thenComposeAsync(txnData -> { final TxnStatus txnStatus = txnData.getStatus(); if (!txnStatus.equals(TxnStatus.OPEN)) { // transaction is not open, dont ping it return CompletableFuture.completedFuture(getPingTxnStatus(txnStatus)); } // Step 1. Sanity check for lease value. if (lease > timeoutService.getMaxLeaseValue()) { return CompletableFuture.completedFuture(createStatus(Status.LEASE_TOO_LARGE)); } else if (lease + System.currentTimeMillis() > txnData.getMaxExecutionExpiryTime()) { return CompletableFuture.completedFuture(createStatus(Status.MAX_EXECUTION_TIME_EXCEEDED)); } else { TxnResource resource = new TxnResource(scope, stream, txnId); // Step 2. Add txn to host-transaction index CompletableFuture<Void> addIndex = !timeoutService.containsTxn(scope, stream, txnId) ? streamMetadataStore.addTxnToIndex(hostId, resource, txnData.getVersion()) : CompletableFuture.completedFuture(null); addIndex.whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed adding txn to host-txn index of host={}", txnId, hostId); } else { log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId); } }); return addIndex.thenComposeAsync(x -> { // Step 3. Update txn node data in the store. CompletableFuture<VersionedTransactionData> pingTxn = streamMetadataStore.pingTransaction( scope, stream, txnData, lease, ctx, executor).whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed updating txn node in store", txnId); } else { log.debug("Txn={}, updated txn node in store", txnId); } }); // Step 4. Add it to timeout service and start managing timeout for this txn. return pingTxn.thenApplyAsync(data -> { Version version = data.getVersion(); long expiryTime = data.getMaxExecutionExpiryTime(); // Even if timeout service has an active/executing timeout task for this txn, it is bound // to fail, since version of txn node has changed because of the above store.pingTxn call. // Hence explicitly add a new timeout task. if (timeoutService.containsTxn(scope, stream, txnId)) { // If timeout service knows about this transaction, attempt to increase its lease. log.debug("Txn={}, extending lease in timeout service", txnId); timeoutService.pingTxn(scope, stream, txnId, version, lease); } else { log.debug("Txn={}, adding in timeout service", txnId); timeoutService.addTxn(scope, stream, txnId, version, lease, expiryTime); } return createStatus(Status.OK); }, executor); }, executor); } }, executor); } private PingTxnStatus getPingTxnStatus(final TxnStatus txnStatus) { final PingTxnStatus status; if (txnStatus.equals(TxnStatus.COMMITTED) || txnStatus.equals(TxnStatus.COMMITTING)) { status = createStatus(PingTxnStatus.Status.COMMITTED); } else if (txnStatus.equals(TxnStatus.ABORTED) || txnStatus.equals(TxnStatus.ABORTING)) { status = createStatus(PingTxnStatus.Status.ABORTED); } else { status = createStatus(PingTxnStatus.Status.UNKNOWN); } return status; } /** * Seals a txn and transitions it to COMMITTING (resp. ABORTING) state if commit param is true (resp. false). * * Post-condition: * 1. If seal completes successfully, then * (a) txn state is COMMITTING/ABORTING, * (b) CommitEvent/AbortEvent is present in the commit stream/abort stream, * (c) txn is removed from host-txn index, * (d) txn is removed from the timeout service. * * 2. If process fails after transitioning txn to COMMITTING/ABORTING state, but before responding to client, then * since txn is present in the host-txn index, some other controller process shall put CommitEvent/AbortEvent to * commit stream/abort stream. * * @param host host id. It is different from hostId iff invoked from TxnSweeper for aborting orphaned txn. * @param scope scope name. * @param stream stream name. * @param commit boolean indicating whether to commit txn. * @param txnId txn id. * @param version expected version of txn node in store. * @param ctx context. * @return Txn status after sealing it. */ CompletableFuture<TxnStatus> sealTxnBody(final String host, final String scope, final String stream, final boolean commit, final UUID txnId, final Version version, final OperationContext ctx) { TxnResource resource = new TxnResource(scope, stream, txnId); Optional<Version> versionOpt = Optional.ofNullable(version); // Step 1. Add txn to current host's index, if it is not already present CompletableFuture<Void> addIndex = host.equals(hostId) && !timeoutService.containsTxn(scope, stream, txnId) ? // PS: txn version in index does not matter, because if update is successful, // then txn would no longer be open. streamMetadataStore.addTxnToIndex(hostId, resource, version) : CompletableFuture.completedFuture(null); addIndex.whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, already present/newly added to host-txn index of host={}", txnId, hostId); } else { log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId); } }); // Step 2. Seal txn CompletableFuture<AbstractMap.SimpleEntry<TxnStatus, Integer>> sealFuture = addIndex.thenComposeAsync(x -> streamMetadataStore.sealTransaction(scope, stream, txnId, commit, versionOpt, ctx, executor), executor) .whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed sealing txn", txnId); } else { log.debug("Txn={}, sealed successfully, commit={}", txnId, commit); } }); // Step 3. write event to corresponding stream. return sealFuture.thenComposeAsync(pair -> { TxnStatus status = pair.getKey(); switch (status) { case COMMITTING: return writeCommitEvent(scope, stream, pair.getValue(), txnId, status); case ABORTING: return writeAbortEvent(scope, stream, pair.getValue(), txnId, status); case ABORTED: case COMMITTED: return CompletableFuture.completedFuture(status); case OPEN: case UNKNOWN: default: // Not possible after successful streamStore.sealTransaction call, because otherwise an // exception would be thrown. return CompletableFuture.completedFuture(status); } }, executor).thenComposeAsync(status -> { // Step 4. Remove txn from timeoutService, and from the index. timeoutService.removeTxn(scope, stream, txnId); log.debug("Txn={}, removed from timeout service", txnId); return streamMetadataStore.removeTxnFromIndex(host, resource, true).whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed removing txn from host-txn index of host={}", txnId, hostId); } else { log.debug("Txn={}, removed txn from host-txn index of host={}", txnId, hostId); } }).thenApply(x -> status); }, executor); } public CompletableFuture<Void> writeCommitEvent(CommitEvent event) { return commitWriterFuture .thenCompose(commitWriter -> commitWriter.writeEvent(event.getKey(), event)); } CompletableFuture<TxnStatus> writeCommitEvent(String scope, String stream, int epoch, UUID txnId, TxnStatus status) { CommitEvent event = new CommitEvent(scope, stream, epoch); return TaskStepsRetryHelper.withRetries(() -> writeCommitEvent(event) .handle((r, e) -> { if (e != null) { log.debug("Transaction {}, failed posting commit event. Retrying...", txnId); throw new WriteFailedException(e); } else { log.debug("Transaction {} commit event posted", txnId); return status; } }), executor); } public CompletableFuture<Void> writeAbortEvent(AbortEvent event) { return abortWriterFuture .thenCompose(abortWriter -> abortWriter.writeEvent(event.getKey(), event)); } CompletableFuture<TxnStatus> writeAbortEvent(String scope, String stream, int epoch, UUID txnId, TxnStatus status) { AbortEvent event = new AbortEvent(scope, stream, epoch, txnId); return TaskStepsRetryHelper.withRetries(() -> writeAbortEvent(event) .handle((r, e) -> { if (e != null) { log.debug("Transaction {}, failed posting abort event. Retrying...", txnId); throw new WriteFailedException(e); } else { log.debug("Transaction {} abort event posted", txnId); return status; } }), executor); } private CompletableFuture<Void> notifyTxnCreation(final String scope, final String stream, final List<StreamSegmentRecord> segments, final UUID txnId) { return Futures.allOf(segments.stream() .parallel() .map(segment -> notifyTxnCreation(scope, stream, segment.segmentId(), txnId)) .collect(Collectors.toList())); } private CompletableFuture<Void> notifyTxnCreation(final String scope, final String stream, final long segmentId, final UUID txnId) { return TaskStepsRetryHelper.withRetries(() -> segmentHelper.createTransaction(scope, stream, segmentId, txnId, this.retrieveDelegationToken()), executor); } private OperationContext getNonNullOperationContext(final String scope, final String stream, final OperationContext contextOpt) { return contextOpt == null ? streamMetadataStore.createContext(scope, stream) : contextOpt; } public String retrieveDelegationToken() { return authHelper.retrieveMasterToken(); } @Override @Synchronized public void close() throws Exception { timeoutService.stopAsync(); timeoutService.awaitTerminated(); CompletableFuture<Void> commitCloseFuture = commitWriterFuture.thenAccept(EventStreamWriter::close); CompletableFuture<Void> abortCloseFuture = abortWriterFuture.thenAccept(EventStreamWriter::close); // since we do the checks under synchronized block, we know the promise for writers cannot be completed // by anyone if we have the lock and we can simply cancel the futures. if (commitWriterFuture.isDone()) { commitCloseFuture.join(); } else { commitWriterFuture.cancel(true); } if (abortWriterFuture.isDone()) { abortCloseFuture.join(); } else { abortWriterFuture.cancel(true); } } }
52.425072
133
0.600253
f113a56cc988a54370b709842d941c2c8bdccbc9
2,548
package com.mint.controller.portal; import com.mint.common.ServerResponse; import com.mint.service.ICollectionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.List; /** * @Program: mint2bbs * @Description: 收藏相关Action * @Author: Jeanne d'Arc * @Create: 2019-03-15 13:33:29 **/ @Controller @RequestMapping("/collection") public class CollectionController { @Autowired ICollectionService iCollectionService; /** * @Description 收藏 * @Param user * @Param resident * @Param session * @Return ServerResponse<String> */ @RequestMapping(value = "collect.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<String> collect(String iid, int itype, String isid, HttpSession session) { ServerResponse<String> response = iCollectionService.collect(iid, itype, isid, session); return response; } /** * @Description 取消收藏 * @Param user * @Param resident * @Param session * @Return ServerResponse<String> */ @RequestMapping(value = "cancelCollect.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<HashMap<String, String>> cancelCollect(String cid) { return iCollectionService.cancelCollect(cid); } /** * @Description 收藏 * @Param user * @Param resident * @Param session * @Return ServerResponse<String> */ @RequestMapping(value = "getMyCollectionCount.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<Integer> getMyCollectionCount(HttpSession session) { return iCollectionService.getMyCollectionCount(session); } /** * @Description 收藏 * @Param user * @Param resident * @Param session * @Return ServerResponse<String> */ @RequestMapping(value = "getMyCollectionWithPage.do", method = RequestMethod.POST) @ResponseBody public ServerResponse<List<HashMap<String, String>>> getMyCollectionWithPage(Integer page, Integer limit, HttpSession session) { return iCollectionService.getMyCollectionWithPage(page, limit, session); } }
30.698795
133
0.686028
349744d68a28d9b8209aabfacda61675e86a16fa
2,293
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.common.mailbox; public final class FolderConstants { private FolderConstants() { } public static final int ID_AUTO_INCREMENT = -1; public static final int ID_FOLDER_USER_ROOT = 1; public static final int ID_FOLDER_INBOX = 2; public static final int ID_FOLDER_TRASH = 3; public static final int ID_FOLDER_SPAM = 4; public static final int ID_FOLDER_SENT = 5; public static final int ID_FOLDER_DRAFTS = 6; public static final int ID_FOLDER_CONTACTS = 7; public static final int ID_FOLDER_TAGS = 8; public static final int ID_FOLDER_CONVERSATIONS = 9; public static final int ID_FOLDER_CALENDAR = 10; public static final int ID_FOLDER_ROOT = 11; // no longer created in new mailboxes since Helix (bug 39647). old mailboxes may still contain a system folder with id 12 @Deprecated public static final int ID_FOLDER_NOTEBOOK = 12; public static final int ID_FOLDER_AUTO_CONTACTS = 13; public static final int ID_FOLDER_IM_LOGS = 14; public static final int ID_FOLDER_TASKS = 15; public static final int ID_FOLDER_BRIEFCASE = 16; public static final int ID_FOLDER_COMMENTS = 17; // ID_FOLDER_PROFILE Was used for folder related to ProfileServlet which was used in pre-release Iron Maiden only. // Old mailboxes may still contain a system folder with id 18 @Deprecated public static final int ID_FOLDER_PROFILE = 18; public static final int ID_FOLDER_UNSUBSCRIBE = 19; public static final int HIGHEST_SYSTEM_ID = 19; }
42.462963
126
0.737462
7b390d08cc8263575c18755fe9557f0efdaaec73
4,713
/* OpenRemote, the Home of the Digital Home. * Copyright 2008-2012, OpenRemote Inc. * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openremote.modeler.domain.component; import java.util.ArrayList; import java.util.List; import org.openremote.modeler.domain.Cell; import org.openremote.modeler.domain.ConfigurationFilesGenerationContext; import org.openremote.modeler.domain.PositionableAndSizable; /** * used to store grid's information. * @author Javen * */ public class UIGrid extends UIComponent implements PositionableAndSizable { private static final long serialVersionUID = 7321863137565245106L; public static final int DEFAULT_LEFT = 1; public static final int DEFALUT_TOP = 1; public static final int DEFALUT_WIDTH = 200; public static final int DEFAULT_HEIGHT = 200; public static final int DEFALUT_ROW_COUNT = 4; public static final int DEFAULT_COL_COUNT = 4; private int left; private int top; private int width; private int height; private int rowCount; private int columnCount; private List<Cell> cells = new ArrayList<Cell>(); public UIGrid(UIGrid grid) { this.left = grid.left; this.top = grid.top; this.width = grid.width; this.height = grid.height; this.rowCount = grid.rowCount; this.columnCount = grid.columnCount; this.cells = grid.cells; } public UIGrid() { super(); this.left = DEFAULT_LEFT; this.top = DEFALUT_TOP; this.width = DEFALUT_WIDTH; this.height = DEFAULT_HEIGHT; this.columnCount = DEFAULT_COL_COUNT; this.rowCount = DEFALUT_ROW_COUNT; } public UIGrid(int left, int top, int width, int height, int rowCount, int columnCount) { super(); this.height = Math.round(height); this.columnCount = columnCount; this.left = Math.round(left); this.rowCount = rowCount; this.top = Math.round(top); this.width = Math.round(width); } public int getLeft() { return left; } public void setLeft(int left) { this.left = Math.round(left); } public int getTop() { return top; } public void setTop(int top) { this.top = Math.round(top); } public int getWidth() { return width; } public void setWidth(int width) { this.width = Math.round(width); } public int getHeight() { return height; } public void setHeight(int height) { this.height = Math.round(height); } public int getRowCount() { return rowCount; } public void setRowCount(int rowCount) { this.rowCount = rowCount; } public int getColumnCount() { return columnCount; } public void setColumnCount(int columnCount) { this.columnCount = columnCount; } public List<Cell> getCells() { return cells; } public void setCells(List<Cell> cells) { this.cells = cells; } public void addCell(Cell cell) { cells.add(cell); } public void removeCell(Cell cell) { cells.remove(cell); } @Override public String getPanelXml(ConfigurationFilesGenerationContext context) { // TODO Auto-generated method stub return null; } @Override public String getName() { return "Grid"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } UIGrid other = (UIGrid) obj; if (left == other.left && top == other.top && width == other.width && height == other.height && columnCount == other.columnCount && rowCount == other.rowCount && cells.equals(other.cells)) { return true; } return false; } }
27.086207
110
0.635264
ed6a0179d9c40b89aa9d7191fd9db9febf7490cf
4,013
package de.erdbeerbaerlp.gbmod.gui; import de.erdbeerbaerlp.gbmod.items.CapabilityGameBoy; import de.erdbeerbaerlp.gbmod.util.ClientOnly; import de.erdbeerbaerlp.guilib.components.Button; import de.erdbeerbaerlp.guilib.gui.BetterGuiScreen; import eu.rekawek.coffeegb.controller.ButtonListener; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import java.io.IOException; @SuppressWarnings("FieldCanBeLocal") @SideOnly(Side.CLIENT) public class GuiGameboy extends BetterGuiScreen { ComponentGameboyScreen screen; Button btnReset; Button btnStop; Button btnStart; private final CapabilityGameBoy gb; public GuiGameboy(CapabilityGameBoy cap) { super(); this.gb = cap; screen.setGb(cap); } /** * Add your components here! */ @Override public void buildGui() { screen = new ComponentGameboyScreen(0, 0); btnStart = new Button(0,0,"Resume", Button.DefaultButtonIcons.PLAY); btnReset = new Button(0,0,"Reset"); btnStop = new Button(0,0,"Pause",Button.DefaultButtonIcons.PAUSE); btnReset.setClickListener(()->{ try { gb.getEmulator().reset(); } catch (Exception e) { e.printStackTrace(); } }); btnStart.setClickListener(()->{ try { gb.getEmulator().run(); } catch (Exception e) { e.printStackTrace(); } }); btnStop.setClickListener(() -> gb.getEmulator().stop()); /*btnSetRom.setClickListener(()->{ try{ gb.cap.getEmulator().switchRom(new File("./config/gameboy-roms/pokemon-debug-yellow/DebugYellow.gbc")); }catch (Exception e){ e.printStackTrace(); } });*/ addAllComponents(screen, btnReset, btnStart, btnStop); } /** * Gets called often to e.g. update components postions */ @Override public void updateGui() { screen.setPosition(width/2, height/2); btnStop.setPosition(width/20, height/2); btnStart.setPosition(btnStop.getX(), btnStop.getY()-btnStart.getHeight()-10); btnReset.setPosition(btnStop.getX(), btnStop.getY()+btnStop.getHeight()+10); //btnSetRom.setPosition(btnStop.getX(), btnStart.getY()-btnSetRom.getHeight()-10); } @Override public boolean doesGuiPauseGame() { return false; } /** * Should pressing ESC close the GUI? */ @Override public boolean doesEscCloseGui() { return true; } @Override public void handleKeyboardInput() throws IOException { super.handleKeyboardInput(); final int key = Keyboard.getEventKey(); final ButtonListener.Button btn = getButton(key); boolean press = Keyboard.isKeyDown(key); if(btn != null) if(press) gb.getEmulator().getJoypad().buttonPress(btn); else gb.getEmulator().getJoypad().buttonRelease(btn); } private ButtonListener.Button getButton(int key){ if (key == ClientOnly.keyGBRight.getKeyCode()) return ButtonListener.Button.RIGHT; if (key == ClientOnly.keyGBUp.getKeyCode()) return ButtonListener.Button.UP; if (key == ClientOnly.keyGBDown.getKeyCode()) return ButtonListener.Button.DOWN; if (key == ClientOnly.keyGBLeft.getKeyCode()) return ButtonListener.Button.LEFT; if (key == ClientOnly.keyGBA.getKeyCode()) return ButtonListener.Button.A; if (key == ClientOnly.keyGBB.getKeyCode()) return ButtonListener.Button.B; if (key == ClientOnly.keyGBStart.getKeyCode()) return ButtonListener.Button.START; if (key == ClientOnly.keyGBSelect.getKeyCode()) return ButtonListener.Button.SELECT; return null; } }
32.626016
119
0.621231
5e6884b97436a785569617e04602cbc171b061bb
7,983
package com.homework.Controller; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.Properties; /** * ControllerServlet.java * This servlet acts as a page controller for the application, handling all * requests from the user. * * @lastName www.codejava.net */ public class ControllerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String DATABASE_URL_PROPERTY_KEY = "database.url"; private static final String DATABASE_USERNAME_PROPERTY_KEY = "database.username"; private static final String DATABASE_PASSWORD_PROPERTY_KEY = "database.password"; private String jdbcURL; private String jdbcUsername; private String jdbcPassword; private ClientController clientCont = new ClientController(); private OrderController orderCont = new OrderController(); private ItemController itemCont = new ItemController(); private PaymentController paymentCont = new PaymentController(); public ControllerServlet() { Properties properties = new Properties(); try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); properties.load(loader.getResourceAsStream("application.properties")); } catch (FileNotFoundException e) { System.out.println("Could not find application properties file"); } catch (IOException e) { System.out.println("Error trying to read application properties"); } jdbcURL = properties.getProperty(DATABASE_URL_PROPERTY_KEY); jdbcUsername = properties.getProperty(DATABASE_USERNAME_PROPERTY_KEY); jdbcPassword = properties.getProperty(DATABASE_PASSWORD_PROPERTY_KEY); // get the property value and print it out System.out.println("Successfully loaded database url= " + properties.getProperty(DATABASE_URL_PROPERTY_KEY)); System.out.println("Successfully loaded database username= " + properties.getProperty(DATABASE_USERNAME_PROPERTY_KEY)); System.out.println("Successfully loaded database password= " + properties.getProperty(DATABASE_PASSWORD_PROPERTY_KEY)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getServletPath(); try { switch (action) { case "/new": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.showNewForm(request, response); break; case "/newOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.showNewForm(request, response); break; case "/newItem": itemCont.init(jdbcURL, jdbcUsername, jdbcPassword); itemCont.showNewForm(request, response); break; case "/newPayment": paymentCont.init(jdbcURL, jdbcUsername, jdbcPassword); paymentCont.showNewForm(request, response); break; case "/insert": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.insert(request, response); break; case "/insertOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.insert(request, response); break; case "/insertItem": itemCont.init(jdbcURL, jdbcUsername, jdbcPassword); itemCont.insert(request, response); break; case "/insertPayment": paymentCont.init(jdbcURL, jdbcUsername, jdbcPassword); paymentCont.insert(request, response); break; case "/delete": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.delete(request, response); break; case "/deleteOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.delete(request, response); break; case "/deleteItem": itemCont.init(jdbcURL, jdbcUsername, jdbcPassword); itemCont.delete(request, response); break; case "/deletePayment": paymentCont.init(jdbcURL, jdbcUsername, jdbcPassword); paymentCont.delete(request, response); break; case "/edit": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.showEditForm(request, response); break; case "/editOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.showEditForm(request, response); break; case "/editItem": itemCont.init(jdbcURL, jdbcUsername, jdbcPassword); itemCont.showEditForm(request, response); break; case "/editPayment": paymentCont.init(jdbcURL, jdbcUsername, jdbcPassword); paymentCont.showEditForm(request, response); break; case "/update": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.update(request, response); break; case "/updateOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.update(request, response); break; case "/updateItem": itemCont.init(jdbcURL, jdbcUsername, jdbcPassword); itemCont.update(request, response); break; case "/updatePayment": paymentCont.init(jdbcURL, jdbcUsername, jdbcPassword); paymentCont.update(request, response); break; case "/options": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.showOptionForm(request, response); break; case "/optionsOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.showOptionForm(request, response); break; case "/": clientCont.init(jdbcURL, jdbcUsername, jdbcPassword); clientCont.listClient(request, response); break; case "/listOrder": orderCont.init(jdbcURL, jdbcUsername, jdbcPassword); orderCont.listOrder(request, response); break; case "/listItem": itemCont.init(jdbcURL, jdbcUsername, jdbcPassword); itemCont.listItem(request, response); break; case "/listPayment": paymentCont.init(jdbcURL, jdbcUsername, jdbcPassword); paymentCont.listPayment(request, response); break; } } catch (SQLException ex) { throw new ServletException(ex); } } }
44.597765
127
0.575849
6c34654f237f6307b5aa3bc3b5ce52c858465784
2,127
package com.lambdaschool.oktafoundation.models; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.persistence.*; import javax.validation.constraints.NotNull; @ApiModel(value = "Reactions") @Entity @Table (name = "reactions") public class Reactions extends Auditable { @ApiModelProperty(name = "reactionid", value = "primary key for reactions", required = true, example = "1") @Id @GeneratedValue(strategy = GenerationType.AUTO) private long reactionid; @ApiModelProperty(name = "emojiname", value = "name of the emoji", required = true, example = "Happy") @NotNull @Column(unique = true) private String emojiname; @ApiModelProperty(name = "emojicode", value = "the unicode value that represents the emoji", required = true, example = "1F600") @NotNull @Column(unique = true) private String emojicode; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "member") private Member member; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "program") private Program program; public Reactions() { } public Reactions(String emojicode, String emojiname) { this.emojiname = emojiname; this.emojicode = emojicode; } public long getReactionid() { return reactionid; } public void setReactionid(long reactionid) { this.reactionid = reactionid; } public String getEmojiname() { return emojiname; } public void setEmojiname(String emojiname) { this.emojiname = emojiname; } public String getEmojicode() { return emojicode; } public void setEmojicode(String emojicode) { this.emojicode = emojicode; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public Program getProgram() { return program; } public void setProgram(Program program) { this.program = program; } }
22.62766
62
0.639868
490c71b4f600dabc2735c5a5a9b2688714d40741
1,575
package com.javachess.screens; import com.javachess.Constants; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.*; /* import java.awt.event.ActionEvent; import java.awt.event.ActionListener; */ public class LoginScreen { public LoginScreen(JPanel parentPanel, CardLayout card) { JPanel panel = new JPanel(new GridLayout(5,1)); panel.setBorder(Constants.zeroPadding); JLabel loginString = new JLabel(Constants.LoginScreenLabel , SwingConstants.CENTER); panel.add(loginString); JTextField userName = new JTextField(); userName.setColumns(Constants.LoginInputCols); JPanel userNamePanel = FlowPanel(); userNamePanel.add(userName); panel.add(userNamePanel); JTextField password = new JTextField(); password.setColumns(Constants.LoginInputCols); JPanel passwordPanel = FlowPanel(); passwordPanel.add(password); panel.add(passwordPanel); JButton loginButton = new JButton("Login"); JPanel loginPanel = FlowPanel(); loginPanel.add(loginButton); panel.add(loginPanel); panel.setPreferredSize(new Dimension(800, 600)); parentPanel.add(panel); parentPanel.revalidate(); loginButton.addActionListener(e -> { card.next(parentPanel); }); } private JPanel FlowPanel() { JPanel panel = new JPanel(new FlowLayout()); return panel; } }
27.631579
92
0.674286
f1b49438f43980a3fa394ee9b0c48e867e8f5020
2,205
package app.hanks.com.conquer.activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import app.hanks.com.conquer.R; public class AboutActivity extends BaseActivity { private ProgressBar pb; private final String aboutUrl = "http://wap.ev123.com/wap_q1w2e4.html"; private final String useUrl = "http://wap.ev123.com/wap/blank.php?username=q1w2e4&channel_id=10829090"; private final String helpUrl = "http://wap.ev123.com/wap/blank.php?username=q1w2e4&channel_id=10829041"; private String url = aboutUrl; private String title = "关于我们"; @Override protected void onCreate(Bundle savedInstanceState) { String type = getIntent().getStringExtra("type"); if (type.endsWith("about")) { url = aboutUrl; title = "关于我们"; } else if (type.endsWith("use")) { url = useUrl; title = "用户协议"; } else if (type.endsWith("help")) { url = helpUrl; title = "使用帮助"; } super.onCreate(savedInstanceState); init(); } /** * 初始化 */ private void init() { WebView webView = (WebView) findViewById(R.id.webview); pb = (ProgressBar) findViewById(R.id.pb); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setSupportZoom(true); webView.getSettings().setBuiltInZoomControls(true); // 为WebView设置WebViewClient处理某些操作 webView.setWebChromeClient(new webViewClient()); webView.loadUrl(url); } class webViewClient extends WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { pb.setProgress(newProgress); if (newProgress == 100) { pb.setVisibility(View.GONE); } super.onProgressChanged(view, newProgress); } } @Override public void initTitleBar(ViewGroup rl_title, TextView tv_title, ImageButton ib_back, ImageButton ib_right, View shadow) { tv_title.setText(title); ib_back.setImageResource(R.drawable.ic_clear_white_24dp); shadow.setVisibility(View.GONE); } @Override public View getContentView() { return View.inflate(context, R.layout.activity_about, null); } }
28.269231
122
0.741497
cf20304f14fa020aa8585445024ef397d785f587
240
package br.com.gabriel.exercicios; public class Fibonacci { public static void main(String[] args) { int x = 0; int y = 1; while (x <= 50) { System.out.print(x + " "); System.out.print(y + " "); x += y; y += x; } } }
16
41
0.545833
55a353e21747e71a66757d93eaea2fcd470bcc71
4,307
package semexe.tables.serialize; import semexe.*; import semexe.basic.IOUtils; import semexe.basic.LispTree; import semexe.basic.LogInfo; import semexe.basic.Pair; import semexe.exec.Execution; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Generate TSV files containing information about fuzzy matched objects. * * @author ppasupat */ public class TaggedFuzzyGenerator extends TSVGenerator implements Runnable { private static final String[] FIELDS = new String[]{ "id", "type", "start", "end", "phrase", "fragment" }; private Grammar grammar = new Grammar(); public static void main(String[] args) { Execution.run(args, "TaggedFuzzyGeneratorMain", new TaggedFuzzyGenerator(), Master.getOptionsParser()); } @Override public void run() { // Read grammar grammar.read(Grammar.opts.inPaths); // Read dataset LogInfo.begin_track("Dataset.read"); for (Pair<String, String> pathPair : Dataset.opts.inPaths) { String group = pathPair.getFirst(); String path = pathPair.getSecond(); // Open output file String filename = Execution.getFile("fuzzy-" + group + ".tsv"); out = IOUtils.openOutHard(filename); dump(FIELDS); // Read LispTrees LogInfo.begin_track("Reading %s", path); int maxExamples = Dataset.getMaxExamplesForGroup(group); Iterator<LispTree> trees = LispTree.proto.parseFromFile(path); // Go through the examples int n = 0; while (n < maxExamples) { // Format: (example (id ...) (utterance ...) (targetFormula ...) (targetValue ...)) LispTree tree = trees.next(); if (tree == null) break; if (tree.children.size() < 2 || !"example".equals(tree.child(0).value)) { if ("metadata".equals(tree.child(0).value)) continue; throw new RuntimeException("Invalid example: " + tree); } Example ex = Example.fromLispTree(tree, path + ':' + n); ex.preprocess(); LogInfo.begin_track("Example %s (%d): %s => %s", ex.id, n, ex.getTokens(), ex.targetValue); n++; dumpExample(ex, tree); LogInfo.end_track(); } out.close(); LogInfo.logs("Finished dumping to %s", filename); LogInfo.end_track(); } LogInfo.end_track(); } @Override protected void dump(String... stuff) { assert stuff.length == FIELDS.length; super.dump(stuff); } private void dumpExample(Example ex, LispTree tree) { int n = ex.numTokens(); for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(ex.token(i)); for (int j = i; j < n; j++) { String term = sb.toString(); Derivation deriv = new Derivation.Builder() .cat(Rule.phraseCat).start(i).end(j) .rule(Rule.nullRule) .children(Derivation.emptyList) .withStringFormulaFrom(term) .canonicalUtterance(term) .createDerivation(); List<Derivation> children = new ArrayList<>(); children.add(deriv); // Get the derived derivations for (Rule rule : grammar.getRules()) { SemanticFn.CallInfo c = new SemanticFn.CallInfo(rule.lhs, i, j + 1, rule, children); Iterator<Derivation> itr = rule.sem.call(ex, c); while (itr.hasNext()) { deriv = itr.next(); LogInfo.logs("Found %s %s -> %s", rule.lhs, term, deriv.formula); dump(ex.id, rule.lhs.substring(1), String.valueOf(i), String.valueOf(j + 1), term, deriv.formula.toString()); } } if (j + 1 < n) sb.append(' ').append(ex.token(j + 1)); } } } }
38.455357
133
0.521244
6e7fe97885c56c3ce08c048f2266c0985d926b40
1,307
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class CheckoutPage extends BasePage { public static final By CHECKOUT_BUTTON = By.id("checkout"); public static final By FIRST_NAME_FIELD = By.id("first-name"); public static final By LAST_NAME_FIELD = By.id("last-name"); public static final By ZIP_CODE = By.id("postal-code"); public static final By CONTINUE_BUTTON = By.id("continue"); public static final By FINISH_BUTTON = By.id("finish"); public static final By BACK_BUTTON = By.id("back-to-products"); String firstName = "John"; String lastName = "Doe"; String zipCode = "220055"; public CheckoutPage(WebDriver driver) { super(driver); } public void checkoutClick() { driver.findElement(CHECKOUT_BUTTON).click(); } public void fillInUserInfo() { driver.findElement(FIRST_NAME_FIELD).sendKeys(firstName); driver.findElement(LAST_NAME_FIELD).sendKeys(lastName); driver.findElement(ZIP_CODE).sendKeys(zipCode); driver.findElement(CONTINUE_BUTTON).click(); } public void FinishCheckout() { driver.findElement(FINISH_BUTTON).click(); } public void backToProducts() { driver.findElement(BACK_BUTTON).click(); } }
30.395349
67
0.68707
c119368b37fb8770844f1720b9f083ae00997d1e
1,926
/* * Copyright 2007 skynamics AG * * 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.openbp.jaspira.event; import org.openbp.jaspira.plugin.Plugin; /** * Event that provides the recepients with the capability to insert a * specific answer via the setAnswer mehtod. If this happens, the event counts as consumed. * * @author Stephan Moritz */ public class AskEvent extends JaspiraEvent { /** The answer to the request. */ private Object answer; /** * Constructor. * @param source The plugin that dispatches this event. Must not be null. * Will be converted to lower case. * @param eventName The name of the event */ public AskEvent(Plugin source, String eventName) { super(source, eventName); } /** * Constructor. * @param source The plugin that dispatches this event. Must not be null. * Will be converted to lower case. * @param eventName The name of the event * @param object An additional data object. Can be null. */ public AskEvent(Plugin source, String eventName, Object object) { super(source, eventName, object); } /** * Returns the answer. * @nowarn */ public Object getAnswer() { return answer; } /** * Sets the answer. * @nowarn */ public void setAnswer(Object answer) { this.answer = answer; this.updateFlags(CONSUMED); } }
26.027027
92
0.675493
4ab6c48d63d7c1d8c7caf5161a5c32fb186ce639
6,317
//package fi.csc.chipster.toolbox; // //import java.io.IOException; //import java.util.Arrays; // //import jakarta.jms.JMSException; //import jakarta.xml.parsers.ParserConfigurationException; // //import org.apache.logging.log4j.LogManager; //import org.apache.logging.log4j.Logger; //import org.xml.sax.SAXException; // //import fi.csc.microarray.config.Configuration; //import fi.csc.microarray.config.DirectoryLayout; //import fi.csc.microarray.constants.ApplicationConstants; //import fi.csc.microarray.messaging.JMSMessagingEndpoint; //import fi.csc.microarray.messaging.MessagingEndpoint; //import fi.csc.microarray.messaging.MessagingListener; //import fi.csc.microarray.messaging.MessagingTopic; //import fi.csc.microarray.messaging.MessagingTopic.AccessMode; //import fi.csc.microarray.messaging.MonitoredNodeBase; //import fi.csc.microarray.messaging.Topics; //import fi.csc.microarray.messaging.message.ChipsterMessage; //import fi.csc.microarray.messaging.message.CommandMessage; //import fi.csc.microarray.messaging.message.ModuleDescriptionMessage; //import fi.csc.microarray.messaging.message.SourceMessage; //import fi.csc.microarray.service.KeepAliveShutdownHandler; //import fi.csc.microarray.service.ShutdownCallback; //import fi.csc.microarray.util.SystemMonitorUtil; // //public class ToolboxServer extends MonitoredNodeBase implements MessagingListener, ShutdownCallback { // // private Logger logger = LogManager.getLogger(); // // private MessagingEndpoint endpoint; // private ToolboxService toolboxRestService; // // public ToolboxServer(String configURL) throws Exception { // // // get configs // DirectoryLayout.initialiseServerLayout(Arrays.asList(new String[] { "toolbox" }), configURL); // Configuration configuration = DirectoryLayout.getInstance().getConfiguration(); // // // init logger // logger.info("starting toolbox service..."); // // String url = configuration.getString("messaging", "toolbox-url"); // String toolsBinPath = configuration.getString("toolbox", "tools-bin-path"); // // this.toolboxRestService = new ToolboxService(url, toolsBinPath); // this.toolboxRestService.startServerWithoutStatsAndAdminServer(); // // // initialize communications // this.endpoint = new JMSMessagingEndpoint(this); // MessagingTopic compTopic = endpoint.createTopic(Topics.Name.TOOLBOX_TOPIC, AccessMode.READ); // compTopic.setListener(this); // // // create keep-alive thread and register shutdown hook // KeepAliveShutdownHandler.init(this); // // logger.info("toolbox is up and running [" + ApplicationConstants.VERSION + "]"); // logger.info("[mem: " + SystemMonitorUtil.getMemInfo() + "]"); // } // // @Override // public void onChipsterMessage(ChipsterMessage chipsterMessage) { // // // expect only command messages // if (chipsterMessage instanceof CommandMessage) { // CommandMessage commandMessage = (CommandMessage) chipsterMessage; // // // Request to send descriptions // if (CommandMessage.COMMAND_DESCRIBE.equals(commandMessage.getCommand())) { // try { // handleGetDescriptions(commandMessage); // } catch (Exception e) { // logger.error("sending descriptions messages failed", e); // } // return; // } // // // source code request // else if (CommandMessage.COMMAND_GET_SOURCE.equals(commandMessage.getCommand())) { // handleGetSourceCode(commandMessage); // return; // } // // // unknown command message // else { // logger.warn("unexpected command message: " + commandMessage.getCommand()); // } // } // // // unknown message (something else than command message) // else { // logger.warn("expecting a command message, got something else: " + chipsterMessage.getMessageID() + " " // + chipsterMessage.getClass()); // } // // } // // @Override // public String getName() { // return "toolbox"; // } // // @Override // public void shutdown() { // logger.info("shutdown requested"); // // // close toolbox rest // try { // this.toolboxRestService.close(); // } catch (Exception e) { // logger.warn("closing toolbox rest service failed", e); // } // // // close jms messaging endpoint // try { // this.endpoint.close(); // } catch (Exception e) { // logger.warn("closing messaging endpoint failed", e); // } // // logger.info("shutting down"); // } // // private void handleGetSourceCode(CommandMessage requestMessage) { // String toolID = new String(requestMessage.getParameters().get(0)); // if (toolID == null || toolID.isEmpty()) { // logger.warn("invalid source code request, tool id is: " + toolID); // return; // } // // ToolboxTool tool = toolboxRestService.getToolbox().getTool(toolID); // // if (tool != null) { // // getSource() would return the original file without SADL replacements // String source = tool.getSadlString() + tool.getCode(); // // logger.info("sending source code for " + toolID); // SourceMessage sourceMessage = new SourceMessage(source); // if (sourceMessage != null) { // sendReplyMessage(requestMessage, sourceMessage); // return; // } // } else { // logger.warn("tool " + toolID + " not found"); // } // } // // private void handleGetDescriptions(CommandMessage requestMessage) // throws IOException, SAXException, ParserConfigurationException { // logger.info("sending all descriptions"); // // for (ModuleDescriptionMessage descriptionMessage : toolboxRestService.getToolbox().getModuleDescriptions()) { // descriptionMessage.setReplyTo(requestMessage.getReplyTo()); // logger.info("sending descriptions for module " + descriptionMessage.getModuleName()); // sendReplyMessage(requestMessage, descriptionMessage); // // } // } // // /** // * Sends the message in new thread. // */ // private void sendReplyMessage(final ChipsterMessage original, final ChipsterMessage reply) { // // reply.setReplyTo(original.getReplyTo()); // // new Thread(new Runnable() { // public void run() { // try { // endpoint.replyToMessage(original, reply); // } catch (JMSException e) { // // Failing is ok, if some other comp has replied quicker and // // the TempTopic has already been deleted // // logger.error("Could not send message.", e); // } // } // }).start(); // } // // public static void main(String[] args) throws Exception { // new ToolboxServer(null); // } //}
33.601064
113
0.707773
16ccb4cd1ff6234c6c585550c4f5ac40b3a738ee
3,923
package com.parser; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import com.common.Config; import com.common.KeyDefine; import com.common.Utility; import com.database.FundDatabaseHandler; public class OTCFundParserHandler extends BaseParserHandler { public OTCFundParserHandler() throws SQLException { super(); mDownloadName = Config.DataAnalyze.downloadName[KeyDefine.OTC_FUND] + "_"; mStockDB = new FundDatabaseHandler(); } public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub OTCFundParserHandler techParser = new OTCFundParserHandler(); techParser.parseAllFileData(); } @Override boolean parseFileData(File aFile, String aDate) { // TODO Auto-generated method stub int mLines = 0; String mTmpLine = ""; String[] mStrArr; try { // csv file need to set decode as MS950 to prevent garbled InputStreamReader mStreamReader = new InputStreamReader(new FileInputStream(aFile), "MS950"); mBufferReader = new BufferedReader(mStreamReader); try { while ((mTmpLine = mBufferReader.readLine()) != null) { if (mTmpLine.contains("管理股票")) { break; } mLines++; if (mLines >= 3) { mStrArr = Utility.removeMessyChar(mTmpLine).split(","); if (mStrArr.length < 5 || mStrArr[0].length() != 4 || mStrArr[0].equals("股票代號")) { // filter 非股票部分(權證) } else { // 代號0,名稱1,本益比2 ,股利3,殖利率4 ,淨值比5 //System.out.printf("代號:%s, 本益比:%s, 殖利率:%s,淨值比:%s\n",mStrArr[0], mStrArr[2], mStrArr[4], mStrArr[5]); try { writeData2DB(aDate, mStrArr); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } mBufferReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } @Override boolean writeData2DB(String aDate, String[] aStrArr) throws SQLException { // TODO Auto-generated method stub //mStockDB.generateSqlPrepareIntCmd(8, Config.DataAnalyze.TWSE); // stock_type //System.out.printf("代號:%s, 本益比:%s, 殖利率:%s,淨值比:%s\n",aStrArr[0], aStrArr[2], aStrArr[4], aStrArr[5]); mStockDB.generateSqlPrepareStrCmd(1, aStrArr[0]); // stock_id mStockDB.generateSqlPrepareStrCmd(2, aDate); // stock_date mStockDB.generateSqlPrepareIntCmd(3, Utility.float2Int(aStrArr[4], 2)); // stock_yield_rate mStockDB.generateSqlPrepareIntCmd(4, Utility.float2Int(aStrArr[2], 2)); // stock_pbr mStockDB.generateSqlPrepareIntCmd(5, Utility.float2Int(aStrArr[5], 2)); // stock_per mStockDB.generateSqlPrepareIntCmd(6, KeyDefine.OTC_FUND + 1); // stock_type mStockDB.addSqlPrepareCmd2Batch(); return true; } }
40.864583
131
0.559266
3381de294cd6d69c8212c8de98c60bd4db3e8d34
62,831
/* * Copyright (C) 2019 Alberto Irurueta Carro ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irurueta.navigation.frames; import com.irurueta.algebra.Matrix; import com.irurueta.algebra.WrongSizeException; import com.irurueta.geometry.InhomogeneousPoint3D; import com.irurueta.geometry.InvalidRotationMatrixException; import com.irurueta.geometry.Point3D; import com.irurueta.geometry.Quaternion; import com.irurueta.navigation.SerializationHelper; import com.irurueta.navigation.geodesic.Constants; import com.irurueta.statistics.UniformRandomizer; import com.irurueta.units.Distance; import com.irurueta.units.DistanceUnit; import com.irurueta.units.Speed; import com.irurueta.units.SpeedUnit; import org.junit.Test; import java.io.IOException; import java.util.Random; import static org.junit.Assert.*; public class ECIFrameTest { private static final double THRESHOLD = 1e-6; private static final double MIN_ANGLE_DEGREES = -45.0; private static final double MAX_ANGLE_DEGREES = 45.0; private static final double MIN_POSITION_VALUE = Constants.EARTH_EQUATORIAL_RADIUS_WGS84 - 50.0; private static final double MAX_POSITION_VALUE = Constants.EARTH_EQUATORIAL_RADIUS_WGS84 + 50.0; private static final double MIN_VELOCITY_VALUE = -2.0; private static final double MAX_VELOCITY_VALUE = 2.0; private static final double ABSOLUTE_ERROR = 1e-8; @Test public void testConstants() { assertEquals(ECIFrame.NUM_POSITION_COORDINATES, 3); assertEquals(ECIFrame.NUM_VELOCITY_COORDINATES, 3); } @Test public void testConstructor() throws WrongSizeException, InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { ECIFrame frame = new ECIFrame(); // check assertEquals(frame.getX(), 0.0, 0.0); assertEquals(frame.getY(), 0.0, 0.0); assertEquals(frame.getZ(), 0.0, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); assertNotNull(frame.getCoordinateTransformation()); CoordinateTransformation c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with coordinate transformation matrix final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c1 = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); frame = new ECIFrame(c1); // check assertEquals(frame.getX(), 0.0, 0.0); assertEquals(frame.getY(), 0.0, 0.0); assertEquals(frame.getZ(), 0.0, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); CoordinateTransformation c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with cartesian position coordinates final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); frame = new ECIFrame(x, y, z); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with position final Point3D position = new InhomogeneousPoint3D(x, y, z); frame = new ECIFrame(position); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with position coordinates final Distance positionX = new Distance(x, DistanceUnit.METER); final Distance positionY = new Distance(y, DistanceUnit.METER); final Distance positionZ = new Distance(z, DistanceUnit.METER); frame = new ECIFrame(positionX, positionY, positionZ); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with cartesian position and velocity coordinates final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); frame = new ECIFrame(x, y, z, vx, vy, vz); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with position and velocity coordinates frame = new ECIFrame(position, vx, vy, vz); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with position and speed coordinates final Speed speedX = new Speed(vx, SpeedUnit.METERS_PER_SECOND); final Speed speedY = new Speed(vy, SpeedUnit.METERS_PER_SECOND); final Speed speedZ = new Speed(vz, SpeedUnit.METERS_PER_SECOND); frame = new ECIFrame(position, speedX, speedY, speedZ); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with cartesian position coordinates and speed coordinates frame = new ECIFrame(x, y, z, speedX, speedY, speedZ); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with position and velocity coordinates frame = new ECIFrame(positionX, positionY, positionZ, vx, vy, vz); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with position and speed coordinates frame = new ECIFrame(positionX, positionY, positionZ, speedX, speedY, speedZ); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); assertNotNull(frame.getCoordinateTransformation()); c = frame.getCoordinateTransformation(); assertEquals(c.getSourceType(), FrameType.BODY_FRAME); assertEquals(c.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c.getMatrix(), Matrix.identity(3, 3)); // test constructor with cartesian position coordinates and coordinate transformation matrix frame = new ECIFrame(x, y, z, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(x, y, z, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with position and coordinate transformation matrix frame = new ECIFrame(position, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(position, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with position coordinates and coordinate transformation matrix frame = new ECIFrame(positionX, positionY, positionZ, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(positionX, positionY, positionZ, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with cartesian position and velocity coordinates, and with coordinate transformation matrix frame = new ECIFrame(x, y, z, vx, vy, vz, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(x, y, z, vx, vy, vz, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with position, velocity coordinates, and coordinate transformation matrix frame = new ECIFrame(position, vx, vy, vz, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(position, vx, vy, vz, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with position, speed coordinates and coordinate transformation matrix frame = new ECIFrame(position, speedX, speedY, speedZ, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(position, speedX, speedY, speedZ, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with cartesian coordinates, speed coordinates and coordinate transformation matrix frame = new ECIFrame(x, y, z, speedX, speedY, speedZ, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(x, y, z, speedX, speedY, speedZ, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (final InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with position coordinates, velocity coordinates and coordinates transformation matrix frame = new ECIFrame(positionX, positionY, positionZ, vx, vy, vz, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(positionX, positionY, positionZ, vx, vy, vz, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with position coordinates, speed coordinates and coordinate transformation matrix frame = new ECIFrame(positionX, positionY, positionZ, speedX, speedY, speedZ, c1); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); assertEquals(frame.getPositionX().getValue().doubleValue(), x, 0.0); assertEquals(frame.getPositionY().getValue().doubleValue(), y, 0.0); assertEquals(frame.getPositionZ().getValue().doubleValue(), z, 0.0); assertEquals(frame.getSpeedX().getValue().doubleValue(), vx, 0.0); assertEquals(frame.getSpeedY().getValue().doubleValue(), vy, 0.0); assertEquals(frame.getSpeedZ().getValue().doubleValue(), vz, 0.0); c2 = frame.getCoordinateTransformation(); assertEquals(c1, c2); // Force InvalidSourceAndDestinationFrameTypeException frame = null; try { frame = new ECIFrame(positionX, positionY, positionZ, speedX, speedY, speedZ, new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (InvalidSourceAndDestinationFrameTypeException ignore) { } assertNull(frame); // test constructor with another ECEF frame frame = new ECIFrame(x, y, z, vx, vy, vz, c1); final ECIFrame frame2 = new ECIFrame(frame); // check assertEquals(frame.getX(), frame2.getX(), 0.0); assertEquals(frame.getY(), frame2.getY(), 0.0); assertEquals(frame.getZ(), frame2.getZ(), 0.0); assertEquals(frame.getVx(), frame2.getVx(), 0.0); assertEquals(frame.getVy(), frame2.getVy(), 0.0); assertEquals(frame.getVz(), frame2.getVz(), 0.0); assertEquals(frame.getCoordinateTransformation(), frame2.getCoordinateTransformation()); } @Test public void testGetSetX() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getX(), 0.0, 0.0); // set new value frame.setX(x); // check assertEquals(frame.getX(), x, 0.0); } @Test public void testGetSetY() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getY(), 0.0, 0.0); // set new value frame.setY(y); // check assertEquals(frame.getY(), y, 0.0); } @Test public void testGetSetZ() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getZ(), 0.0, 0.0); // set new value frame.setZ(z); // check assertEquals(frame.getZ(), z, 0.0); } @Test public void testSetCoordinates() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial values assertEquals(frame.getX(), 0.0, 0.0); assertEquals(frame.getY(), 0.0, 0.0); assertEquals(frame.getZ(), 0.0, 0.0); // set new values frame.setCoordinates(x, y, z); // check assertEquals(frame.getX(), x, 0.0); assertEquals(frame.getY(), y, 0.0); assertEquals(frame.getZ(), z, 0.0); } @Test public void testGetSetPosition() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getPosition(), Point3D.create()); // set new value final Point3D position = new InhomogeneousPoint3D(x, y, z); frame.setPosition(position); // check assertEquals(frame.getPosition(), position); final Point3D position2 = new InhomogeneousPoint3D(); frame.getPosition(position2); assertEquals(position, position2); } @Test public void testGetSetPositionX() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getPositionX().getValue().doubleValue(), 0.0, 0.0); // set new value final Distance positionX1 = new Distance(x, DistanceUnit.METER); frame.setPositionX(positionX1); // check final Distance positionX2 = new Distance(0.0, DistanceUnit.CENTIMETER); frame.getPositionX(positionX2); final Distance positionX3 = frame.getPositionX(); assertEquals(positionX1, positionX2); assertEquals(positionX1, positionX3); } @Test public void testGetSetPositionY() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getPositionY().getValue().doubleValue(), 0.0, 0.0); // set new value final Distance positionY1 = new Distance(y, DistanceUnit.METER); frame.setPositionY(positionY1); // check final Distance positionY2 = new Distance(0.0, DistanceUnit.CENTIMETER); frame.getPositionY(positionY2); final Distance positionY3 = frame.getPositionY(); assertEquals(positionY1, positionY2); assertEquals(positionY1, positionY3); } @Test public void testGetSetPositionZ() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getPositionZ().getValue().doubleValue(), 0.0, 0.0); // set new value final Distance positionZ1 = new Distance(z, DistanceUnit.METER); frame.setPositionZ(positionZ1); // check final Distance positionZ2 = new Distance(0.0, DistanceUnit.CENTIMETER); frame.getPositionZ(positionZ2); final Distance positionZ3 = frame.getPositionZ(); assertEquals(positionZ1, positionZ2); assertEquals(positionZ1, positionZ3); } @Test public void testSetPositionCoordinates() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final Distance positionX = new Distance(x, DistanceUnit.METER); final Distance positionY = new Distance(y, DistanceUnit.METER); final Distance positionZ = new Distance(z, DistanceUnit.METER); final ECIFrame frame = new ECIFrame(); frame.setPositionCoordinates(positionX, positionY, positionZ); // check assertEquals(frame.getPositionX(), positionX); assertEquals(frame.getPositionY(), positionY); assertEquals(frame.getPositionZ(), positionZ); } @Test public void testGetPositionNorm() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double norm = Math.sqrt(Math.pow(x, 2.0) + Math.pow(y, 2.0) + Math.pow(z, 2.0)); final ECIFrame frame = new ECIFrame(x, y, z); assertEquals(frame.getPositionNorm(), norm, ABSOLUTE_ERROR); final Distance normDistance1 = new Distance(0.0, DistanceUnit.KILOMETER); frame.getPositionNormAsDistance(normDistance1); final Distance normDistance2 = frame.getPositionNormAsDistance(); assertEquals(normDistance1.getValue().doubleValue(), norm, ABSOLUTE_ERROR); assertEquals(normDistance1.getUnit(), DistanceUnit.METER); assertEquals(normDistance1, normDistance2); } @Test public void testGetSetVx() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getVx(), 0.0, 0.0); // set new value frame.setVx(vx); // check assertEquals(frame.getVx(), vx, 0.0); } @Test public void testGetSetVy() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getVy(), 0.0, 0.0); // set new value frame.setVy(vy); // check assertEquals(frame.getVy(), vy, 0.0); } @Test public void testGetSetVz() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getVz(), 0.0, 0.0); // set new value frame.setVz(vz); // check assertEquals(frame.getVz(), vz, 0.0); } @Test public void testSetVelocityCoordinates() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getVx(), 0.0, 0.0); assertEquals(frame.getVy(), 0.0, 0.0); assertEquals(frame.getVz(), 0.0, 0.0); // set new values frame.setVelocityCoordinates(vx, vy, vz); // check assertEquals(frame.getVx(), vx, 0.0); assertEquals(frame.getVy(), vy, 0.0); assertEquals(frame.getVz(), vz, 0.0); } @Test public void testGetVelocityNorm() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double norm = Math.sqrt(Math.pow(vx, 2.0) + Math.pow(vy, 2.0) + Math.pow(vz, 2.0)); final ECIFrame frame = new ECIFrame(); frame.setVelocityCoordinates(vx, vy, vz); assertEquals(frame.getVelocityNorm(), norm, ABSOLUTE_ERROR); final Speed normSpeed1 = new Speed(0.0, SpeedUnit.KILOMETERS_PER_HOUR); frame.getVelocityNormAsSpeed(normSpeed1); final Speed normSpeed2 = frame.getVelocityNormAsSpeed(); assertEquals(normSpeed1.getValue().doubleValue(), norm, ABSOLUTE_ERROR); assertEquals(normSpeed1.getUnit(), SpeedUnit.METERS_PER_SECOND); assertEquals(normSpeed1, normSpeed2); } @Test public void testGetSetSpeedX() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getSpeedX().getValue().doubleValue(), 0.0, 0.0); // set new value final Speed speedX1 = new Speed(vx, SpeedUnit.METERS_PER_SECOND); frame.setSpeedX(speedX1); // check final Speed speedX2 = new Speed(0.0, SpeedUnit.KILOMETERS_PER_HOUR); frame.getSpeedX(speedX2); final Speed speedX3 = frame.getSpeedX(); assertEquals(speedX1, speedX2); assertEquals(speedX1, speedX3); } @Test public void testGetSetSpeedY() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getSpeedY().getValue().doubleValue(), 0.0, 0.0); // set new value final Speed speedY1 = new Speed(vy, SpeedUnit.METERS_PER_SECOND); frame.setSpeedY(speedY1); // check final Speed speedY2 = new Speed(0.0, SpeedUnit.KILOMETERS_PER_HOUR); frame.getSpeedY(speedY2); final Speed speedY3 = frame.getSpeedY(); assertEquals(speedY1, speedY2); assertEquals(speedY1, speedY3); } @Test public void testGetSetSpeedZ() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final ECIFrame frame = new ECIFrame(); // check initial value assertEquals(frame.getSpeedZ().getValue().doubleValue(), 0.0, 0.0); // set new value final Speed speedZ1 = new Speed(vz, SpeedUnit.METERS_PER_SECOND); frame.setSpeedZ(speedZ1); // check final Speed speedZ2 = new Speed(0.0, SpeedUnit.KILOMETERS_PER_HOUR); frame.getSpeedZ(speedZ2); final Speed speedZ3 = frame.getSpeedZ(); assertEquals(speedZ1, speedZ2); assertEquals(speedZ1, speedZ3); } @Test public void testSetSpeedCoordinates() { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final Speed speedX = new Speed(vx, SpeedUnit.METERS_PER_SECOND); final Speed speedY = new Speed(vy, SpeedUnit.METERS_PER_SECOND); final Speed speedZ = new Speed(vz, SpeedUnit.METERS_PER_SECOND); final ECIFrame frame = new ECIFrame(); // set new values frame.setSpeedCoordinates(speedX, speedY, speedZ); // check assertEquals(frame.getSpeedX(), speedX); assertEquals(frame.getSpeedY(), speedY); assertEquals(frame.getSpeedZ(), speedZ); } @Test public void testGetSetCoordinateTransformation() throws WrongSizeException, InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final ECIFrame frame = new ECIFrame(); // check initial value final CoordinateTransformation c1 = frame.getCoordinateTransformation(); assertEquals(c1.getSourceType(), FrameType.BODY_FRAME); assertEquals(c1.getDestinationType(), FrameType.EARTH_CENTERED_INERTIAL_FRAME); assertEquals(c1.getMatrix(), Matrix.identity(3, 3)); // set new value final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c2 = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); frame.setCoordinateTransformation(c2); // check assertEquals(frame.getCoordinateTransformation(), c2); final CoordinateTransformation c3 = new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME); frame.getCoordinateTransformation(c3); assertEquals(c2, c3); // Force InvalidSourceAndDestinationFrameTypeException try { frame.setCoordinateTransformation(new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME)); fail("InvalidSourceAndDestinationFrameTypeException expected but not thrown"); } catch (InvalidSourceAndDestinationFrameTypeException ignore) { } } @Test public void testGetSetCoordinateTransformationMatrix() throws WrongSizeException, InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m1 = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m1, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame = new ECIFrame(c); // check assertEquals(frame.getCoordinateTransformationMatrix(), m1); final Matrix m2 = new Matrix(CoordinateTransformation.ROWS, CoordinateTransformation.COLS); frame.getCoordinateTransformationMatrix(m2); assertEquals(m2, m1); } @Test public void testIsValidCoordinateTransformation() { final CoordinateTransformation c1 = new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final CoordinateTransformation c2 = new CoordinateTransformation( FrameType.BODY_FRAME, FrameType.BODY_FRAME); final CoordinateTransformation c3 = new CoordinateTransformation( FrameType.LOCAL_NAVIGATION_FRAME, FrameType.LOCAL_NAVIGATION_FRAME); assertTrue(ECIFrame.isValidCoordinateTransformation(c1)); assertFalse(ECIFrame.isValidCoordinateTransformation(c2)); assertFalse(ECIFrame.isValidCoordinateTransformation(c3)); } @Test public void testCopyTo() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame2 = new ECIFrame(); frame1.copyTo(frame2); // check assertEquals(frame1.getX(), frame2.getX(), 0.0); assertEquals(frame1.getY(), frame2.getY(), 0.0); assertEquals(frame1.getZ(), frame2.getZ(), 0.0); assertEquals(frame1.getVx(), frame2.getVx(), 0.0); assertEquals(frame1.getVy(), frame2.getVy(), 0.0); assertEquals(frame1.getVz(), frame2.getVz(), 0.0); assertEquals(frame1.getCoordinateTransformation(), frame2.getCoordinateTransformation()); } @Test public void testCopyFrom() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame2 = new ECIFrame(); frame2.copyFrom(frame1); // check assertEquals(frame1.getX(), frame2.getX(), 0.0); assertEquals(frame1.getY(), frame2.getY(), 0.0); assertEquals(frame1.getZ(), frame2.getZ(), 0.0); assertEquals(frame1.getVx(), frame2.getVx(), 0.0); assertEquals(frame1.getVy(), frame2.getVy(), 0.0); assertEquals(frame1.getVz(), frame2.getVz(), 0.0); assertEquals(frame1.getCoordinateTransformation(), frame2.getCoordinateTransformation()); } @Test public void testHashCode() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame2 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame3 = new ECIFrame(); assertEquals(frame1.hashCode(), frame2.hashCode()); assertNotEquals(frame1.hashCode(), frame3.hashCode()); } @Test public void testEquals() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame2 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame3 = new ECIFrame(); //noinspection ConstantConditions,SimplifiableJUnitAssertion assertTrue(frame1.equals((Object) frame1)); //noinspection EqualsWithItself assertTrue(frame1.equals(frame1)); assertTrue(frame1.equals(frame2)); assertFalse(frame1.equals(frame3)); //noinspection ConstantConditions,SimplifiableJUnitAssertion assertFalse(frame1.equals((Object) null)); assertFalse(frame1.equals(null)); //noinspection SimplifiableJUnitAssertion assertFalse(frame1.equals(new Object())); } @Test public void testEqualsWithThreshold() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame2 = new ECIFrame(x, y, z, vx, vy, vz, c); final ECIFrame frame3 = new ECIFrame(); assertTrue(frame1.equals(frame1, THRESHOLD)); assertTrue(frame1.equals(frame2, THRESHOLD)); assertFalse(frame1.equals(frame3, THRESHOLD)); assertFalse(frame1.equals(null, THRESHOLD)); } @Test public void testClone() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException, CloneNotSupportedException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); final Object frame2 = frame1.clone(); assertEquals(frame1, frame2); } @Test public void testSerializeDeserialize() throws InvalidRotationMatrixException, InvalidSourceAndDestinationFrameTypeException, IOException, ClassNotFoundException { final UniformRandomizer randomizer = new UniformRandomizer(new Random()); final double x = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double y = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double z = randomizer.nextDouble(MIN_POSITION_VALUE, MAX_POSITION_VALUE); final double vx = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vy = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double vz = randomizer.nextDouble(MIN_VELOCITY_VALUE, MAX_VELOCITY_VALUE); final double roll = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double pitch = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final double yaw = Math.toRadians( randomizer.nextDouble(MIN_ANGLE_DEGREES, MAX_ANGLE_DEGREES)); final Quaternion q = new Quaternion(roll, pitch, yaw); final Matrix m = q.asInhomogeneousMatrix(); final CoordinateTransformation c = new CoordinateTransformation( m, FrameType.BODY_FRAME, FrameType.EARTH_CENTERED_INERTIAL_FRAME); final ECIFrame frame1 = new ECIFrame(x, y, z, vx, vy, vz, c); // serialize and deserialize final byte[] bytes = SerializationHelper.serialize(frame1); final ECIFrame frame2 = SerializationHelper.deserialize(bytes); // check assertEquals(frame1, frame2); assertNotSame(frame1, frame2); } }
41.527429
128
0.663797
185da7a7d3207ba4c9fa4f09c36034a938f7190c
259
package super_keyword04; public class Vehicle { String color; double weight; Vehicle(String c, double w){ color = c; weight = w; } void display(){ System.out.println("Color :"+color); System.out.println("Weight :"+weight); } }
11.26087
40
0.625483
c156728d8c4b4f2e7f178b35a24ce2aaaf0f4a93
115
package edu.anadolu.eval; /** * Enum for effectiveness measures */ public enum Metric { NDCG, ERR, MAP, P }
12.777778
34
0.66087
44370944e96d1abe3b0a8e8ad64a87c0ee05b762
2,911
package com.qa.ims.controller; import java.text.DecimalFormat; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.qa.ims.persistence.dao.ItemDAO; import com.qa.ims.persistence.domain.Item; import com.qa.ims.utils.PrintUtils; import com.qa.ims.utils.Utils; /** * Takes in item details for CRUD functionality * */ public class ItemController implements CrudController<Item> { public static final Logger LOGGER = LogManager.getLogger(); private ItemDAO itemDAO; private Utils utils; public ItemController(ItemDAO itemDAO, Utils utils) { super(); this.itemDAO = itemDAO; this.utils = utils; } /** * Reads all items to the logger */ @Override public List<Item> readAll() { List<Item> items = itemDAO.readAll(); LOGGER.info("Items: "); PrintUtils.printDottedLine(); for (Item item : items) { LOGGER.info(item); } PrintUtils.printLine(); return items; } /** * Creates a item by taking in user input */ @Override public Item create() { DecimalFormat df = new DecimalFormat("#.##"); LOGGER.info("Please enter an item name"); String item_name = utils.getString(); LOGGER.info("Please enter a price"); Double price = utils.getDouble(); price = Double.valueOf(df.format(price)); Item item = itemDAO.create(new Item(item_name, price)); LOGGER.info("Item Created"); PrintUtils.printDottedLine(); LOGGER.info(item); PrintUtils.printLine(); return item; } /** * Updates an existing item by taking in user input */ @Override public Item update() { DecimalFormat df = new DecimalFormat("#.##"); Item itemFound = getItem(); Long item_id = itemFound.getItemId(); LOGGER.info("Item Found: {}", itemFound); LOGGER.info("Please enter an updated item name"); String item_name = utils.getString(); LOGGER.info("Please enter an update price"); Double price = utils.getDouble(); price = Double.valueOf(df.format(price)); Item itemUpdated = itemDAO.update(new Item(item_id, item_name, price)); LOGGER.info("Item Updated"); PrintUtils.printDottedLine(); LOGGER.info(itemUpdated); PrintUtils.printLine(); return itemUpdated; } /** * Deletes an existing item by the id of the item * * @return */ @Override public int delete() { Item itemFound = getItem(); if(itemDAO.readLatest().equals(null)) { delete(); } Long item_id = itemFound.getItemId(); LOGGER.info("Item Deleted"); PrintUtils.printDottedLine(); PrintUtils.printLine(); return itemDAO.delete(item_id); } /** * Retrieves a customer using user input */ public Item getItem() { LOGGER.info("Please enter an item_id"); Long item_id = utils.getLong(); while(item_id > itemDAO.readLatest().getItemId() || item_id<1) { LOGGER.info("This is not a valid item_id. Please try again"); item_id = utils.getLong(); } return itemDAO.read(item_id); } }
24.462185
73
0.696324
c0217c85d6e6661a5f604791c3b7d6d547d8f359
40,672
package com.spark.blockchain.rpcclient; import com.alibaba.fastjson.JSONObject; import com.spark.blockchain.rpcclient.Bitcoin.AddNoteCmd; import com.spark.blockchain.rpcclient.Bitcoin.AddressValidationResult; import com.spark.blockchain.rpcclient.Bitcoin.BasicTxInput; import com.spark.blockchain.rpcclient.Bitcoin.Block; import com.spark.blockchain.rpcclient.Bitcoin.Info; import com.spark.blockchain.rpcclient.Bitcoin.MiningInfo; import com.spark.blockchain.rpcclient.Bitcoin.PeerInfo; import com.spark.blockchain.rpcclient.Bitcoin.RawTransaction; import com.spark.blockchain.rpcclient.Bitcoin.ReceivedAddress; import com.spark.blockchain.rpcclient.Bitcoin.Transaction; import com.spark.blockchain.rpcclient.Bitcoin.TransactionsSinceBlock; import com.spark.blockchain.rpcclient.Bitcoin.TxInput; import com.spark.blockchain.rpcclient.Bitcoin.TxOutSetInfo; import com.spark.blockchain.rpcclient.Bitcoin.TxOutput; import com.spark.blockchain.rpcclient.Bitcoin.Unspent; import com.spark.blockchain.rpcclient.Bitcoin.Work; import com.spark.blockchain.rpcclient.Bitcoin.RawTransaction.In; import com.spark.blockchain.rpcclient.Bitcoin.RawTransaction.Out; import com.spark.blockchain.rpcclient.Bitcoin.RawTransaction.Out.ScriptPubKey; import com.spark.blockchain.util.Base64Coder; import com.spark.blockchain.util.JSON; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; public class BitcoinRPCClient implements Bitcoin { private static final Logger logger = Logger.getLogger(BitcoinRPCClient.class.getCanonicalName()); public final URL rpcURL; private URL noAuthURL; private String authStr; private HostnameVerifier hostnameVerifier; private SSLSocketFactory sslSocketFactory; private int connectTimeout; public static final Charset QUERY_CHARSET = Charset.forName("UTF-8"); public BitcoinRPCClient(String rpcUrl) throws MalformedURLException { this(new URL(rpcUrl)); } public BitcoinRPCClient(URL rpc) { this.hostnameVerifier = null; this.sslSocketFactory = null; this.connectTimeout = 0; this.rpcURL = rpc; try { this.noAuthURL = (new URI(rpc.getProtocol(), (String)null, rpc.getHost(), rpc.getPort(), rpc.getPath(), rpc.getQuery(), (String)null)).toURL(); } catch (MalformedURLException var3) { throw new IllegalArgumentException(rpc.toString(), var3); } catch (URISyntaxException var4) { throw new IllegalArgumentException(rpc.toString(), var4); } this.authStr = rpc.getUserInfo() == null ? null : String.valueOf(Base64Coder.encode(rpc.getUserInfo().getBytes(Charset.forName("ISO8859-1")))); } public HostnameVerifier getHostnameVerifier() { return this.hostnameVerifier; } public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { this.hostnameVerifier = hostnameVerifier; } public SSLSocketFactory getSslSocketFactory() { return this.sslSocketFactory; } public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; } public void setConnectTimeout(int timeout) { if (timeout < 0) { throw new IllegalArgumentException("timeout can not be negative"); } else { this.connectTimeout = timeout; } } public int getConnectTimeout() { return this.connectTimeout; } public byte[] prepareRequest(final String method, final Object... params) { return JSON.stringify(new LinkedHashMap() { { this.put("method", method); this.put("params", params); this.put("id", "1"); } }).getBytes(QUERY_CHARSET); } private static byte[] loadStream(InputStream in, boolean close) throws IOException { ByteArrayOutputStream o = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while(true) { int nr = in.read(buffer); if (nr == -1) { return o.toByteArray(); } if (nr == 0) { throw new IOException("Read timed out"); } o.write(buffer, 0, nr); } } public Object loadResponse(InputStream in, Object expectedID, boolean close) throws IOException, BitcoinException { Object var6; try { String r = new String(loadStream(in, close), QUERY_CHARSET); logger.log(Level.FINE, "Bitcoin JSON-RPC response:\n{0}", r); try { JSONObject response = com.alibaba.fastjson.JSON.parseObject(r); if (!expectedID.equals(response.get("id"))) { throw new BitcoinRPCException("Wrong response ID (expected: " + String.valueOf(expectedID) + ", response: " + response.get("id") + ")"); } if (response.get("error") != null) { throw new BitcoinException(JSON.stringify(response.get("error"))); } var6 = response.get("result"); } catch (ClassCastException var10) { throw new BitcoinRPCException("Invalid server response format (data: \"" + r + "\")"); } } finally { if (close) { in.close(); } } return var6; } public Object query(String method, Object... o) throws BitcoinException { try { HttpURLConnection conn = (HttpURLConnection)this.noAuthURL.openConnection(); if (this.connectTimeout != 0) { conn.setConnectTimeout(this.connectTimeout); } conn.setDoOutput(true); conn.setDoInput(true); if (conn instanceof HttpsURLConnection) { if (this.hostnameVerifier != null) { ((HttpsURLConnection)conn).setHostnameVerifier(this.hostnameVerifier); } if (this.sslSocketFactory != null) { ((HttpsURLConnection)conn).setSSLSocketFactory(this.sslSocketFactory); } } conn.setRequestProperty("Authorization", "Basic " + this.authStr); byte[] r = this.prepareRequest(method, o); logger.log(Level.FINE, "Bitcoin JSON-RPC request:\n{0}", new String(r, QUERY_CHARSET)); conn.getOutputStream().write(r); conn.getOutputStream().close(); int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new BitcoinRPCException("RPC Query Failed (method: " + method + ", params: " + Arrays.deepToString(o) + ", response header: " + responseCode + " " + conn.getResponseMessage() + ", response: " + new String(loadStream(conn.getErrorStream(), true))); } else { return this.loadResponse(conn.getInputStream(), "1", true); } } catch (IOException var6) { throw new BitcoinRPCException("RPC Query Failed (method: " + method + ", params: " + Arrays.deepToString(o) + ")", var6); } } public void addNode(String node, AddNoteCmd command) throws BitcoinException { this.query("addnode", node, command.toString()); } public String createRawTransaction(List<TxInput> inputs, List<TxOutput> outputs) throws BitcoinException { List<Map> pInputs = new ArrayList(); Iterator var4 = inputs.iterator(); while(var4.hasNext()) { final TxInput txInput = (TxInput)var4.next(); pInputs.add(new LinkedHashMap() { { this.put("txid", txInput.txid()); this.put("vout", txInput.vout()); } }); } Map<String, BigDecimal> pOutputs = new LinkedHashMap(); Iterator var6 = outputs.iterator(); while(var6.hasNext()) { TxOutput txOutput = (TxOutput)var6.next(); BigDecimal oldValue; if ((oldValue = (BigDecimal)pOutputs.put(txOutput.address(), txOutput.amount())) != null) { pOutputs.put(txOutput.address(), oldValue.add(txOutput.amount())); } } return (String)this.query("createrawtransaction", pInputs, pOutputs); } public RawTransaction decodeRawTransaction(String hex) throws BitcoinException { return new BitcoinRPCClient.RawTransactionImpl((Map)this.query("decoderawtransaction", hex)); } public String dumpPrivKey(String address) throws BitcoinException { return (String)this.query("dumpprivkey", address); } public String getAccount(String address) throws BitcoinException { return (String)this.query("getaccount", address); } public String getAccountAddress(String account) throws BitcoinException { return (String)this.query("getaccountaddress", account); } public List<String> getAddressesByAccount(String account) throws BitcoinException { return (List)this.query("getaddressesbyaccount", account); } public double getBalance() throws BitcoinException { return ((Number)this.query("getbalance")).doubleValue(); } public double getBalance(String account) throws BitcoinException { return ((Number)this.query("getbalance", account)).doubleValue(); } public double getBalance(String account, int minConf) throws BitcoinException { return ((Number)this.query("getbalance", account, minConf)).doubleValue(); } public Block getBlock(String blockHash) throws BitcoinException { return new BitcoinRPCClient.BlockMapWrapper((Map)this.query("getblock", blockHash)); } public int getBlockCount() throws BitcoinException { return ((Number)this.query("getblockcount")).intValue(); } public String getBlockHash(int blockId) throws BitcoinException { return (String)this.query("getblockhash", blockId); } public int getConnectionCount() throws BitcoinException { return ((Number)this.query("getconnectioncount")).intValue(); } public double getDifficulty() throws BitcoinException { return ((Number)this.query("getdifficulty")).doubleValue(); } public boolean getGenerate() throws BitcoinException { return (Boolean)this.query("getgenerate"); } public double getHashesPerSec() throws BitcoinException { return ((Number)this.query("gethashespersec")).doubleValue(); } public Info getInfo() throws BitcoinException { return new BitcoinRPCClient.InfoMapWrapper((Map)this.query("getinfo")); } public MiningInfo getMiningInfo() throws BitcoinException { return new BitcoinRPCClient.MiningInfoMapWrapper((Map)this.query("getmininginfo")); } public String getNewAddress() throws BitcoinException { return (String)this.query("getnewaddress"); } public String getNewAddress(String account) throws BitcoinException { return (String)this.query("getnewaddress", account); } public PeerInfo getPeerInfo() throws BitcoinException { return new BitcoinRPCClient.PeerInfoMapWrapper((Map)this.query("getmininginfo")); } public String getRawTransactionHex(String txId) throws BitcoinException { return (String)this.query("getrawtransaction", txId); } public RawTransaction getRawTransaction(String txId) throws BitcoinException { return new BitcoinRPCClient.RawTransactionImpl((Map)this.query("getrawtransaction", txId, 1)); } public double getReceivedByAccount(String account) throws BitcoinException { return ((Number)this.query("getreceivedbyaccount", account)).doubleValue(); } public double getReceivedByAccount(String account, int minConf) throws BitcoinException { return ((Number)this.query("getreceivedbyaccount", account, minConf)).doubleValue(); } public double getReceivedByAddress(String address) throws BitcoinException { return ((Number)this.query("getreceivedbyaddress", address)).doubleValue(); } public double getReceivedByAddress(String address, int minConf) throws BitcoinException { return ((Number)this.query("getreceivedbyaddress", address, minConf)).doubleValue(); } public RawTransaction getTransaction(String txId) throws BitcoinException { return new BitcoinRPCClient.RawTransactionImpl((Map)this.query("gettransaction", txId)); } public TxOutSetInfo getTxOutSetInfo() throws BitcoinException { final Map txoutsetinfoResult = (Map)this.query("gettxoutsetinfo"); return new TxOutSetInfo() { public int height() { return ((Number)txoutsetinfoResult.get("height")).intValue(); } public String bestBlock() { return (String)txoutsetinfoResult.get("bestblock"); } public int transactions() { return ((Number)txoutsetinfoResult.get("transactions")).intValue(); } public int txOuts() { return ((Number)txoutsetinfoResult.get("txouts")).intValue(); } public int bytesSerialized() { return ((Number)txoutsetinfoResult.get("bytes_serialized")).intValue(); } public String hashSerialized() { return (String)txoutsetinfoResult.get("hash_serialized"); } public double totalAmount() { return ((Number)txoutsetinfoResult.get("total_amount")).doubleValue(); } public String toString() { return txoutsetinfoResult.toString(); } }; } public Work getWork() throws BitcoinException { final Map workResult = (Map)this.query("getwork"); return new Work() { public String midstate() { return (String)workResult.get("midstate"); } public String data() { return (String)workResult.get("data"); } public String hash1() { return (String)workResult.get("hash1"); } public String target() { return (String)workResult.get("target"); } public String toString() { return workResult.toString(); } }; } public void importPrivKey(String bitcoinPrivKey) throws BitcoinException { this.query("importprivkey", bitcoinPrivKey); } public void importPrivKey(String bitcoinPrivKey, String label) throws BitcoinException { this.query("importprivkey", bitcoinPrivKey, label); } public void importPrivKey(String bitcoinPrivKey, String label, boolean rescan) throws BitcoinException { this.query("importprivkey", bitcoinPrivKey, label, rescan); } public Map<String, Number> listAccounts() throws BitcoinException { return (Map)this.query("listaccounts"); } public Map<String, Number> listAccounts(int minConf) throws BitcoinException { return (Map)this.query("listaccounts", minConf); } public List<ReceivedAddress> listReceivedByAccount() throws BitcoinException { return new BitcoinRPCClient.ReceivedAddressListWrapper((List)this.query("listreceivedbyaccount")); } public List<ReceivedAddress> listReceivedByAccount(int minConf) throws BitcoinException { return new BitcoinRPCClient.ReceivedAddressListWrapper((List)this.query("listreceivedbyaccount", minConf)); } public List<ReceivedAddress> listReceivedByAccount(int minConf, boolean includeEmpty) throws BitcoinException { return new BitcoinRPCClient.ReceivedAddressListWrapper((List)this.query("listreceivedbyaccount", minConf, includeEmpty)); } public List<ReceivedAddress> listReceivedByAddress() throws BitcoinException { return new BitcoinRPCClient.ReceivedAddressListWrapper((List)this.query("listreceivedbyaddress")); } public List<ReceivedAddress> listReceivedByAddress(int minConf) throws BitcoinException { return new BitcoinRPCClient.ReceivedAddressListWrapper((List)this.query("listreceivedbyaddress", minConf)); } public List<ReceivedAddress> listReceivedByAddress(int minConf, boolean includeEmpty) throws BitcoinException { return new BitcoinRPCClient.ReceivedAddressListWrapper((List)this.query("listreceivedbyaddress", minConf, includeEmpty)); } public TransactionsSinceBlock listSinceBlock() throws BitcoinException { return new BitcoinRPCClient.TransactionsSinceBlockImpl((Map)this.query("listsinceblock")); } public TransactionsSinceBlock listSinceBlock(String blockHash) throws BitcoinException { return new BitcoinRPCClient.TransactionsSinceBlockImpl((Map)this.query("listsinceblock", blockHash)); } public TransactionsSinceBlock listSinceBlock(String blockHash, int targetConfirmations) throws BitcoinException { return new BitcoinRPCClient.TransactionsSinceBlockImpl((Map)this.query("listsinceblock", blockHash, targetConfirmations)); } public List<Transaction> listTransactions() throws BitcoinException { return new BitcoinRPCClient.TransactionListMapWrapper((List)this.query("listtransactions")); } public List<Transaction> listTransactions(String account) throws BitcoinException { return new BitcoinRPCClient.TransactionListMapWrapper((List)this.query("listtransactions", account)); } public List<Transaction> listTransactions(String account, int count) throws BitcoinException { return new BitcoinRPCClient.TransactionListMapWrapper((List)this.query("listtransactions", account, count)); } public List<Transaction> listTransactions(String account, int count, int from) throws BitcoinException { return new BitcoinRPCClient.TransactionListMapWrapper((List)this.query("listtransactions", account, count, from)); } public List<Unspent> listUnspent() throws BitcoinException { return new BitcoinRPCClient.UnspentListWrapper((List)this.query("listunspent")); } public List<Unspent> listUnspent(int minConf) throws BitcoinException { return new BitcoinRPCClient.UnspentListWrapper((List)this.query("listunspent", minConf)); } public List<Unspent> listUnspent(int minConf, int maxConf) throws BitcoinException { return new BitcoinRPCClient.UnspentListWrapper((List)this.query("listunspent", minConf, maxConf)); } public List<Unspent> listUnspent(int minConf, int maxConf, String... addresses) throws BitcoinException { return new BitcoinRPCClient.UnspentListWrapper((List)this.query("listunspent", minConf, maxConf, addresses)); } public String sendFrom(String fromAccount, String toBitcoinAddress, double amount) throws BitcoinException { return (String)this.query("sendfrom", fromAccount, toBitcoinAddress, amount); } public String sendFrom(String fromAccount, String toBitcoinAddress, double amount, int minConf) throws BitcoinException { return (String)this.query("sendfrom", fromAccount, toBitcoinAddress, amount, minConf); } public String sendFrom(String fromAccount, String toBitcoinAddress, double amount, int minConf, String comment) throws BitcoinException { return (String)this.query("sendfrom", fromAccount, toBitcoinAddress, amount, minConf, comment); } public String sendFrom(String fromAccount, String toBitcoinAddress, double amount, int minConf, String comment, String commentTo) throws BitcoinException { return (String)this.query("sendfrom", fromAccount, toBitcoinAddress, amount, minConf, comment, commentTo); } public String sendMany(String fromAccount, List<TxOutput> outputs) throws BitcoinException { Map<String, BigDecimal> pOutputs = new LinkedHashMap(); Iterator var5 = outputs.iterator(); while(var5.hasNext()) { TxOutput txOutput = (TxOutput)var5.next(); BigDecimal oldValue; if ((oldValue = (BigDecimal)pOutputs.put(txOutput.address(), txOutput.amount())) != null) { pOutputs.put(txOutput.address(), oldValue.add(txOutput.amount())); } } return (String)this.query("sendmany", fromAccount, pOutputs); } public String sendMany(String fromAccount, List<TxOutput> outputs, int minConf) throws BitcoinException { Map<String, BigDecimal> pOutputs = new LinkedHashMap(); Iterator var6 = outputs.iterator(); while(var6.hasNext()) { TxOutput txOutput = (TxOutput)var6.next(); BigDecimal oldValue; if ((oldValue = (BigDecimal)pOutputs.put(txOutput.address(), txOutput.amount())) != null) { pOutputs.put(txOutput.address(), oldValue.add(txOutput.amount())); } } return (String)this.query("sendmany", fromAccount, pOutputs, minConf); } public String sendMany(String fromAccount, List<TxOutput> outputs, int minConf, String comment) throws BitcoinException { Map<String, BigDecimal> pOutputs = new LinkedHashMap(); Iterator var7 = outputs.iterator(); while(var7.hasNext()) { TxOutput txOutput = (TxOutput)var7.next(); BigDecimal oldValue; if ((oldValue = (BigDecimal)pOutputs.put(txOutput.address(), txOutput.amount())) != null) { pOutputs.put(txOutput.address(), oldValue.add(txOutput.amount())); } } return (String)this.query("sendmany", fromAccount, pOutputs, minConf, comment); } public String sendRawTransaction(String hex) throws BitcoinException { return (String)this.query("sendrawtransaction", hex); } public String sendToAddress(String toAddress, double amount) throws BitcoinException { return (String)this.query("sendtoaddress", toAddress, amount); } public String sendToAddress(String toAddress, double amount, String comment) throws BitcoinException { return (String)this.query("sendtoaddress", toAddress, amount, comment); } public Boolean setTxFee(double amount) throws BitcoinException { return (Boolean)this.query("settxfee", amount); } public String sendToAddress(String toAddress, double amount, String comment, String commentTo) throws BitcoinException { return (String)this.query("sendtoaddress", toAddress, amount, comment, commentTo); } public String signMessage(String address, String message) throws BitcoinException { return (String)this.query("signmessage", address, message); } public String signRawTransaction(String hex) throws BitcoinException { Map result = (Map)this.query("signrawtransaction", hex); if ((Boolean)result.get("complete")) { return (String)result.get("hex"); } else { throw new BitcoinException("Incomplete"); } } public void stop() throws BitcoinException { this.query("stop"); } public AddressValidationResult validateAddress(String address) throws BitcoinException { final Map validationResult = (Map)this.query("validateaddress", address); return new AddressValidationResult() { public boolean isValid() { return (Boolean)validationResult.get("isvalid"); } public String address() { return (String)validationResult.get("address"); } public boolean isMine() { return (Boolean)validationResult.get("ismine"); } public boolean isScript() { return (Boolean)validationResult.get("isscript"); } public String pubKey() { return (String)validationResult.get("pubkey"); } public boolean isCompressed() { return (Boolean)validationResult.get("iscompressed"); } public String account() { return (String)validationResult.get("account"); } public String toString() { return validationResult.toString(); } }; } public boolean verifyMessage(String address, String signature, String message) throws BitcoinException { return (Boolean)this.query("verifymessage", address, signature, message); } private class UnspentListWrapper extends ListMapWrapper<Unspent> { public UnspentListWrapper(List<Map> list) { super(list); } protected Unspent wrap(final Map m) { return new Unspent() { public String txid() { return MapWrapper.mapStr(m, "txid"); } public int vout() { return MapWrapper.mapInt(m, "vout"); } public String address() { return MapWrapper.mapStr(m, "address"); } public String scriptPubKey() { return MapWrapper.mapStr(m, "scriptPubKey"); } public String account() { return MapWrapper.mapStr(m, "account"); } public BigDecimal amount() { return MapWrapper.mapBigDecimal(m, "amount"); } public int confirmations() { return MapWrapper.mapInt(m, "confirmations"); } }; } } private class TransactionsSinceBlockImpl implements TransactionsSinceBlock { public final List<Transaction> transactions; public final String lastBlock; public TransactionsSinceBlockImpl(Map r) { this.transactions = BitcoinRPCClient.this.new TransactionListMapWrapper((List)r.get("transactions")); this.lastBlock = (String)r.get("lastblock"); } public List<Transaction> transactions() { return this.transactions; } public String lastBlock() { return this.lastBlock; } } private class TransactionListMapWrapper extends ListMapWrapper<Transaction> { public TransactionListMapWrapper(List<Map> list) { super(list); } protected Transaction wrap(final Map m) { return new Transaction() { private RawTransaction raw = null; public String account() { return MapWrapper.mapStr(m, "account"); } public String address() { return MapWrapper.mapStr(m, "address"); } public String category() { return MapWrapper.mapStr(m, "category"); } public double amount() { return MapWrapper.mapDouble(m, "amount"); } public double fee() { return MapWrapper.mapDouble(m, "fee"); } public int confirmations() { return MapWrapper.mapInt(m, "confirmations"); } public String blockHash() { return MapWrapper.mapStr(m, "blockhash"); } public int blockIndex() { return MapWrapper.mapInt(m, "blockindex"); } public Date blockTime() { return MapWrapper.mapCTime(m, "blocktime"); } public String txId() { return MapWrapper.mapStr(m, "txid"); } public Date time() { return MapWrapper.mapCTime(m, "time"); } public Date timeReceived() { return MapWrapper.mapCTime(m, "timereceived"); } public String comment() { return MapWrapper.mapStr(m, "comment"); } public String commentTo() { return MapWrapper.mapStr(m, "to"); } public RawTransaction raw() { if (this.raw == null) { try { this.raw = BitcoinRPCClient.this.getRawTransaction(this.txId()); } catch (BitcoinException var2) { throw new RuntimeException(var2); } } return this.raw; } public String toString() { return m.toString(); } }; } } private static class ReceivedAddressListWrapper extends AbstractList<ReceivedAddress> { private final List<Map<String, Object>> wrappedList; public ReceivedAddressListWrapper(List<Map<String, Object>> wrappedList) { this.wrappedList = wrappedList; } public ReceivedAddress get(int index) { final Map<String, Object> e = (Map)this.wrappedList.get(index); return new ReceivedAddress() { public String address() { return (String)e.get("address"); } public String account() { return (String)e.get("account"); } public double amount() { return ((Number)e.get("amount")).doubleValue(); } public int confirmations() { return ((Number)e.get("confirmations")).intValue(); } public String toString() { return e.toString(); } }; } public int size() { return this.wrappedList.size(); } } private class RawTransactionImpl extends MapWrapper implements RawTransaction { public RawTransactionImpl(Map<String, Object> tx) { super(tx); } public String hex() { return this.mapStr("hex"); } public String txId() { return this.mapStr("txid"); } public int version() { return this.mapInt("version"); } public long lockTime() { return this.mapLong("locktime"); } public List<In> vIn() { final List<Map<String, Object>> vIn = (List)this.m.get("vin"); return new AbstractList<In>() { public In get(int index) { return RawTransactionImpl.this.new InImpl((Map)vIn.get(index)); } public int size() { return vIn.size(); } }; } public List<Out> vOut() { final List<Map<String, Object>> vOut = (List)this.m.get("vout"); return new AbstractList<Out>() { public Out get(int index) { return RawTransactionImpl.this.new OutImpl((Map)vOut.get(index)); } public int size() { return vOut.size(); } }; } public String blockHash() { return this.mapStr("blockhash"); } public int confirmations() { return this.mapInt("confirmations"); } public Date time() { return this.mapCTime("time"); } public Date blocktime() { return this.mapCTime("blocktime"); } private class OutImpl extends MapWrapper implements Out { public OutImpl(Map m) { super(m); } public double value() { return this.mapDouble("value"); } public int n() { return this.mapInt("n"); } public ScriptPubKey scriptPubKey() { return new BitcoinRPCClient.RawTransactionImpl.OutImpl.ScriptPubKeyImpl((Map)this.m.get("scriptPubKey")); } public TxInput toInput() { return new BasicTxInput(this.transaction().txId(), this.n()); } public RawTransaction transaction() { return RawTransactionImpl.this; } private class ScriptPubKeyImpl extends MapWrapper implements ScriptPubKey { public ScriptPubKeyImpl(Map m) { super(m); } public String asm() { return this.mapStr("asm"); } public String hex() { return this.mapStr("hex"); } public int reqSigs() { return this.mapInt("reqSigs"); } public String type() { return this.mapStr(this.type()); } public List<String> addresses() { return (List)this.m.get("addresses"); } } } private class InImpl extends MapWrapper implements In { public InImpl(Map m) { super(m); } public String txid() { return this.mapStr("txid"); } public int vout() { return this.mapInt("vout"); } public Map<String, Object> scriptSig() { return (Map)this.m.get("scriptSig"); } public long sequence() { return this.mapLong("sequence"); } public RawTransaction getTransaction() { try { return BitcoinRPCClient.this.getRawTransaction(this.mapStr("txid")); } catch (BitcoinException var2) { throw new RuntimeException(var2); } } public Out getTransactionOutput() { return (Out)this.getTransaction().vOut().get(this.mapInt("vout")); } } } private class PeerInfoMapWrapper extends MapWrapper implements PeerInfo { public PeerInfoMapWrapper(Map m) { super(m); } public String addr() { return this.mapStr("addr"); } public String services() { return this.mapStr("services"); } public int lastsend() { return this.mapInt("lastsend"); } public int lastrecv() { return this.mapInt("lastrecv"); } public int bytessent() { return this.mapInt("bytessent"); } public int bytesrecv() { return this.mapInt("bytesrecv"); } public int blocksrequested() { return this.mapInt("blocksrequested"); } public Date conntime() { return this.mapCTime("conntime"); } public int version() { return this.mapInt("version"); } public String subver() { return this.mapStr("subver"); } public boolean inbound() { return this.mapBool("inbound"); } public int startingheight() { return this.mapInt("startingheight"); } public int banscore() { return this.mapInt("banscore"); } } private class MiningInfoMapWrapper extends MapWrapper implements MiningInfo { public MiningInfoMapWrapper(Map m) { super(m); } public int blocks() { return this.mapInt("blocks"); } public int currentblocksize() { return this.mapInt("currentblocksize"); } public int currentblocktx() { return this.mapInt("currentblocktx"); } public double difficulty() { return this.mapDouble("difficulty"); } public String errors() { return this.mapStr("errors"); } public int genproclimit() { return this.mapInt("genproclimit"); } public double networkhashps() { return this.mapDouble("networkhashps"); } public int pooledtx() { return this.mapInt("pooledtx"); } public boolean testnet() { return this.mapBool("testnet"); } public String chain() { return this.mapStr("chain"); } public boolean generate() { return this.mapBool("generate"); } } private class InfoMapWrapper extends MapWrapper implements Info { public InfoMapWrapper(Map m) { super(m); } public int version() { return this.mapInt("version"); } public int protocolversion() { return this.mapInt("protocolversion"); } public int walletversion() { return this.mapInt("walletversion"); } public double balance() { return this.mapDouble("balance"); } public int blocks() { return this.mapInt("blocks"); } public int timeoffset() { return this.mapInt("timeoffset"); } public int connections() { return this.mapInt("connections"); } public String proxy() { return this.mapStr("proxy"); } public double difficulty() { return this.mapDouble("difficulty"); } public boolean testnet() { return this.mapBool("testnet"); } public int keypoololdest() { return this.mapInt("keypoololdest"); } public int keypoolsize() { return this.mapInt("keypoolsize"); } public int unlocked_until() { return this.mapInt("unlocked_until"); } public double paytxfee() { return this.mapDouble("paytxfee"); } public double relayfee() { return this.mapDouble("relayfee"); } public String errors() { return this.mapStr("errors"); } } private class BlockMapWrapper extends MapWrapper implements Block { public BlockMapWrapper(Map m) { super(m); } public String hash() { return this.mapStr("hash"); } public int confirmations() { return this.mapInt("confirmations"); } public int size() { return this.mapInt("size"); } public int height() { return this.mapInt("height"); } public int version() { return this.mapInt("version"); } public String merkleRoot() { return this.mapStr(""); } public List<String> tx() { return (List)this.m.get("tx"); } public Date time() { return this.mapCTime("time"); } public long nonce() { return this.mapLong("nonce"); } public String bits() { return this.mapStr("bits"); } public double difficulty() { return this.mapDouble("difficulty"); } public String previousHash() { return this.mapStr("previousblockhash"); } public String nextHash() { return this.mapStr("nextblockhash"); } public Block previous() throws BitcoinException { return !this.m.containsKey("previousblockhash") ? null : BitcoinRPCClient.this.getBlock(this.previousHash()); } public Block next() throws BitcoinException { return !this.m.containsKey("nextblockhash") ? null : BitcoinRPCClient.this.getBlock(this.nextHash()); } } }
33.865112
269
0.596774
68fb9a7fbd1426808d2024c9c14d0395a2aefb35
4,819
/* Copyright (C) GridGain Systems. 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 org.gridgain.examples.datagrid.datastructures; import org.gridgain.examples.datagrid.*; import org.gridgain.grid.*; import org.gridgain.grid.cache.datastructures.*; import org.gridgain.grid.lang.*; import java.util.*; /** * Demonstrates a simple usage of distributed atomic reference. * <p> * Remote nodes should always be started with special configuration file which * enables P2P class loading: {@code 'ggstart.{sh|bat} examples/config/example-cache.xml'}. * <p> * Alternatively you can run {@link CacheNodeStartup} in another JVM which will * start GridGain node with {@code examples/config/example-cache.xml} configuration. */ public final class CacheAtomicReferenceExample { /** Cache name. */ private static final String CACHE_NAME = "partitioned_tx"; /** * Executes example. * * @param args Command line arguments, none required. * @throws GridException If example execution failed. */ public static void main(String[] args) throws GridException { try (Grid g = GridGain.start("examples/config/example-cache.xml")) { System.out.println(); System.out.println(">>> Cache atomic reference example started."); // Make name of atomic reference. final String refName = UUID.randomUUID().toString(); // Make value of atomic reference. String val = UUID.randomUUID().toString(); // Initialize atomic reference in grid. GridCacheAtomicReference<String> ref = g.cache(CACHE_NAME).dataStructures(). atomicReference(refName, val, true); System.out.println("Atomic reference initial value : " + ref.get() + '.'); // Make closure for checking atomic reference value on grid. Runnable c = new ReferenceClosure(CACHE_NAME, refName); // Check atomic reference on all grid nodes. g.compute().run(c).get(); // Make new value of atomic reference. String newVal = UUID.randomUUID().toString(); System.out.println("Try to change value of atomic reference with wrong expected value."); ref.compareAndSet("WRONG EXPECTED VALUE", newVal); // Won't change. // Check atomic reference on all grid nodes. // Atomic reference value shouldn't be changed. g.compute().run(c).get(); System.out.println("Try to change value of atomic reference with correct expected value."); ref.compareAndSet(val, newVal); // Check atomic reference on all grid nodes. // Atomic reference value should be changed. g.compute().run(c).get(); } System.out.println(); System.out.println("Finished atomic reference example..."); System.out.println("Check all nodes for output (this node is also part of the grid)."); } /** * Obtains atomic reference. */ private static class ReferenceClosure implements GridRunnable { /** Cache name. */ private final String cacheName; /** Reference name. */ private final String refName; /** * @param cacheName Cache name. * @param refName Reference name. */ ReferenceClosure(String cacheName, String refName) { this.cacheName = cacheName; this.refName = refName; } /** {@inheritDoc} */ @Override public void run() { try { GridCacheAtomicReference<String> ref = GridGain.grid().cache(cacheName).dataStructures(). atomicReference(refName, null, true); System.out.println("Atomic reference value is " + ref.get() + '.'); } catch (GridException e) { throw new GridRuntimeException(e); } } } }
36.233083
105
0.619216
af5491d3aa592384c0dd4a3775b84c3802e25836
14,247
package com.helenssc.android.toddlertabletpublic; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.io.IOException; /** * <h1>Toddler Tablet MathActivity</h1> * Quizzes on simple addition or subtraction problems. Numbers and potential answers * are randomly generated. Activity is also exited through the * menu in case the navigation bar has been disabled. * <br /> * <b>Note:</b> This activity was designed for a 2012 Nexus 7 wifi that has been rooted * to disable the bottom navigation bar. * * @author Christine Stoner * @version 1.0 * @since 2017-02-27 */ public class MathActivity extends ActionBarActivity { private View decorView; private TextView number_one, operator, number_two, equals_picture, guess_one, guess_two, guess_three, guess_four; private MediaPlayer letterPlayer; private String listName; private Integer correct_guess; private ToddlerItem firstToddlerItem, secondToddlerItem, guessOneToddlerItem, guessTwoToddlerItem, guessThreeToddlerItem, guessFourToddlerItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); decorView = getWindow().getDecorView(); setContentView(R.layout.activity_math); //list name determines addition or subtraction Intent intent = getIntent(); listName = intent.getStringExtra(OpenActivity.LIST_NAME); //create MediaPlayer with default sound letterPlayer = MediaPlayer.create(this, R.raw.equals); try { letterPlayer.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //assign view items number_one = (TextView) findViewById(R.id.first_number); operator = (TextView) findViewById(R.id.operator); number_two = (TextView) findViewById(R.id.second_number); equals_picture = (TextView) findViewById(R.id.equals_picture); guess_one = (TextView) findViewById(R.id.guess_one); guess_two = (TextView) findViewById(R.id.guess_two); guess_three = (TextView) findViewById(R.id.guess_three); guess_four = (TextView) findViewById(R.id.guess_four); //change text to - if minus passed by Intent if (listName.equals("minus")){ operator.setText("-"); } //sets onClickListener for first number number_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(firstToddlerItem.getSoundID()); } }); //sets onClickListener for operator operator.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listName.equals("add")) { playSound(R.raw.plus); } else { playSound(R.raw.minus); } } }); //sets onClickListener for second number number_two.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(secondToddlerItem.getSoundID()); } }); //sets onClickListener for equals equals_picture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playSound(R.raw.equals); } }); //sets onClickListener for first guess guess_one.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (correct_guess == 1){ playSound(R.raw.yeah); setEquation(); } else { playSound(R.raw.wawawa); } } }); //sets onClickListener for second guess guess_two.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (correct_guess == 2){ playSound(R.raw.yeah); setEquation(); } else { playSound(R.raw.wawawa); } } }); //sets onClickListener for third guess guess_three.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (correct_guess == 3){ playSound(R.raw.yeah); setEquation(); } else { playSound(R.raw.wawawa); } } }); //sets onClickListener for fourth guess guess_four.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (correct_guess == 4){ playSound(R.raw.yeah); setEquation(); } else { playSound(R.raw.wawawa); } } }); setEquation(); } /** * Plays the sound passed as an argument. * @param soundId the int id of the sound to play * @return Nothing */ private void playSound(Integer soundId) { if(letterPlayer.isPlaying()){ letterPlayer.stop(); } letterPlayer.reset(); try { AssetFileDescriptor afd = getResources().openRawResourceFd(soundId); if (afd == null) return; letterPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } catch (IOException excep){ excep.printStackTrace();; } catch (IllegalStateException excep){ excep.printStackTrace(); } try{ letterPlayer.prepare(); } catch(IllegalStateException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } letterPlayer.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_quiz, menu); return true; } /** * Handles the menu, which exits the activity. * Main menu functionality is * to exit the activity in case the navigation bar is disabled. * @param item parameter is the MenuItem selected. * @return Nothing */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.exit_quizactivity) { onBackPressed(); } return super.onOptionsItemSelected(item); } /** * Sets the math equation question and assigns one correct and three incorrect answers. * @return Nothing */ private void setEquation(){ Integer first_number, second_number, answer; //assign first and second number randomly if (listName.equals("add")) { first_number = 1 + (int) (Math.random() * ((10 - 1) + 1)); second_number = 1 + (int) (Math.random() * ((10 - 1) + 1)); //calculate answer answer = first_number + second_number; } else { first_number = 2 + (int) (Math.random() * ((10 - 2) + 2)); do { second_number = 1 + (int) (Math.random() * ((10 - 1) + 1)); } while (second_number >= first_number); //calculate answer answer = first_number - second_number; } //determine which guess from 1 to 4 will be correct correct_guess = 1 + (int)(Math.random() * ((4-1)+1)); //assign correct guess and random numbers to wrong guesses Integer firstGuess, secondGuess, thirdGuess; do { firstGuess = 1 + (int) (Math.random() * ((19 - 1) + 1)); } while (firstGuess == answer); do { secondGuess = 1 + (int) (Math.random() * ((19 - 1) + 1)); } while (secondGuess == firstGuess || secondGuess == answer); do { thirdGuess = 1 + (int) (Math.random() * ((19 - 1) + 1)); } while (thirdGuess == secondGuess || thirdGuess == firstGuess || thirdGuess == answer); switch (correct_guess){ case 1: guessOneToddlerItem = setToddlerItem(answer); guessTwoToddlerItem = setToddlerItem(firstGuess); guessThreeToddlerItem = setToddlerItem(secondGuess); guessFourToddlerItem = setToddlerItem(thirdGuess); break; case 2: guessOneToddlerItem = setToddlerItem(firstGuess); guessTwoToddlerItem = setToddlerItem(answer); guessThreeToddlerItem = setToddlerItem(secondGuess); guessFourToddlerItem = setToddlerItem(thirdGuess); break; case 3: guessOneToddlerItem = setToddlerItem(firstGuess); guessTwoToddlerItem = setToddlerItem(secondGuess); guessThreeToddlerItem = setToddlerItem(answer); guessFourToddlerItem = setToddlerItem(thirdGuess); break; default: guessOneToddlerItem = setToddlerItem(firstGuess); guessTwoToddlerItem = setToddlerItem(secondGuess); guessThreeToddlerItem = setToddlerItem(thirdGuess); guessFourToddlerItem = setToddlerItem(answer); break; } //set ToddlerItem for numbers firstToddlerItem = setToddlerItem(first_number); secondToddlerItem = setToddlerItem(second_number); //set text for guesses and numbers number_one.setText(firstToddlerItem.getLetterTitle()); number_two.setText(secondToddlerItem.getLetterTitle()); guess_one.setText(guessOneToddlerItem.getLetterTitle()); guess_two.setText(guessTwoToddlerItem.getLetterTitle()); guess_three.setText(guessThreeToddlerItem.getLetterTitle()); guess_four.setText(guessFourToddlerItem.getLetterTitle()); setColors(); } /** * Sets random text colors for the textviews displayed. * @return Nothing */ private void setColors(){ number_one.setTextColor(getRandomColor()); operator.setTextColor(getRandomColor()); number_two.setTextColor(getRandomColor()); equals_picture.setTextColor(getRandomColor()); guess_one.setTextColor(getRandomColor()); guess_two.setTextColor(getRandomColor()); guess_three.setTextColor(getRandomColor()); guess_four.setTextColor(getRandomColor()); } /** * Picks a random color from blue, green, red or yellow. * @return int color id */ private int getRandomColor() { int randomColor = 1 + (int) (Math.random() * ((4 - 1) + 1)); int colorPick = Color.BLUE; switch (randomColor) { case 1: colorPick = Color.BLUE; break; case 2: colorPick = Color.GREEN; break; case 3: colorPick = Color.RED; break; default: colorPick = Color.YELLOW; break; } return colorPick; } /** * Sets the ToddlerItem matching the number passed as an argument. * @param itemNumber int of of number for which matching ToddlerItem desired * @return ToddlerItem matching number of parameter. */ private ToddlerItem setToddlerItem(Integer itemNumber){ switch(itemNumber) { case 1: return new ToddlerItem("1", R.drawable.one, R.raw.one); case 2: return new ToddlerItem("2", R.drawable.two, R.raw.two); case 3: return new ToddlerItem("3", R.drawable.three, R.raw.three); case 4: return new ToddlerItem("4", R.drawable.four, R.raw.four); case 5: return new ToddlerItem("5", R.drawable.five, R.raw.five); case 6: return new ToddlerItem("6", R.drawable.six, R.raw.six); case 7: return new ToddlerItem("7", R.drawable.seven, R.raw.seven); case 8: return new ToddlerItem("8", R.drawable.eight, R.raw.eight); case 9: return new ToddlerItem("9", R.drawable.nine, R.raw.nine); case 10: return new ToddlerItem("10", R.drawable.ten, R.raw.ten); case 11: return new ToddlerItem("11", R.drawable.eleven, R.raw.eleven); case 12: return new ToddlerItem("12", R.drawable.twelve, R.raw.twelve); case 13: return new ToddlerItem("13", R.drawable.thirteen, R.raw.thirteen); case 14: return new ToddlerItem("14", R.drawable.fourteen, R.raw.fourteen); case 15: return new ToddlerItem("15", R.drawable.fifteen, R.raw.fifteen); case 16: return new ToddlerItem("16", R.drawable.sixteen, R.raw.sixteen); case 17: return new ToddlerItem("17", R.drawable.seventeen, R.raw.seventeen); case 18: return new ToddlerItem("18", R.drawable.eighteen, R.raw.eighteen); case 19: return new ToddlerItem("19", R.drawable.nineteen, R.raw.nineteen); case 20: return new ToddlerItem("20", R.drawable.twenty, R.raw.twenty); } return new ToddlerItem("one", R.drawable.one, R.raw.one); } }
34.664234
148
0.573945
fa63dedb1e515d0a4ea88e5e59638ccbb4abd6bc
4,279
/* * Copyright (c) 2009-2014 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.system; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Allows extraction of platform specific binaries from classpath via build * systems. * * @author normenhansen */ public class ExtractNativeLibraries { public static void main(String[] args) { if (args.length == 1) { if ("getjarexcludes".equals(args[0])) { File[] jarFiles = NativeLibraryLoader.getJarsWithNatives(); for (int i = 0; i < jarFiles.length; i++) { File jarFile = jarFiles[i]; System.out.print("**/*" + jarFile.getName()); if (i != jarFiles.length - 1) { System.out.print(","); } } System.exit(0); } } if (args.length < 2) { System.err.println("Usage: ExtractNativeLibraries Platform ExtractionPath"); System.err.println("Where 'Platform' is either Windows32, Windows64, Linux32, Linux64, MacOSX32 or MacOSX64"); System.err.println("'ExtractionPath' is a folder to extract the binaries to."); System.err.println("You can also use ExtractNativeLibraries getjarexcludes to get a list of excludes for the jar files that contain binaries."); System.exit(1); } String path = args[1].replace('/', File.separatorChar); File folder = new File(path); try { if ("Windows32".equals(args[0])) { NativeLibraryLoader.extractNativeLibraries(Platform.Windows32, folder); } else if ("Windows64".equals(args[0])) { NativeLibraryLoader.extractNativeLibraries(Platform.Windows64, folder); } else if ("Linux32".equals(args[0])) { NativeLibraryLoader.extractNativeLibraries(Platform.Linux32, folder); } else if ("Linux64".equals(args[0])) { NativeLibraryLoader.extractNativeLibraries(Platform.Linux64, folder); } else if ("MacOSX32".equals(args[0])) { NativeLibraryLoader.extractNativeLibraries(Platform.MacOSX32, folder); } else if ("MacOSX64".equals(args[0])) { NativeLibraryLoader.extractNativeLibraries(Platform.MacOSX64, folder); } else { System.err.println("Please specify a platform, Windows32, Windows64, Linux32, Linux64, MacOSX32 or MacOSX64"); System.exit(3); } } catch (IOException ex) { Logger.getLogger(ExtractNativeLibraries.class.getName()).log(Level.SEVERE, null, ex); } } }
46.51087
156
0.656228
6303d3757f9dd8305d6095ee032a08f05405e7fb
9,855
package us.ihmc.robotics.math.trajectories; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Random; import org.junit.After; import org.junit.Test; import us.ihmc.continuousIntegration.ContinuousIntegrationAnnotations.ContinuousIntegrationTest; import us.ihmc.euclid.referenceFrame.FramePoint3D; import us.ihmc.euclid.referenceFrame.FrameVector3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.referenceFrame.tools.ReferenceFrameTools; import us.ihmc.euclid.tools.EuclidCoreTestTools; import us.ihmc.yoVariables.registry.YoVariableRegistry; import us.ihmc.robotics.random.RandomGeometry; public class YoParabolicTrajectoryGeneratorTest { @After public void tearDown() { ReferenceFrameTools.clearWorldFrameTree(); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testConditions() { YoVariableRegistry registry = new YoVariableRegistry("registry"); ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); FramePoint3D initialPosition = new FramePoint3D(referenceFrame, 0.0, 0.0, 0.0); FramePoint3D intermediatePosition = new FramePoint3D(referenceFrame, 0.5, 0.5, 2.5); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, 1.0, 1.0, 1.0); double intermediateParameter = 0.5; YoParabolicTrajectoryGenerator trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); trajectoryGenerator.initialize(initialPosition, intermediatePosition, finalPosition, intermediateParameter); double delta = 1e-10; FramePoint3D positionToPack = new FramePoint3D(referenceFrame); trajectoryGenerator.getPosition(positionToPack, 0.0); EuclidCoreTestTools.assertTuple3DEquals(initialPosition, positionToPack, delta); trajectoryGenerator.getPosition(positionToPack, intermediateParameter); EuclidCoreTestTools.assertTuple3DEquals(intermediatePosition, positionToPack, delta); trajectoryGenerator.getPosition(positionToPack, 1.0); EuclidCoreTestTools.assertTuple3DEquals(finalPosition, positionToPack, delta); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000,expected = RuntimeException.class) public void testIllegalParameter1() { double intermediateParameter = 1.1; ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); FramePoint3D initialPosition = new FramePoint3D(referenceFrame, 0.0, 0.0, 0.0); FramePoint3D intermediatePosition = new FramePoint3D(referenceFrame, 0.5, 0.5, 2.5); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, 1.0, 1.0, 1.0); YoVariableRegistry registry = new YoVariableRegistry("registry"); YoParabolicTrajectoryGenerator trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); trajectoryGenerator.initialize(initialPosition, intermediatePosition, finalPosition, intermediateParameter); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000,expected = RuntimeException.class) public void testIllegalParameter2() { double intermediateParameter = -0.1; ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); FramePoint3D initialPosition = new FramePoint3D(referenceFrame, 0.0, 0.0, 0.0); FramePoint3D intermediatePosition = new FramePoint3D(referenceFrame, 0.5, 0.5, 2.5); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, 1.0, 1.0, 1.0); YoVariableRegistry registry = new YoVariableRegistry("registry"); YoParabolicTrajectoryGenerator trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); trajectoryGenerator.initialize(initialPosition, intermediatePosition, finalPosition, intermediateParameter); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000,expected = RuntimeException.class) public void testIllegalParameter3() { ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); YoParabolicTrajectoryGenerator trajectoryGenerator = null; try { double intermediateParameter = 0.7; FramePoint3D initialPosition = new FramePoint3D(referenceFrame, 0.0, 0.0, 0.0); FramePoint3D intermediatePosition = new FramePoint3D(referenceFrame, 0.5, 0.5, 2.5); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, 1.0, 1.0, 1.0); YoVariableRegistry registry = new YoVariableRegistry("registry"); trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); trajectoryGenerator.initialize(initialPosition, intermediatePosition, finalPosition, intermediateParameter); } catch (RuntimeException e) { fail(); } FramePoint3D positionToPack = new FramePoint3D(referenceFrame); trajectoryGenerator.getPosition(positionToPack, 1.1); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testApex() { YoVariableRegistry registry = new YoVariableRegistry("registry"); ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); FramePoint3D initialPosition = new FramePoint3D(referenceFrame, 0.0, 0.0, 0.0); FramePoint3D intermediatePosition = new FramePoint3D(referenceFrame, 0.5, 0.5, 2.5); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, 1.0, 1.0, 0.0); double intermediateParameter = 0.5; YoParabolicTrajectoryGenerator trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); trajectoryGenerator.initialize(initialPosition, intermediatePosition, finalPosition, intermediateParameter); double delta = 1e-10; FramePoint3D positionToPack = new FramePoint3D(referenceFrame); int n = 1000; double smallestDifference = Double.POSITIVE_INFINITY; for (int i = 0; i < n; i++) { double parameter = i / (double) n; trajectoryGenerator.getPosition(positionToPack, parameter); double difference = intermediatePosition.getZ() - positionToPack.getZ(); if (difference < smallestDifference) smallestDifference = difference; } assertTrue(smallestDifference < delta); assertTrue(smallestDifference >= 0.0); } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testVelocity() { YoVariableRegistry registry = new YoVariableRegistry("registry"); Random random = new Random(186L); ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); YoParabolicTrajectoryGenerator trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); int nTests = 100; for (int i = 0; i < nTests; i++) { FramePoint3D initialPosition = new FramePoint3D(referenceFrame, RandomGeometry.nextVector3D(random)); FramePoint3D intermediatePosition = new FramePoint3D(referenceFrame, RandomGeometry.nextVector3D(random)); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, RandomGeometry.nextVector3D(random)); double intermediateParameter = random.nextDouble(); trajectoryGenerator.initialize(initialPosition, intermediatePosition, finalPosition, intermediateParameter); FramePoint3D position1 = new FramePoint3D(referenceFrame); FramePoint3D position2 = new FramePoint3D(referenceFrame); double dt = 1e-9; double parameter = random.nextDouble(); trajectoryGenerator.getPosition(position1, parameter); trajectoryGenerator.getPosition(position2, parameter + dt); FrameVector3D numericalVelocity = new FrameVector3D(position2); numericalVelocity.sub(position1); numericalVelocity.scale(1.0 / dt); FrameVector3D velocityFromTrajectoryGenerator = new FrameVector3D(referenceFrame); trajectoryGenerator.getVelocity(velocityFromTrajectoryGenerator, parameter); double delta = 1e-4; EuclidCoreTestTools.assertTuple3DEquals(numericalVelocity, velocityFromTrajectoryGenerator, delta); } } @ContinuousIntegrationTest(estimatedDuration = 0.0) @Test(timeout = 30000) public void testInitialVelocity() { YoVariableRegistry registry = new YoVariableRegistry("registry"); Random random = new Random(186L); ReferenceFrame referenceFrame = ReferenceFrame.getWorldFrame(); YoParabolicTrajectoryGenerator trajectoryGenerator = new YoParabolicTrajectoryGenerator("test", referenceFrame, registry); FramePoint3D initialPosition = new FramePoint3D(referenceFrame, RandomGeometry.nextVector3D(random)); FrameVector3D initialVelocity = new FrameVector3D(referenceFrame, RandomGeometry.nextVector3D(random)); FramePoint3D finalPosition = new FramePoint3D(referenceFrame, RandomGeometry.nextVector3D(random)); trajectoryGenerator.initialize(initialPosition, initialVelocity, finalPosition); FramePoint3D initialPositionBack = new FramePoint3D(referenceFrame); trajectoryGenerator.getPosition(initialPositionBack, 0.0); FrameVector3D initialVelocityBack = new FrameVector3D(referenceFrame); trajectoryGenerator.getVelocity(initialVelocityBack, 0.0); FramePoint3D finalPositionBack = new FramePoint3D(referenceFrame); trajectoryGenerator.getPosition(finalPositionBack, 1.0); double delta = 0.0; EuclidCoreTestTools.assertTuple3DEquals(initialPosition, initialPositionBack, delta); EuclidCoreTestTools.assertTuple3DEquals(initialVelocity, initialVelocityBack, delta); EuclidCoreTestTools.assertTuple3DEquals(finalPosition, finalPositionBack, delta); } }
46.706161
128
0.756875
e0df586c4cfce4714efc5e1241aa27fc751a5b62
737
package de.langs.archivela; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Check if the given page name is valid. */ @Component public class PageValidator { @Autowired public PageValidator() { } public void validate(String pageName) throws RuleValidationException { if (pageName == null || pageName.isEmpty()) { throw new RuleValidationException("No page given"); } else if (!(pageName.contains("(") && pageName.contains(")"))) { throw new RuleValidationException("Wrong format of page name, should be 'Title (SpaceKey)'"); } else if (PageUtils.getPage(pageName) == null) { throw new RuleValidationException("Non-accessible page"); } } }
28.346154
96
0.72863
7ef06a9e2486f940967e6897dd0b2e5011c1808d
1,964
package org.wildfly.halos.proxy; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import io.smallrye.mutiny.Multi; import static java.util.stream.Collectors.joining; @Path("/v1/instance") @Produces(MediaType.TEXT_PLAIN) public class InstanceResource { @Inject Instances instances; @GET public String instanceNames() { return instances.instances().stream() .map(instance -> instance.name) .collect(joining(",")); } @GET @Path("/subscribe") @Produces(MediaType.SERVER_SENT_EVENTS) public Multi<String> modifications() { return instances.modifications().map(InstanceModification::toString); } @POST public Response register(Instance instance) { if (instances.hasInstance(instance.name)) { return Response.status(Status.NOT_MODIFIED).build(); } else { try { instances.register(instance); return Response.status(Status.CREATED).entity(instance).build(); } catch (ManagementException e) { return Response.serverError().entity(e.getMessage()).build(); } } } @DELETE @Path("/{name}") public Response unregister(@PathParam("name") String name) { if (instances.hasInstance(name)) { try { instances.unregister(name); return Response.noContent().build(); } catch (ManagementException e) { return Response.serverError().entity(e.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("No instance found for '" + name + "'.").build(); } } }
29.313433
109
0.620672
d3d2d707e9ca54e3a49c1f01e16eac1515f2a9f5
8,245
/* * Copyright 2020, OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opentelemetry.trace.attributes; /** * Defines constants for all attribute names defined in the OpenTelemetry Semantic Conventions * specifications. * * @see <a * href="https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-semantic-conventions.md">Semantic * Conventions</a> */ public final class SemanticAttributes { /** Transport protocol used. */ public static final StringAttributeSetter NET_TRANSPORT = StringAttributeSetter.create("net.transport"); /** Remote address of the peer (dotted decimal for IPv4 or RFC5952 for IPv6). */ public static final StringAttributeSetter NET_PEER_IP = StringAttributeSetter.create("net.peer.ip"); /** Remote port number as an integer. E.g., 80. */ public static final LongAttributeSetter NET_PEER_PORT = LongAttributeSetter.create("net.peer.port"); /** Remote hostname or similar. */ public static final StringAttributeSetter NET_PEER_NAME = StringAttributeSetter.create("net.peer.name"); /** Like net.peer.ip but for the host IP. Useful in case of a multi-IP host. */ public static final StringAttributeSetter NET_HOST_IP = StringAttributeSetter.create("net.host.ip"); /** Like net.peer.port but for the host port. */ public static final LongAttributeSetter NET_HOST_PORT = LongAttributeSetter.create("net.host.port"); /** Local hostname or similar. */ public static final StringAttributeSetter NET_HOST_NAME = StringAttributeSetter.create("net.host.name"); /** Logical name of a remote service. */ public static final StringAttributeSetter PEER_SERVICE = StringAttributeSetter.create("peer.service"); /** * Username or client_id extracted from the access token or Authorization header in the inbound * request from outside the system. */ public static final StringAttributeSetter ENDUSER_ID = StringAttributeSetter.create("enduser.id"); /** * Actual/assumed role the client is making the request under extracted from token or application * security context. */ public static final StringAttributeSetter ENDUSER_ROLE = StringAttributeSetter.create("enduser.role"); /** * Scopes or granted authorities the client currently possesses extracted from token or * application security context. The value would come from the scope associated with an OAuth 2.0 * Access Token or an attribute value in a SAML 2.0 Assertion. */ public static final StringAttributeSetter ENDUSER_SCOPE = StringAttributeSetter.create("enduser.scope"); /** HTTP request method. E.g. "GET". */ public static final StringAttributeSetter HTTP_METHOD = StringAttributeSetter.create("http.method"); /** Full HTTP request URL in the form scheme://host[:port]/path?query[#fragment]. */ public static final StringAttributeSetter HTTP_URL = StringAttributeSetter.create("http.url"); /** The full request target as passed in a HTTP request line or equivalent. */ public static final StringAttributeSetter HTTP_TARGET = StringAttributeSetter.create("http.target"); /** The value of the HTTP host header. */ public static final StringAttributeSetter HTTP_HOST = StringAttributeSetter.create("http.host"); /** The URI scheme identifying the used protocol: "http" or "https". */ public static final StringAttributeSetter HTTP_SCHEME = StringAttributeSetter.create("http.scheme"); /** HTTP response status code. E.g. 200 (integer) If and only if one was received/sent. */ public static final LongAttributeSetter HTTP_STATUS_CODE = LongAttributeSetter.create("http.status_code"); /** HTTP reason phrase. E.g. "OK" */ public static final StringAttributeSetter HTTP_STATUS_TEXT = StringAttributeSetter.create("http.status_text"); /** Kind of HTTP protocol used: "1.0", "1.1", "2", "SPDY" or "QUIC". */ public static final StringAttributeSetter HTTP_FLAVOR = StringAttributeSetter.create("http.flavor"); /** Value of the HTTP "User-Agent" header sent by the client. */ public static final StringAttributeSetter HTTP_USER_AGENT = StringAttributeSetter.create("http.user_agent"); /** The primary server name of the matched virtual host. Usually obtained via configuration. */ public static final StringAttributeSetter HTTP_SERVER_NAME = StringAttributeSetter.create("http.server_name"); /** The matched route (path template). */ public static final StringAttributeSetter HTTP_ROUTE = StringAttributeSetter.create("http.route"); /** The IP address of the original client behind all proxies, if known. */ public static final StringAttributeSetter HTTP_CLIENT_IP = StringAttributeSetter.create("http.client_ip"); /** * The size of the request payload body, in bytes. For payloads using transport encoding, this is * the compressed size. */ public static final StringAttributeSetter HTTP_REQUEST_CONTENT_LENGTH = StringAttributeSetter.create("http.request_content_length"); /** * The size of the uncompressed request payload body, in bytes. Only set for requests that use * transport encoding. */ public static final StringAttributeSetter HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = StringAttributeSetter.create("http.request_content_length_uncompressed"); /** * The size of the response payload body, in bytes. For payloads using transport encoding, this is * the compressed size. */ public static final StringAttributeSetter HTTP_RESPONSE_CONTENT_LENGTH = StringAttributeSetter.create("http.response_content_length"); /** * The size of the uncompressed response payload body, in bytes. Only set for responses that use * transport encoding. */ public static final StringAttributeSetter HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = StringAttributeSetter.create("http.response_content_length_uncompressed"); /** The service name, must be equal to the $service part in the span name. */ public static final StringAttributeSetter RPC_SERVICE = StringAttributeSetter.create("rpc.service"); /** RPC span event attribute with value "SENT" or "RECEIVED". */ public static final StringAttributeSetter MESSAGE_TYPE = StringAttributeSetter.create("message.type"); /** RPC span event attribute starting from 1 for each of sent messages and received messages. */ public static final LongAttributeSetter MESSAGE_ID = LongAttributeSetter.create("message.id"); /** RPC span event attribute for compressed size. */ public static final LongAttributeSetter MESSAGE_COMPRESSED_SIZE = LongAttributeSetter.create("message.compressed_size"); /** RPC span event attribute for uncompressed size. */ public static final LongAttributeSetter MESSAGE_UNCOMPRESSED_SIZE = LongAttributeSetter.create("message.uncompressed_size"); /** Database type. For any SQL database, "sql". For others, the lower-case database category. */ public static final StringAttributeSetter DB_TYPE = StringAttributeSetter.create("db.type"); /** Database instance name. */ public static final StringAttributeSetter DB_INSTANCE = StringAttributeSetter.create("db.instance"); /** Database statement for the given database type. */ public static final StringAttributeSetter DB_STATEMENT = StringAttributeSetter.create("db.statement"); /** Username for accessing database. */ public static final StringAttributeSetter DB_USER = StringAttributeSetter.create("db.user"); /** JDBC substring like "mysql://db.example.com:3306" */ public static final StringAttributeSetter DB_URL = StringAttributeSetter.create("db.url"); private SemanticAttributes() {} }
51.855346
139
0.752699
fcc501201df90b56550f73bcc8f90d6f0286aecb
12,966
package org.firstinspires.ftc.teamcode.Controllers; import android.os.Environment; import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.config.Config; import org.firstinspires.ftc.teamcode.Development.PoseStorage; import org.jetbrains.annotations.NotNull; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfDouble; import org.opencv.core.MatOfPoint; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvPipeline; import java.io.File; import java.io.IOException; import java.util.ArrayList; /* * An example image processing pipeline to be run upon receipt of each frame from the camera. * Note that the processFrame() method is called serially from the frame worker thread - * that is, a new camera frame will not come in while you're still processing a previous one. * In other words, the processFrame() method will never be called multiple times simultaneously. * * However, the rendering of your processed image to the viewport is done in parallel to the * frame worker thread. That is, the amount of time it takes to render the image to the * viewport does NOT impact the amount of frames per second that your pipeline can process. * * IMPORTANT NOTE: this pipeline is NOT invoked on your OpMode thread. It is invoked on the * frame worker thread. This should not be a problem in the vast majority of cases. However, * if you're doing something weird where you do need it synchronized with your OpMode thread, * then you will need to account for that accordingly. */ @Config public class CupFinder extends OpenCvPipeline { public CupFinder(@NotNull OpenCvCamera webcamToUse) { super(); webcam = webcamToUse; } private FtcDashboard dashboard; private OpenCvCamera webcam; private Mat inputImageBGR = new Mat(); private Mat hsvImage = new Mat(); private Mat maskImage = new Mat(); private Mat blurImage = new Mat(); private Mat outputImageBGR = new Mat(); private Mat outputImageRBG = new Mat(); public Rect BoundingRectangle = null; public static int colorErrorTolerance = 60; public static int baseH = 162, baseS = 125, baseV = 150; public static int areaThreshold = 1500; Scalar base = new Scalar(baseH, baseS, baseV); Scalar lower = new Scalar(base.val[0] - 7.5, base.val[1] -colorErrorTolerance, base.val[2] - colorErrorTolerance); Scalar upper = new Scalar(base.val[0] + 7.5, base.val[1] +colorErrorTolerance, base.val[2] + colorErrorTolerance); // Volatile since accessed by OpMode thread w/o synchronization public volatile PositionEnum positionDetected = PositionEnum.UNKNOWN; public volatile PipelineStages pipelineStageToDisplay = PipelineStages.INPUT; public volatile int measuredArea = 0; public volatile Point centerOFTarget = null; public enum PositionEnum { LEFT, CENTER, RIGHT, UNKNOWN } public enum PipelineStages { INPUT, CONVERT2HSV, MASKIMAGE, BLURIMAGE, OUTPUTWITHBOUNDINGRECT } @Override public Mat processFrame(Mat input) { try { Imgproc.cvtColor(input, inputImageBGR, Imgproc.COLOR_RGB2BGR); inputImageBGR.copyTo(outputImageBGR); // Here we could possible crop the image to speed processing. If we do, we need to do so in the init as well //Rect cropRect = new Rect(83, 1017, 642, 237); //Mat cropImage = input.submat(cropRect); Imgproc.cvtColor(inputImageBGR, hsvImage, Imgproc.COLOR_BGR2HSV); // refresh the lower/upper bounds so that this can work via FTC Dashboard Scalar lowerHSVBound = new Scalar(lower.val[0], lower.val[1], lower.val[2]); Scalar upperHSVBound = new Scalar(upper.val[0], upper.val[1], upper.val[2]); Core.inRange(hsvImage, lowerHSVBound, upperHSVBound, maskImage); Imgproc.medianBlur(maskImage, blurImage, 11); ArrayList<MatOfPoint> contours = new ArrayList<>(); Mat hierarchy = new Mat(); Imgproc.findContours(blurImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); if(contours.size() > 0) { // find the largest contour by area (this can't be assumed to be the first one in the list double maxContourArea = 0D; MatOfPoint maxContour = null; for(int i = 0; i< contours.size(); i++) { MatOfPoint contour = contours.get(i); double contourArea = Imgproc.contourArea(contour); if(contourArea > maxContourArea) { maxContourArea = contourArea; maxContour = contour; } } // maxContour should never be null...but somehow it was and was throwing an exception... if(maxContour != null) BoundingRectangle = Imgproc.boundingRect(maxContour); } else BoundingRectangle = null; if(BoundingRectangle == null) { if(PoseStorage.alliance == PoseStorage.Alliance.RED){ positionDetected = PositionEnum.RIGHT; Scalar rectColor = new Scalar(0, 255, 0); int[] baseline ={0}; Size textSize = Imgproc.getTextSize(positionDetected.toString(), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5,2, baseline); Point textOrigin = new Point(input.width() - textSize.width, input.height()/2.0); Imgproc.putText(outputImageBGR, positionDetected.toString(), textOrigin, Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, rectColor, 2); } else if (PoseStorage.alliance == PoseStorage.Alliance.BLUE) { positionDetected = PositionEnum.LEFT; Scalar rectColor = new Scalar(0, 255, 0); int[] baseline ={0}; Size textSize = Imgproc.getTextSize(positionDetected.toString(), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5,2, baseline); Point textOrigin = new Point(textSize.width, input.height()/2.0); Imgproc.putText(outputImageBGR, positionDetected.toString(), textOrigin, Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, rectColor, 2); } else { positionDetected = PositionEnum.UNKNOWN; Scalar rectColor = new Scalar(0, 255, 0); Point textOrigin = new Point(input.width()/2.0, input.height()/2.0); Imgproc.putText(outputImageBGR, positionDetected.toString(), textOrigin, Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, rectColor, 2); } measuredArea = 0; centerOFTarget = null; } else { measuredArea = BoundingRectangle.width * BoundingRectangle.height; double rectXCenter = BoundingRectangle.x + BoundingRectangle.width/2.0; double rectYCenter = BoundingRectangle.y + BoundingRectangle.height/2.0; double xScreenRelativeCenter = rectXCenter - input.width()/2.0; double yScreenRelativeCenter = rectYCenter - input.height()/2.0; centerOFTarget = new Point(xScreenRelativeCenter, yScreenRelativeCenter); if(PoseStorage.alliance == PoseStorage.Alliance.RED) { if(measuredArea < areaThreshold) { positionDetected = PositionEnum.RIGHT; } else { if (BoundingRectangle.x <= 250) positionDetected = PositionEnum.LEFT; else positionDetected = PositionEnum.CENTER; } } else { if(measuredArea < areaThreshold) { positionDetected = PositionEnum.LEFT; } else { if (BoundingRectangle.x <= 250) positionDetected = PositionEnum.CENTER; else positionDetected = PositionEnum.RIGHT; } } // Draw a simple box around the rings Scalar rectColor = new Scalar(0, 255, 0); Imgproc.rectangle(outputImageBGR, BoundingRectangle, rectColor, 4); int baseline[]={0}; Size textSize = Imgproc.getTextSize(positionDetected.toString(), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5,2, baseline); int margin = 2; Point textOrigin = new Point(BoundingRectangle.x + BoundingRectangle.width/2 - textSize.width/2, BoundingRectangle.y - textSize.height - margin); Imgproc.putText(outputImageBGR, positionDetected.toString(), textOrigin, Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, rectColor, 2); } switch (pipelineStageToDisplay) { case MASKIMAGE: return maskImage; case BLURIMAGE: return blurImage; case CONVERT2HSV: // when showing hsv, put a small box on the screen and // make a 100x100 square in the middle of the frame int width = 100; int height = 100; int x = (input.width() - width)/2; int y = (input.height() - height)/2; Rect sampleRect = new Rect(x,y,width,height); Imgproc.rectangle(hsvImage, sampleRect, new Scalar(0, 255, 0), 4); // now calculate the mean and std of the sample area Mat sampleImage = hsvImage.submat(sampleRect); MatOfDouble mean = new MatOfDouble(); MatOfDouble std = new MatOfDouble(); Core.meanStdDev(sampleImage, mean, std); double[] meanArray = mean.toArray(); double[] stdArray = std.toArray(); int[] hsvMean = new int[3]; int[] hsvStd = new int[3]; for(int i=0 ;i<3; i++){ hsvMean[i] = (int)meanArray[i]; hsvStd[i] = (int)stdArray[i]; } // HSVSampleMetrics = String.format("hsv mean (%d, %d,%d), std (%d, %d,%d)", hsvMean[0] , hsvMean[1], hsvMean[2], hsvStd[0], hsvStd[1], hsvStd[2]); //telemetry.addData("HSV Mean", String.format("(%d, %d,%d)", hsvMean[0] , hsvMean[1], hsvMean[2])); //telemetry.addData("HSV StdDev", String.format("(%d, %d,%d)", hsvStd[0], hsvStd[1], hsvStd[2])); return hsvImage; case OUTPUTWITHBOUNDINGRECT: // we need to return an RGB image Imgproc.cvtColor(outputImageBGR, outputImageRBG, Imgproc.COLOR_BGR2RGB); return outputImageRBG; case INPUT: default: return input; } } catch (Exception ex){ throw ex; } } private int captureCounter = 0; public Mat CaptureImage() throws IOException { Mat image2Save; String fullFileName = String.format("ring-"+ pipelineStageToDisplay.toString().toLowerCase()+"-%d.png",captureCounter++); switch (pipelineStageToDisplay) { case MASKIMAGE: image2Save = maskImage; break; case CONVERT2HSV: image2Save = hsvImage; break; case BLURIMAGE: image2Save = blurImage; break; case OUTPUTWITHBOUNDINGRECT: image2Save = outputImageBGR; break; case INPUT: default: image2Save = inputImageBGR; break; } if(image2Save != null) return image2Save; else throw new IOException("Null image to save"); } public static final File VISION_FOLDER = new File(Environment.getExternalStorageDirectory().getPath() + "/vision/"); public boolean saveOpenCvImageToFile(String filename, Mat mat) { Mat mIntermediateMat = new Mat(); Imgproc.cvtColor(mat, mIntermediateMat, Imgproc.COLOR_BGR2RGB, 3); boolean mkdirs = VISION_FOLDER.mkdirs(); File file = new File(VISION_FOLDER, filename); boolean savedSuccessfully = Imgcodecs.imwrite(file.toString(), mat); return savedSuccessfully; } }
45.978723
167
0.591239
78dd8d82d6c92e018cd65226cc7fdae7fe5312b5
4,413
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Mirakl Connector * * Copyright (c) 2018 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. * */ package com.adyen.mirakl.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A DocRetry. */ @Entity @Table(name = "doc_retry") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class DocRetry implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "doc_id", unique = true) private String docId; @Column(name = "shop_id") private String shopId; @Column(name = "times_failed") private Integer timesFailed; @OneToMany(mappedBy = "docRetry", fetch = FetchType.EAGER) @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<DocError> docErrors = new HashSet<>(); // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDocId() { return docId; } public DocRetry docId(String docId) { this.docId = docId; return this; } public void setDocId(String docId) { this.docId = docId; } public String getShopId() { return shopId; } public DocRetry shopId(String shopId) { this.shopId = shopId; return this; } public void setShopId(String shopId) { this.shopId = shopId; } public Integer getTimesFailed() { return timesFailed; } public DocRetry timesFailed(Integer timesFailed) { this.timesFailed = timesFailed; return this; } public void setTimesFailed(Integer timesFailed) { this.timesFailed = timesFailed; } public Set<DocError> getDocErrors() { return docErrors; } public DocRetry docErrors(Set<DocError> docErrors) { this.docErrors = docErrors; return this; } public DocRetry addDocError(DocError docError) { this.docErrors.add(docError); docError.setDocRetry(this); return this; } public DocRetry removeDocError(DocError docError) { this.docErrors.remove(docError); docError.setDocRetry(null); return this; } public void setDocErrors(Set<DocError> docErrors) { this.docErrors = docErrors; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DocRetry docRetry = (DocRetry) o; if (docRetry.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), docRetry.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "DocRetry{" + "id=" + getId() + ", docId='" + getDocId() + "'" + ", shopId='" + getShopId() + "'" + ", timesFailed=" + getTimesFailed() + "}"; } }
26.267857
109
0.51303
7b382eaeaa65c4ce0d6d43dd18a462aa268b9b7d
183
package name.atsushieno.midi; public interface IMidiPlayerStatus { PlayerState getState(); int getTempo(); int getPlayDeltaTime(); int getTotalPlayTimeMilliseconds(); }
18.3
37
0.748634
828397a2440993988ba4ae7aa2517f390d743bd4
1,480
package com.jamonapi; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CounterTest { @Test public void testSetCount() { Counter counter=new Counter(); assertThat(counter.getCount()).isEqualTo(0); counter.setCount(150); assertThat(counter.getCount()).isEqualTo(150); counter.setCount(-150); assertThat(counter.getCount()).isEqualTo(-150); } @Test public void testIncrementDecrement() { Counter counter=new Counter(); counter.decrement(); assertThat(counter.getCount()).isEqualTo(-1); counter.increment(); assertThat(counter.getCount()).isEqualTo(0); counter.increment(); assertThat(counter.getCount()).isEqualTo(1); assertThat(counter.incrementAndReturn()).isEqualTo(2); } @Test public void testEnableDisable() { Counter counter=new Counter(); counter.enable(false); counter.increment(); assertThat(counter.getCount()).isEqualTo(0); counter.decrement(); counter.decrement(); counter.decrement(); assertThat(counter.getCount()).isEqualTo(0); counter.setCount(100); assertThat(counter.getCount()).isEqualTo(0); counter.enable(true); assertThat(counter.incrementAndReturn()).isEqualTo(1); counter.decrement(); assertThat(counter.getCount()).isEqualTo(0); } }
23.492063
62
0.630405
30204caa6d49ebcd14a6c33bff3eb286438a3d5c
4,429
package com.chutneytesting.execution.domain.report; import static java.util.Collections.emptyList; import com.chutneytesting.environment.domain.Target; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; public class StepExecutionReportCoreBuilder { private long executionId; private String name; private long duration; private Instant startDate; private ServerReportStatus status; private List<String> information; private List<String> errors; private List<StepExecutionReportCore> steps; private String type; private String targetName = ""; private String targetUrl = ""; private String strategy = "sequential"; private Map<String, Object> evaluatedInputs; private Map<String, Object> stepOutputs; public StepExecutionReportCoreBuilder from(StepExecutionReportCore stepExecutionReport) { setExecutionId(stepExecutionReport.executionId); setName(stepExecutionReport.name); setDuration(stepExecutionReport.duration); setStartDate(stepExecutionReport.startDate); setStatus(stepExecutionReport.status); setInformation(stepExecutionReport.information); setErrors(stepExecutionReport.errors); setSteps(stepExecutionReport.steps); setType(stepExecutionReport.type); setTargetName(stepExecutionReport.targetName); setTargetUrl(stepExecutionReport.targetUrl); setStrategy(stepExecutionReport.strategy); setStepOutputs(stepExecutionReport.stepOutputs); return setEvaluatedInputs(stepExecutionReport.evaluatedInputs); } public StepExecutionReportCoreBuilder setExecutionId(long executionId) { this.executionId = executionId; return this; } public StepExecutionReportCoreBuilder setName(String name) { this.name = name; return this; } public StepExecutionReportCoreBuilder setDuration(long duration) { this.duration = duration; return this; } public StepExecutionReportCoreBuilder setStartDate(Instant startDate) { this.startDate = startDate; return this; } public StepExecutionReportCoreBuilder setStatus(ServerReportStatus status) { this.status = status; return this; } public StepExecutionReportCoreBuilder setInformation(List<String> information) { this.information = information; return this; } public StepExecutionReportCoreBuilder setErrors(List<String> errors) { this.errors = errors; return this; } public StepExecutionReportCoreBuilder setSteps(List<StepExecutionReportCore> steps) { this.steps = steps; return this; } public StepExecutionReportCoreBuilder setType(String type) { this.type = type; return this; } public StepExecutionReportCoreBuilder setTarget(Target target) { if (target != null) { this.targetName = target.name; this.targetUrl = target.url; } return this; } public StepExecutionReportCoreBuilder setTargetName(String name) { this.targetName = name; return this; } public StepExecutionReportCoreBuilder setTargetUrl(String url) { this.targetUrl = url; return this; } public StepExecutionReportCoreBuilder setEvaluatedInputs(Map<String, Object> evaluatedInputs) { this.evaluatedInputs = evaluatedInputs; return this; } public StepExecutionReportCoreBuilder setStepOutputs(Map<String, Object> stepOutputs) { this.stepOutputs = stepOutputs; return this; } public StepExecutionReportCoreBuilder setStrategy(String strategy) { if (strategy != null) { this.strategy = strategy; } return this; } public StepExecutionReportCore createStepExecutionReport() { return new StepExecutionReportCore( executionId, name, duration, startDate, status, Optional.ofNullable(information).orElse(emptyList()), Optional.ofNullable(errors).orElse(emptyList()), Optional.ofNullable(steps).orElse(emptyList()), type, targetName, targetUrl, strategy, evaluatedInputs, stepOutputs ); } }
30.129252
99
0.680063
3a1bb80dcc024c4d665b0bd779b50e3b5be0d95d
425
package org.ylzl.eden.spring.boot.qcloud.tpns.env; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * TPNS 配置 * * @author <a href="mailto:[email protected]">gyl</a> * @since 2.4.x */ @Data @ConfigurationProperties(prefix = "tencent.cloud.tpns") public class TPNSProperties { private Boolean enabled; private String secretId; private String secretKey; }
19.318182
75
0.755294
0352a3c9986885f068024f4474a27be505d2dfe9
3,968
/* * 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.hop.core.auth.core.impl; import org.apache.hop.core.auth.core.AuthenticationFactoryException; import org.apache.hop.core.auth.core.IAuthenticationConsumer; import org.apache.hop.core.auth.core.IAuthenticationConsumerFactory; import org.apache.hop.i18n.BaseMessages; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class DefaultAuthenticationConsumerFactory implements IAuthenticationConsumerFactory<Object, Object, Object> { private static final Class<?> PKG = DefaultAuthenticationConsumerFactory.class; // For Translator private final Constructor<?> constructor; private final Class<Object> consumedType; private final Class<Object> returnType; private final Class<Object> createArgType; @SuppressWarnings("unchecked") public DefaultAuthenticationConsumerFactory(Class<?> consumerClass) throws AuthenticationFactoryException { Constructor<?>[] constructors = consumerClass.getConstructors(); if (constructors.length != 1) { throw new AuthenticationFactoryException( BaseMessages.getString( PKG, "DefaultAuthenticationConsumerFactory.Constructor", getClass().getName(), consumerClass.getCanonicalName())); } constructor = constructors[0]; Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length != 1) { throw new AuthenticationFactoryException( BaseMessages.getString( PKG, "DefaultAuthenticationConsumerFactory.Constructor.Arg", getClass().getName(), consumerClass.getCanonicalName())); } Method consumeMethod = null; Class<?> consumedType = Object.class; for (Method method : consumerClass.getMethods()) { if ("consume".equals(method.getName())) { Class<?>[] methodParameterTypes = method.getParameterTypes(); if (methodParameterTypes.length == 1 && consumedType.isAssignableFrom(methodParameterTypes[0])) { consumeMethod = method; consumedType = methodParameterTypes[0]; } } } if (consumeMethod == null) { throw new AuthenticationFactoryException( BaseMessages.getString( PKG, "DefaultAuthenticationConsumerFactory.Consume", consumerClass.getCanonicalName())); } this.consumedType = (Class<Object>) consumeMethod.getParameterTypes()[0]; this.returnType = (Class<Object>) consumeMethod.getReturnType(); this.createArgType = (Class<Object>) parameterTypes[0]; } @Override public Class<Object> getConsumedType() { return consumedType; } @Override public Class<Object> getReturnType() { return returnType; } @Override public Class<Object> getCreateArgType() { return createArgType; } @SuppressWarnings("unchecked") @Override public IAuthenticationConsumer<Object, Object> create(Object createArg) { try { return (IAuthenticationConsumer<Object, Object>) constructor.newInstance(createArg); } catch (Exception e) { throw new RuntimeException(e); } } }
36.072727
99
0.707913
8a026d0e4f61ca33e125628e8fa1eedc8066aea7
43,759
package com.smartfoo.android.core.app; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.NavUtils; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.SearchView.OnQueryTextListener; import android.widget.TextView; import com.smartfoo.android.core.FooRun; import com.smartfoo.android.core.FooString; import com.smartfoo.android.core.R; import com.smartfoo.android.core.logging.FooLog; import com.smartfoo.android.core.logging.FooLogCat; import com.smartfoo.android.core.logging.FooLogCat.LogProcessCallbacks; import com.smartfoo.android.core.logging.FooLogFilePrinter; import com.smartfoo.android.core.logging.SetLogLimitDialogFragment; import com.smartfoo.android.core.logging.SetLogLimitDialogFragment.SetLogLimitDialogFragmentCallbacks; import com.smartfoo.android.core.platform.FooPlatformUtils; import com.smartfoo.android.core.platform.FooRes; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; /* * TODO:(pv) Fix the actionbar search menu: * https://github.com/codepath/android_guides/wiki/Extended-ActionBar-Guide#adding-searchview-to-actionbar * TODO:(pv) Update w/ RecyclerView and remove deprecated APIs (setSupportProgressBarIndeterminateVisibility, etc) * TODO:(pv) Stop loading log once the first "I FooLogCat: T27810 +load()" is encountered * TODO:(pv) Search backward and forward in log * TODO:(pv) Ignore everything up the first PID? */ public class FooDebugActivity extends AppCompatActivity//PbPermisoActivity // implements OnQueryTextListener, // SetLogLimitDialogFragmentCallbacks { private static final String TAG = FooLog.TAG(FooDebugActivity.class); public static Bundle makeExtras(Bundle extras, String username) { return makeExtras(extras, username, null, null, android.os.Process.myPid()); } public static Bundle makeExtras(Bundle extras, String username, String message, String logRaw, int logPid) { if (extras == null) { extras = new Bundle(); } if (!FooString.isNullOrEmpty(username)) { extras.putString(EXTRA_USER_NAME, username); } if (!FooString.isNullOrEmpty(message)) { extras.putString(EXTRA_MESSAGE, message); } if (!FooString.isNullOrEmpty(logRaw)) { extras.putString(EXTRA_LOG_RAW, logRaw); } if (logPid != -1) { extras.putInt(EXTRA_LOG_PID, logPid); } return extras; } private static final String EXTRA_USER_NAME = "EXTRA_USER_NAME"; private static final String EXTRA_MESSAGE = "EXTRA_MESSAGE"; private static final String EXTRA_LOG_RAW = "EXTRA_LOG_RAW"; private static final String EXTRA_LOG_PID = "EXTRA_LOG_PID"; private static final String FRAGMENT_DIALOG_SET_LOG_LIMIT = "FRAGMENT_DIALOG_SET_LOG_LIMIT"; private static final int REQUEST_SHARE = 1; /** * Quickly fake some log lines, instead of reading the actual log.<br> * Set to <= 0 to disable. */ @SuppressWarnings("FieldCanBeLocal") private static int FAKE_LOG_LINES = 0; private static int EMAIL_MAX_KILOBYTES_DEFAULT = FooLogCat.EMAIL_MAX_BYTES_DEFAULT; private static int ACCUMULATOR_MAX = FooLogCat.ACCUMULATOR_MAX; private static final String LINEFEED = FooLogCat.LINEFEED; private static final String TYPEFACE_FAMILY = FooLogCat.TYPEFACE_FAMILY; private static final float TYPEFACE_SIZE = FooLogCat.TYPEFACE_SIZE; private String mUserName; private FooDebugConfiguration mDebugConfiguration; private String mHeader; /** * Raw log file that has not been parsed by LogReaderTask in to LogAdapter */ private String mLogRaw; private Boolean mIsSharedLogFileCompressed; private ViewGroup mGroupProgress; private TextView mTextProgressTitle; private RecyclerView mRecyclerView; private LinearLayoutManager mRecyclerLayoutManager; private LogAdapter mRecyclerAdapter; private int mColorSelected; private int mColorAssert; private int mColorError; private int mColorWarn; private int mColorInfo; private int mColorDebug; private int mColorVerbose; private int mColorOther; private int mLogLimitKb; private int mLogEmailLimitKb; public void showProgressIndicator(String text) { if (FooString.isNullOrEmpty(text)) { mGroupProgress.setVisibility(View.GONE); } else { mTextProgressTitle.setText(text); mGroupProgress.setVisibility(View.VISIBLE); } } /* @Override public String getPermissionRequiredToText(int requestCode, String permissionDenied) { String permissionRationale = null; switch (permissionDenied) { case Manifest.permission.READ_PHONE_STATE: permissionRationale = getString(R.string.phone_state_permission_rationale); break; case Manifest.permission.WRITE_EXTERNAL_STORAGE: permissionRationale = getString(R.string.activity_debug_external_storage_permission_rationale); break; } return permissionRationale; } @Override public boolean onRequestPermissionGranted(int requestCode, String permissionGranted) { switch (permissionGranted) { case Manifest.permission.READ_PHONE_STATE: { loadLog(true); break; } } return false; } */ public static FooDebugApplication getFooDebugApplication(@NonNull Context context) { FooRun.throwIllegalArgumentExceptionIfNull(context, "context"); Application applicationContext = (Application) context.getApplicationContext(); if (!(applicationContext instanceof FooDebugApplication)) { throw new IllegalStateException("Application context must implement FooDebugApplication"); } return (FooDebugApplication) applicationContext; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent != null) { mUserName = intent.getStringExtra(EXTRA_USER_NAME); } FooDebugApplication application = getFooDebugApplication(this); mDebugConfiguration = application.getFooDebugConfiguration(); setContentView(R.layout.activity_debug); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); ProgressBar toolbarProgressBar = (ProgressBar) findViewById(R.id.toolbar_progress_bar); toolbarProgressBar.setVisibility(View.GONE); if (NavUtils.getParentActivityName(this) != null) { ActionBar actionbar = getSupportActionBar(); if (actionbar != null) { actionbar.setHomeButtonEnabled(true); actionbar.setDisplayHomeAsUpEnabled(true); } } } // // NOTE:(pv) For some reason setting visibility to gone in the layout isn't working on some devices. // Forcing it to default to GONE here. // mGroupProgress = (ViewGroup) findViewById(R.id.groupProgress); mTextProgressTitle = (TextView) findViewById(R.id.textProgressTitle); if (savedInstanceState == null) { showProgressIndicator(null); mHeader = null; mLogRaw = null; mLogLimitKb = mDebugConfiguration.getDebugLogLimitKb(EMAIL_MAX_KILOBYTES_DEFAULT); mLogEmailLimitKb = mDebugConfiguration.getDebugLogEmailLimitKb(EMAIL_MAX_KILOBYTES_DEFAULT); } mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mRecyclerLayoutManager); /* // TODO:(pv) Figure out why this fast scroller jumps BACKWARDS so much; fix and then uncomment… VerticalRecyclerViewFastScroller fastScroller = (VerticalRecyclerViewFastScroller) findViewById(R.id.fast_scroller); if (fastScroller != null) { mRecyclerView.setOnScrollListener(fastScroller.getOnScrollListener()); fastScroller.setRecyclerView(mRecyclerView); } */ Resources resources = getResources(); //noinspection deprecation mColorSelected = FooRes.getColor(resources, R.color.log_selected); //noinspection deprecation mColorAssert = FooRes.getColor(resources, R.color.log_level_assert); //noinspection deprecation mColorError = FooRes.getColor(resources, R.color.log_level_error); //noinspection deprecation mColorWarn = FooRes.getColor(resources, R.color.log_level_warn); //noinspection deprecation mColorInfo = FooRes.getColor(resources, R.color.log_level_info); //noinspection deprecation mColorDebug = FooRes.getColor(resources, R.color.log_level_debug); //noinspection deprecation mColorVerbose = FooRes.getColor(resources, R.color.log_level_verbose); //noinspection deprecation mColorOther = FooRes.getColor(resources, R.color.log_level_other); loadLog(false); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("mHeader", mHeader); outState.putString("mLogRaw", mLogRaw); if (mIsSharedLogFileCompressed != null) { outState.putBoolean("mIsSharedLogFileCompressed", mIsSharedLogFileCompressed); } outState.putInt("mLogLimitKb", mLogLimitKb); outState.putInt("mLogEmailLimitKb", mLogEmailLimitKb); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mHeader = savedInstanceState.getString("mHeader"); mLogRaw = savedInstanceState.getString("mLogRaw"); mIsSharedLogFileCompressed = savedInstanceState.getBoolean("mIsSharedLogFileCompressed"); mLogLimitKb = savedInstanceState.getInt("mLogLimitKb"); mLogEmailLimitKb = savedInstanceState.getInt("mLogEmailLimitKb"); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.activity_debug, menu); MenuItem searchItem = menu.findItem(R.id.action_debug_find); if (searchItem != null) { SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); if (searchView != null) { searchView.setOnQueryTextListener(this); } } Intent intent = getIntent(); Bundle extras = intent.getExtras(); boolean isFixedLog = false; if (extras != null) { isFixedLog = (extras.containsKey(EXTRA_MESSAGE) || extras.containsKey(EXTRA_LOG_RAW)); } MenuItem clear = menu.findItem(R.id.action_debug_clear); if (clear != null) { clear.setVisible(!isFixedLog); } MenuItem refresh = menu.findItem(R.id.action_debug_refresh); if (refresh != null) { refresh.setVisible(!isFixedLog); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem logFile = menu.findItem(R.id.action_debug_log_file); if (logFile != null) { boolean isDebugToFileEnabled = mDebugConfiguration.getDebugToFileEnabled(); int resId = isDebugToFileEnabled ? R.string.activity_debug_action_log_file_disable : R.string.activity_debug_action_log_file_enable; logFile.setTitle(resId); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // // NOTE:(pv) Must be an "if" and not a "switch" statement if this project is a Library: // http://tools.android.com/tips/non-constant-fields // http://tools.android.com/recent/switchstatementconversion // A switch statement will cause a "case expressions must be constant expressions" compiler error. // For compatibility reasons, leave it this way even if this project is not a Library. // int itemId = item.getItemId(); if (itemId == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // //NavUtils.navigateUpFromSameTask(this); finish(); return true; } else if (itemId == R.id.action_debug_find) { SearchView searchView = (SearchView) MenuItemCompat.getActionView(item); if (searchView != null) { searchView.setIconified(false); } return true; } else if (itemId == R.id.action_debug_share) { shareLog(); return true; } else if (itemId == R.id.action_debug_clear) { FooLog.clear(); FooLogFilePrinter.deleteLogFile(this); loadLog(true); return true; } else if (itemId == R.id.action_debug_refresh) { loadLog(true); return true; } else if (itemId == R.id.action_debug_set_log_limit) { SetLogLimitDialogFragment dialogFragment = SetLogLimitDialogFragment.newInstance(EMAIL_MAX_KILOBYTES_DEFAULT, mLogLimitKb, mLogEmailLimitKb); dialogFragment.show(getFragmentManager(), FRAGMENT_DIALOG_SET_LOG_LIMIT); return true; } else if (itemId == R.id.action_debug_log_file) { boolean isDebugToFileEnabled = mDebugConfiguration.getDebugToFileEnabled(); setDebugToFileEnabled(!isDebugToFileEnabled); return true; } // TODO:(pv) Enable/Disable Scan Logging else { return super.onOptionsItemSelected(item); } } private void setDebugToFileEnabled(boolean enabled) { /* if (enabled) { ResultSet resultSet = PbPermiso.checkPermissions(this, FooLogFilePrinter.REQUIRED_PERMISSIONS); if (!resultSet.areAllPermissionsGranted()) { mPlatformManager.showToastLong("Storage Permissions denied; Logging to file is disabled.", false); return; } } */ mDebugConfiguration.setDebugToFileEnabled(enabled); FooPlatformUtils.toastLong(this, "Logging to file is " + (enabled ? "enabled" : "disabled") + "."); invalidateOptionsMenu(); } private void loadLog(final boolean reset) { /* PbPermiso.getInstance().requestPermissions(new IOnPermissionResult<Void>() { @Override public Void onPermissionResult(ResultSet resultSet) { loadLogInternal(reset); return null; } @Override public String getPermissionRequiredToText(String permission) { String permissionRationale = null; switch (permission) { case Manifest.permission.READ_PHONE_STATE: permissionRationale = getString(R.string.activity_debug_phone_state_permission_rationale); break; case Manifest.permission.WRITE_EXTERNAL_STORAGE: permissionRationale = getString(R.string.activity_debug_external_storage_permission_rationale); break; } return permissionRationale; } }, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE); */ loadLogInternal(reset); } private void loadLogInternal(boolean reset) { if (reset) { mHeader = null; mLogRaw = null; } if (mHeader == null) { StringBuilder sb = new StringBuilder(); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { String message = extras.getString(EXTRA_MESSAGE); if (!FooString.isNullOrEmpty(message)) { sb.append(message).append(LINEFEED).append(LINEFEED); } } LinkedHashMap<String, String> platformInfoExtras = new LinkedHashMap<>(); if (!FooString.isNullOrEmpty(mUserName)) { platformInfoExtras.put("Username", FooString.quote(mUserName)); } String platformInfo = FooPlatformUtils.getPlatformInfoString(this, platformInfoExtras); sb.append(platformInfo); mHeader = sb.toString(); } mRecyclerAdapter = new LogAdapter(this, mColorSelected, mColorOther); mRecyclerView.setAdapter(mRecyclerAdapter); final long start = System.currentTimeMillis(); final int logLimitBytes = mLogLimitKb * 1024; showProgressIndicator("Loading Log…"); LogReaderTask logReaderTask = new LogReaderTask(this, logLimitBytes, mColorAssert, mColorError, mColorWarn, mColorInfo, mColorDebug, mColorVerbose, mColorOther, new LogReaderTask.LogReaderTaskListener() { @Override public void onLogRawLoaded(String logRaw) { mLogRaw = logRaw; } @Override public void onLogLines(List<Spanned> logLines) { mRecyclerAdapter.addLogLines(logLines); } @Override public void onLogEnd() { SpannableString header = FooString.newSpannableString(mHeader, mColorOther, -1, Typeface.BOLD, TYPEFACE_FAMILY, TYPEFACE_SIZE); mRecyclerAdapter.setHeaderAndMaxLogLength(header, logLimitBytes); long stop = System.currentTimeMillis(); long elapsed = stop - start; int length = mRecyclerAdapter.getLogLength(); FooPlatformUtils.toastLong(FooDebugActivity.this, "onLogEnd: " + elapsed + "ms, " + length + " bytes"); showProgressIndicator(null); } }); logReaderTask.execute(mLogRaw); } private void shareLog() { final boolean isDebugToFileEnabled = mDebugConfiguration.getDebugToFileEnabled(); /* if (isDebugToFileEnabled) { ResultSet resultSet = PbPermiso.checkPermissions(this, FooLogFilePrinter.REQUIRED_PERMISSIONS); if (!resultSet.areAllPermissionsGranted()) { return; } } */ // // Semi-slow on large texts, even on a quad-core...but it *IS* colorized! // new AsyncTask<Void, Integer, Intent>() { // // WARNING: Too large of an email will cause the below Intent.createChooser to throw android.os.TransactionTooLargeException // final int logEmailLimitBytes = mLogEmailLimitKb * 1024; @Override protected void onPreExecute() { showProgressIndicator("Sharing Log…"); } @Override protected void onProgressUpdate(Integer... progress) { // TODO:(pv) Show more visible "Processing…" progress dialog (may be indeterminate)? } @Override protected Intent doInBackground(Void... params) { // TODO:(pv) Find way to make SOLID background color w/ no visible gap between lines // TODO:(pv) quick/efficient Spanned to pdf w/ colorized text on SOLID dark background // http://developer.android.com/reference/android/graphics/pdf/PdfDocument.html (API >= 19) // http://developer.android.com/reference/android/graphics/pdf/PdfDocument.Page.html // http://developer.android.com/reference/android/graphics/Canvas.html // http://developer.android.com/reference/android/graphics/Canvas.html#drawText(java.lang.String, float, float, android.graphics.Paint) SpannableStringBuilder emailMessage = new SpannableStringBuilder(); //noinspection UnnecessaryLocalVariable boolean headerOnly = isDebugToFileEnabled; int maxTextLength = logEmailLimitBytes; List<Spanned> items = mRecyclerAdapter.getItemsCopy(); int positionHightlighted = mRecyclerAdapter.getPositionHighlighted(); if (maxTextLength > 0) { // // Walk items backwards until maxTextLength is reached, // but always include items 0 [header] and 0 [demarkator] // int linefeedLength = LINEFEED.length(); int headerLength = 0; Spanned item; item = items.get(0); // header headerLength += item.length(); emailMessage.append(item); headerLength += linefeedLength; emailMessage.append(LINEFEED); if (!headerOnly) { int itemCount = items.size(); item = items.get(1); // demarkator headerLength += item.length(); emailMessage.append(item); headerLength += linefeedLength; emailMessage.append(LINEFEED); int position = (positionHightlighted != -1) ? positionHightlighted : itemCount; while (position > 2) // first line after the demarkator { // TODO:(pv) publishProgress(); // // NOTE:(pv) We are going iterating and inserting in reverse! // item = items.get(--position); if (emailMessage.length() + item.length() + linefeedLength > maxTextLength) { break; } emailMessage.insert(headerLength, LINEFEED); emailMessage.insert(headerLength, item); } } } else { if (headerOnly) { Spanned item; item = items.get(0); // header emailMessage.append(item); emailMessage.append(LINEFEED); } else { int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { // TODO:(pv) publishProgress(); Spanned item = items.get(i); emailMessage.append(item).append(LINEFEED); if (positionHightlighted != -1 && i > positionHightlighted) { break; } } } } FooLog.d(TAG, "shareLog: emailMessage.length()=" + emailMessage.length()); Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:")); String subject = String.format(getString(R.string.activity_debug_email_subject_formatted), getString(R.string.app_name)); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, emailMessage); intent.setType("text/html"); mIsSharedLogFileCompressed = null; if (isDebugToFileEnabled) { FooLogFilePrinter logFileWriter = FooLogFilePrinter.getInstance(); File logFile; try { logFile = logFileWriter.getCompressedLogFile(true); mIsSharedLogFileCompressed = true; } catch (IOException e1) { logFile = logFileWriter.getUncompressedLogFile(); } Uri logFileUri = Uri.fromFile(logFile); intent.putExtra(Intent.EXTRA_STREAM, logFileUri); } String title = String.format(getString(R.string.activity_debug_send_title_formatted), subject); //noinspection UnnecessaryLocalVariable Intent chooser = Intent.createChooser(intent, title); return chooser; } @Override protected void onPostExecute(Intent chooser) { showProgressIndicator(null); startActivityForResult(chooser, REQUEST_SHARE); } }.execute(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_SHARE: { if (mIsSharedLogFileCompressed != null && mIsSharedLogFileCompressed) { mIsSharedLogFileCompressed = null; try { File logFile = FooLogFilePrinter.getInstance().getCompressedLogFile(false); //noinspection ResultOfMethodCallIgnored logFile.delete(); } catch (IOException e) { // ignore } } break; } } } @Override public void onSetLogLimit(int logLimitKb, int logEmailLimitKb) { mDebugConfiguration.setDebugLogLimitKb(logLimitKb); mDebugConfiguration.setDebugLogEmailLimitKb(logEmailLimitKb); mLogLimitKb = logLimitKb; mLogEmailLimitKb = logEmailLimitKb; loadLog(true); } private static class LogViewHolder extends RecyclerView.ViewHolder { private final TextView mTextView; private LogViewHolder(View itemView) { super(itemView); mTextView = (TextView) itemView.findViewById(R.id.textViewLogLine); } private void onBind(Spanned text, int backgroundColor, OnLongClickListener itemViewOnLongClickListener) { itemView.setOnLongClickListener(itemViewOnLongClickListener); itemView.setTag(this); mTextView.setText(text); mTextView.setBackgroundColor(backgroundColor); } } private static class LogAdapter extends RecyclerView.Adapter<LogViewHolder> implements OnLongClickListener { private final LayoutInflater mLayoutInflater; private final List<Spanned> mItems; private final SpannableStringBuilder mHeader; private final int mColorSelected; private final int mColorOther; private int mItemsTextLength; private int mPositionHighlighted; private LogAdapter(Context context, int colorSelected, int colorOther) { mLayoutInflater = LayoutInflater.from(context); mItems = new ArrayList<>(); mHeader = new SpannableStringBuilder(); mColorSelected = colorSelected; mColorOther = colorOther; clear(false); } private void clear(boolean clearItems) { synchronized (mItems) { setPositionHighlighted(-1); mHeader.clear(); if (clearItems) { mItems.clear(); mItemsTextLength = 0; notifyDataSetChanged(); } } } private int getLogLength() { return mItemsTextLength; } private int findFirstPosition(int offset, String newText) { newText = newText.toLowerCase(Locale.getDefault()); synchronized (mItems) { String itemText; Iterator<Spanned> iterator = mItems.listIterator(offset); while (iterator.hasNext()) { itemText = iterator.next().toString().toLowerCase(Locale.getDefault()); if (itemText.contains(newText)) { return offset; } offset++; } } return -1; } private int getPositionHighlighted() { return mPositionHighlighted; } private void setPositionHighlighted(int position) { int oldPositionHighlighted = mPositionHighlighted; if (position == oldPositionHighlighted) { // Toggle the highlight position = -1; } mPositionHighlighted = position; if (position != -1) { notifyItemChanged(position); } if (oldPositionHighlighted != -1) { notifyItemChanged(oldPositionHighlighted); } } @Override public LogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mLayoutInflater.inflate(R.layout.activity_debug_list_item, parent, false); return new LogViewHolder(view); } @Override public void onBindViewHolder(LogViewHolder holder, int position) { Spanned text = getItemByIndex(position); int backgroundColor = (position == mPositionHighlighted) ? mColorSelected : Color.TRANSPARENT; holder.onBind(text, backgroundColor, this); } @Override public int getItemCount() { synchronized (mItems) { return mItems.size(); } } private List<Spanned> getItemsCopy() { return new ArrayList<>(mItems); } private Spanned getItemByIndex(int position) { synchronized (mItems) { return mItems.get(position); } } /** * @param header header * @param maxLogLength Set to <= 0 to disable. */ private void setHeaderAndMaxLogLength(Spanned header, int maxLogLength) { final Spannable demarkator = FooString.newSpannableString(FooLogCat.HEADER_DEV_LOG_MAIN2, mColorOther, -1, Typeface.BOLD, TYPEFACE_FAMILY, TYPEFACE_SIZE); synchronized (mItems) { clear(false); mHeader // .append(header).append(LINEFEED) // .append(demarkator).append(LINEFEED); // // NOTE: mHeader is mItem[0], demarkator is mItem[1], and first log line is mItem[2] // mItems.add(0, header); mItems.add(1, demarkator); if (maxLogLength > 0) { // // Remove the first log line until the below generated mText would be <= maxTextLength // int headerLength = mHeader.length() + demarkator.length(); Spanned logLine; while (headerLength + mItemsTextLength > maxLogLength) { logLine = mItems.remove(2); // first line after the demarkator mItemsTextLength -= logLine.length() + 1; // + 1 for LINEFEED } } notifyDataSetChanged(); } } /** * @param logLines to insert; the list is reset/cleared if any "null" value is encountered */ private void addLogLines(List<Spanned> logLines) { synchronized (mItems) { for (Spanned logLine : logLines) { if (logLine == null) { // Reset the list clear(true); } else { int oldLastLine = mItems.size(); mItems.add(logLine); mItemsTextLength += logLine.length() + 1; // + 1 for LINEFEED int newLastLine = mItems.size(); notifyItemRangeChanged(oldLastLine, newLastLine); } } } } @Override public boolean onLongClick(View v) { LogViewHolder holder = (LogViewHolder) v.getTag(); int position = holder.getAdapterPosition(); //Context context = v.getContext(); //PbPlatformUtils.toastLong(context, "onLongClick row #" + position); setPositionHighlighted(position); return true; } } private static class LogReaderTask extends AsyncTask<String, List<Spanned>, Void> { private interface LogReaderTaskListener { void onLogRawLoaded(String logRaw); void onLogLines(List<Spanned> logLines); void onLogEnd(); } private final Activity mActivity; private final int mLogLimitBytes; private final LogReaderTaskListener mListener; private final int mColorAssert; private final int mColorError; private final int mColorWarn; private final int mColorInfo; private final int mColorDebug; private final int mColorVerbose; private final int mColorOther; private LogReaderTask(Activity activity, int logLimitBytes, int colorAssert, int colorError, int colorWarn, int colorInfo, int colorDebug, int colorVerbose, int colorOther, LogReaderTaskListener listener) { mActivity = activity; mLogLimitBytes = logLimitBytes; mColorAssert = colorAssert; mColorError = colorError; mColorWarn = colorWarn; mColorInfo = colorInfo; mColorDebug = colorDebug; mColorVerbose = colorVerbose; mColorOther = colorOther; mListener = listener; } @Override protected void onPostExecute(Void result) { mListener.onLogEnd(); } @SuppressWarnings("unchecked") @Override protected void onProgressUpdate(List<Spanned>... progress) { for (List<Spanned> accumulator : progress) { mListener.onLogLines(accumulator); } } @SuppressWarnings("ConstantConditions") @Override protected Void doInBackground(String... params) { String logRaw = params[0]; int pid = FooLogCat.getMyPid(); if (logRaw == null) { if (FAKE_LOG_LINES > 0) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= FAKE_LOG_LINES; i++) { sb.append("00-00 00:00:00.000 123 456 I TAG: #").append(i).append(LINEFEED); } logRaw = sb.toString(); } else { Intent intent = mActivity.getIntent(); Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(EXTRA_LOG_RAW)) { logRaw = extras.getString(EXTRA_LOG_RAW); if (extras.containsKey(EXTRA_LOG_PID)) { pid = extras.getInt(EXTRA_LOG_PID); } } else { // TODO:(pv) load log until *LAST* terminator is found (this is a bit more complicated than it sounds) // "I FooLogCat: TXXXXX +load()" //String terminator = myPid + " " + myTid + " I " + FooLog.TAG(FooLogCat.class) + " T" + myTid + " +load()"; logRaw = FooLogCat.load(mLogLimitBytes);//, terminator); } } mListener.onLogRawLoaded(logRaw); } FooLogCat.process(pid, logRaw, new LogProcessCallbacks() { @Override public int getColorAssert() { return mColorAssert; } @Override public int getColorError() { return mColorError; } @Override public int getColorWarn() { return mColorWarn; } @Override public int getColorInfo() { return mColorInfo; } @Override public int getColorDebug() { return mColorDebug; } @Override public int getColorVerbose() { return mColorVerbose; } @Override public int getColorOther() { return mColorOther; } @Override public String getTypefaceFamily() { return TYPEFACE_FAMILY; } @Override public float getTypefaceSize() { return TYPEFACE_SIZE; } @Override public int getAccumulatorMax() { return ACCUMULATOR_MAX; } @Override public void onLogLines(List<Spanned> logLines) { //noinspection unchecked publishProgress(logLines); } }); return null; } } private int mPositionFound = -1; @Override public boolean onQueryTextSubmit(String query) { findPosition(mPositionFound + 1, query); return true; } @Override public boolean onQueryTextChange(String newText) { // Called when the action bar search text has changed. // Since this is a simple array adapter, we can just have it do the filtering. if (!FooString.isNullOrEmpty(newText)) { int offset; int positionSelected = mRecyclerAdapter.getPositionHighlighted(); if (positionSelected != -1) { offset = positionSelected; } else { offset = mRecyclerLayoutManager.findFirstVisibleItemPosition(); } findPosition(offset, newText); } return true; } private void findPosition(int offset, String query) { if (offset < 0 || offset >= mRecyclerAdapter.getItemCount()) { offset = 0; } mPositionFound = mRecyclerAdapter.findFirstPosition(offset, query); if (mPositionFound != -1) { mRecyclerAdapter.setPositionHighlighted(mPositionFound); mRecyclerView.scrollToPosition(mPositionFound); } else { FooPlatformUtils.toastLong(this, "Reached end of log"); } } }
33.76466
153
0.548344
0ca44c8fb2f2849686efc0aec1bdf7a0e221ccb9
2,883
package com.anker.bluetoothtool.util; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import androidx.recyclerview.widget.RecyclerView; /** * Author: philip.zhang * Time: 2021/1/4 * Description : This is description. */ public class LinearItemDecoration extends RecyclerView.ItemDecoration { private int leftMargin = 0; private int rightMargin = 0; private int mDividerHeight = 2; private int dividerColor; private Paint mPaint; private Context mContext; private Paint whitePaint; public LinearItemDecoration(Context context, int dividerColor) { this.dividerColor = dividerColor; mContext = context; mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(dividerColor); mPaint.setStyle(Paint.Style.FILL); whitePaint = new Paint(Paint.ANTI_ALIAS_FLAG); whitePaint.setColor(Color.WHITE); whitePaint.setStyle(Paint.Style.FILL); } public void setDividerHeight(int height) { this.mDividerHeight = dp2px(height); } public void setLeftMargin(int leftMargin) { this.leftMargin = dp2px(leftMargin); } public void setRightMargin(int rightMargin) { this.rightMargin = dp2px(rightMargin); } @Override public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) { super.onDraw(canvas, parent, state); final int childCount = parent.getChildCount(); @SuppressLint("RtlGetPadding") int left = parent.getPaddingLeft(); @SuppressLint("RtlGetPadding") int right = parent.getWidth() - parent.getPaddingRight(); for (int i = 0; i < childCount - 1; i++) { final View child = parent.getChildAt(i); RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getBottom() + layoutParams.bottomMargin; final int bottom = top + mDividerHeight; if (leftMargin != 0) { canvas.drawRect(left, top, left + leftMargin, bottom, whitePaint); } if (rightMargin != 0) { canvas.drawRect(right - rightMargin, top, right, bottom, whitePaint); } canvas.drawRect(left + leftMargin, top, right - rightMargin, bottom, mPaint); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.set(0, 0, 0, mDividerHeight); } private int dp2px(int dp) { return (int) (mContext.getResources().getDisplayMetrics().density * dp); } }
31.336957
105
0.663892
03397b53061da1041ed876daca273336a307f6d4
594
package com.zednight.utils; import cn.hutool.core.util.RuntimeUtil; public class CaddyUtils { public static boolean isRun() { boolean isRun = false; if (SystemTool.isWindows()) { String[] command = { "tasklist" }; String rs = RuntimeUtil.execForStr(command); isRun = rs.toLowerCase().contains("caddy"); } else { String[] command = { "/bin/sh", "-c", "ps -ef|grep caddy" }; String rs = RuntimeUtil.execForStr(command); isRun = rs.contains("caddy run"); } return isRun; } }
29.7
72
0.560606
4552f141dc295604e8f8c5dadd67a430bbad83cb
1,972
package sample; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javax.swing.text.html.ImageView; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class Controller { private List<String> scores; private ObservableList<String> items; /* @FXML private ImageView play_btn; @FXML private ImageView openLeaderboad;*/ @FXML private Label hghscr; @FXML private ListView<String> listOfScores; public void playGame() throws Exception { Main.playNewGame(); } public void initialize() { hghscr.setText(Integer.toString(MainGame.highscore)); } @FXML public void leaderboardScreen() throws IOException { Parent root = FXMLLoader.load(getClass().getResource("leaderboard.fxml")); Scene scene = new Scene(root, 500, 650); Main.getStage().setScene(scene); /*scores = Main.getRecentScores(); items = FXCollections.observableArrayList(scores); listOfScores.setItems(items);*/ Main.getStage().show(); } public void settingsScreen() throws IOException { Parent root = FXMLLoader.load(getClass().getResource("settings.fxml")); Scene scene = new Scene(root, 500, 650); Main.getStage().setScene(scene); Main.getStage().show(); } public void closeScreen() { Main.getStage().close(); } }
26.648649
82
0.71146
a27397470e601e1d763ec5b10a86778b4017a538
2,656
package me.mical.cleaneraddon.config; import me.mical.cleaneraddon.CleanerAddon; import me.mical.cleaneraddon.utils.DebugPrintUtil; import me.mical.cleaneraddon.utils.MapUtil; import me.mical.cleaneraddon.utils.TempStorage; import org.bukkit.inventory.ItemStack; import org.serverct.parrot.parrotx.api.ParrotXAPI; import org.serverct.parrot.parrotx.config.PConfig; import org.serverct.parrot.parrotx.data.autoload.annotations.PAutoload; import org.serverct.parrot.parrotx.data.autoload.annotations.PAutoloadGroup; import org.serverct.parrot.parrotx.utils.TimeUtil; import org.serverct.parrot.parrotx.utils.i18n.I18n; import java.util.*; @PAutoloadGroup @PAutoload public class DataManager extends PConfig { private static DataManager instance; public DataManager() { super(ParrotXAPI.getPlugin(CleanerAddon.class), "data", "数据文件"); } public static DataManager getInstance() { if (Objects.isNull(instance)) { instance = new DataManager(); } return instance; } @PAutoload("TimeMap") public static Map<Integer, Long> timeMap; @PAutoload("TimeFormatMap") public static Map<Integer, String> timeFormatMap; @PAutoload("ItemMap") public static Map<Integer, List<ItemStack>> itemMap; public int newDataInt() { return timeMap.size() + 1; } public void newData(Long timestamp, List<ItemStack> itemMap) { final int data = newDataInt(); TempStorage.timeMap.put(data, timestamp); TempStorage.formatTimeMap.put(data, TimeUtil.getDefaultFormatDate(new Date(timestamp))); TempStorage.itemMap.put(data, itemMap); DebugPrintUtil.printItemStackList(plugin, data); } @Override public void load() { super.load(); try { TempStorage.timeMap = timeMap; MapUtil.formatMap(timeMap, "timeMap").forEach(s -> lang.log.debug("{0}", s)); TempStorage.formatTimeMap = timeFormatMap; MapUtil.formatMap(timeFormatMap, "timeFormatMap").forEach(s -> lang.log.debug("{0}", s)); TempStorage.itemMap = itemMap; MapUtil.formatMap(itemMap, "itemMap").forEach(s -> lang.log.debug("{0}", s)); lang.log.debug("已成功从临时文件中加载全部数据."); } catch (Throwable e) { lang.log.error(I18n.LOAD, name(), e, null); } } @Override public void save() { getConfig().set("TimeMap", TempStorage.timeMap); getConfig().set("TimeFormatMap", TempStorage.formatTimeMap); getConfig().set("ItemMap", TempStorage.itemMap); super.save(); lang.log.debug("已成功保存全部数据至临时文件."); } }
33.620253
101
0.674322
ee57514d8bfe5b79fe58b9c60ee8de7b20f702e0
6,621
package fi.nls.oskari.control.admin; import java.util.Collections; import java.util.List; import java.util.Set; import fi.nls.oskari.control.*; import fi.nls.oskari.util.PropertyUtil; import org.oskari.log.AuditLog; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.oskari.capabilities.CapabilitiesUpdateResult; import org.oskari.capabilities.CapabilitiesUpdateService; import org.oskari.service.util.ServiceFactory; import fi.mml.map.mapwindow.util.OskariLayerWorker; import fi.nls.oskari.annotation.OskariActionRoute; import fi.nls.oskari.domain.map.OskariLayer; import fi.nls.oskari.map.layer.OskariLayerService; import fi.nls.oskari.map.view.ViewService; import fi.nls.oskari.map.view.util.ViewHelper; import fi.nls.oskari.service.ServiceException; import fi.nls.oskari.service.capabilities.CapabilitiesCacheService; import fi.nls.oskari.util.ResponseHelper; /** * ActionRoute to update the capabilities of layers * Can be called with 'id' parameter where the value is a layer id. * If 'id' can not be parsed into an integer then this action route * will try to update the capabilities of ALL layers. * * Responds with a JSON object describing the result. * The result contains two keys, "success" and "error". * * "success" is an array of the ids of the layers whose * capabilities were succesfully updated. * * "error" is an object consisting of multiple * "{layerId}": "{errorMsg}" entries each describing what * went wrong with updating that particular layer. * * Both "success" and "error" might be empty */ @OskariActionRoute("UpdateCapabilities") public class UpdateCapabilitiesHandler extends RestActionHandler { private OskariLayerService layerService; private CapabilitiesCacheService capabilitiesCacheService; private CapabilitiesUpdateService capabilitiesUpdateService; private ViewService viewService; public UpdateCapabilitiesHandler() { // No-param constructor for @OskariActionRoute } public UpdateCapabilitiesHandler(OskariLayerService layerService, CapabilitiesCacheService capabilitiesCacheService, ViewService viewService) { // Full-param constructor if one is required this.layerService = layerService; this.capabilitiesCacheService = capabilitiesCacheService; this.viewService = viewService; } @Override public void init() { // Lazily populate the fields if they haven't been set by the full-param constructor if (layerService == null) { layerService = ServiceFactory.getMapLayerService(); } if (capabilitiesCacheService == null) { capabilitiesCacheService = ServiceFactory.getCapabilitiesCacheService(); } if (capabilitiesUpdateService == null) { capabilitiesUpdateService = new CapabilitiesUpdateService( layerService, capabilitiesCacheService); } if (viewService == null) { viewService = ServiceFactory.getViewService(); } } @Override public void handlePost(ActionParameters params) throws ActionException { params.requireAdminUser(); String layerId = params.getHttpParam(ActionConstants.KEY_ID); List<OskariLayer> layers = getLayersToUpdate(layerId); Set<String> systemCRSs = getSystemCRSs(); for (OskariLayer layer : layers) { AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", layer.getId()) .withParam("name", layer.getName(PropertyUtil.getDefaultLanguage())) .withParam("url", layer.getUrl()) .withParam("name", layer.getName()) .withMsg("Capabilities update") .updated(AuditLog.ResourceType.MAPLAYER); } List<CapabilitiesUpdateResult> result = capabilitiesUpdateService.updateCapabilities(layers, systemCRSs); JSONObject response = createResponse(result, layerId, params); ResponseHelper.writeResponse(params, response); } private List<OskariLayer> getLayersToUpdate(String layerId) throws ActionParamsException { if (layerId == null) { return layerService.findAll(); } int id = getId(layerId); OskariLayer layer = layerService.find(id); if (layer == null) { throw new ActionParamsException("Unknown layer id:" + id); } return Collections.singletonList(layer); } private int getId(String layerId) throws ActionParamsException { try { return Integer.parseInt(layerId); } catch (NumberFormatException e) { throw new ActionParamsException("Layer id is not a number:" + layerId); } } private Set<String> getSystemCRSs() throws ActionException { try { return ViewHelper.getSystemCRSs(viewService); } catch (ServiceException e) { throw new ActionException("Failed to get systemCRSs", e); } } private JSONObject createResponse(List<CapabilitiesUpdateResult> result, String layerId, ActionParameters params) throws ActionException { try { JSONArray success = new JSONArray(); JSONObject errors = new JSONObject(); for (CapabilitiesUpdateResult r : result) { if (r.getErrorMessage() == null) { success.put(r.getLayerId()); } else { errors.put(r.getLayerId(), r.getErrorMessage()); } } JSONObject response = new JSONObject(); response.put("success", success); response.put("error", errors); if (layerId != null && success.length() == 1) { // If this is a update-single-layer request then add the updated information // Fetch the OskariLayer again to make sure we have all the fields updated in the object OskariLayer layer = layerService.find(getId(layerId)); JSONObject layerJSON = OskariLayerWorker.getMapLayerJSON(layer, params.getUser(), params.getLocale().getLanguage(), params.getHttpParam(ActionConstants.PARAM_SRS)); response.put("layerUpdate", layerJSON); } return response; } catch (JSONException e) { throw new ActionException("Failed to create response JSON", e); } } }
38.271676
117
0.657907
5d41f565257859ebcd464fcf10375391730c4578
25,530
/* * 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.solr.handler.dataimport; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; /** * <p> Test for XPathRecordReader </p> * * * @since solr 1.3 */ public class TestXPathRecordReader extends AbstractDataImportHandlerTestCase { @Test public void testBasic() { String xml="<root>\n" + " <b><c>Hello C1</c>\n" + " <c>Hello C1</c>\n" + " </b>\n" + " <b><c>Hello C2</c>\n" + " </b>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/b"); rr.addField("c", "/root/b/c", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(2, l.size()); assertEquals(2, ((List) l.get(0).get("c")).size()); assertEquals(1, ((List) l.get(1).get("c")).size()); } @Test public void testAttributes() { String xml="<root>\n" + " <b a=\"x0\" b=\"y0\" />\n" + " <b a=\"x1\" b=\"y1\" />\n" + " <b a=\"x2\" b=\"y2\" />\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/b"); rr.addField("a", "/root/b/@a", false); rr.addField("b", "/root/b/@b", false); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(3, l.size()); assertEquals("x0", l.get(0).get("a")); assertEquals("x1", l.get(1).get("a")); assertEquals("x2", l.get(2).get("a")); assertEquals("y0", l.get(0).get("b")); assertEquals("y1", l.get(1).get("b")); assertEquals("y2", l.get(2).get("b")); } @Test public void testAttrInRoot(){ String xml="<r>\n" + "<merchantProduct id=\"814636051\" mid=\"189973\">\n" + " <in_stock type=\"stock-4\" />\n" + " <condition type=\"cond-0\" />\n" + " <price>301.46</price>\n" + " </merchantProduct>\n" + "<merchantProduct id=\"814636052\" mid=\"189974\">\n" + " <in_stock type=\"stock-5\" />\n" + " <condition type=\"cond-1\" />\n" + " <price>302.46</price>\n" + " </merchantProduct>\n" + "\n" + "</r>"; XPathRecordReader rr = new XPathRecordReader("/r/merchantProduct"); rr.addField("id", "/r/merchantProduct/@id", false); rr.addField("mid", "/r/merchantProduct/@mid", false); rr.addField("price", "/r/merchantProduct/price", false); rr.addField("conditionType", "/r/merchantProduct/condition/@type", false); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); Map<String, Object> m = l.get(0); assertEquals("814636051", m.get("id")); assertEquals("189973", m.get("mid")); assertEquals("301.46", m.get("price")); assertEquals("cond-0", m.get("conditionType")); m = l.get(1); assertEquals("814636052", m.get("id")); assertEquals("189974", m.get("mid")); assertEquals("302.46", m.get("price")); assertEquals("cond-1", m.get("conditionType")); } @Test public void testAttributes2Level() { String xml="<root>\n" + "<a>\n <b a=\"x0\" b=\"y0\" />\n" + " <b a=\"x1\" b=\"y1\" />\n" + " <b a=\"x2\" b=\"y2\" />\n" + " </a>" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a/b"); rr.addField("a", "/root/a/b/@a", false); rr.addField("b", "/root/a/b/@b", false); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(3, l.size()); assertEquals("x0", l.get(0).get("a")); assertEquals("y1", l.get(1).get("b")); } @Test public void testAttributes2LevelHetero() { String xml="<root>\n" + "<a>\n <b a=\"x0\" b=\"y0\" />\n" + " <b a=\"x1\" b=\"y1\" />\n" + " <b a=\"x2\" b=\"y2\" />\n" + " </a>" + "<x>\n <b a=\"x4\" b=\"y4\" />\n" + " <b a=\"x5\" b=\"y5\" />\n" + " <b a=\"x6\" b=\"y6\" />\n" + " </x>" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a | /root/x"); rr.addField("a", "/root/a/b/@a", false); rr.addField("b", "/root/a/b/@b", false); rr.addField("a", "/root/x/b/@a", false); rr.addField("b", "/root/x/b/@b", false); final List<Map<String, Object>> a = new ArrayList<>(); final List<Map<String, Object>> x = new ArrayList<>(); rr.streamRecords(new StringReader(xml), (record, xpath) -> { if (record == null) return; if (xpath.equals("/root/a")) a.add(record); if (xpath.equals("/root/x")) x.add(record); }); assertEquals(1, a.size()); assertEquals(1, x.size()); } @Test public void testAttributes2LevelMissingAttrVal() { String xml="<root>\n" + "<a>\n <b a=\"x0\" b=\"y0\" />\n" + " <b a=\"x1\" b=\"y1\" />\n" + " </a>" + "<a>\n <b a=\"x3\" />\n" + " <b b=\"y4\" />\n" + " </a>" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a"); rr.addField("a", "/root/a/b/@a", true); rr.addField("b", "/root/a/b/@b", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(2, l.size()); assertNull(((List) l.get(1).get("a")).get(1)); assertNull(((List) l.get(1).get("b")).get(0)); } @Test public void testElems2LevelMissing() { String xml="<root>\n" + "\t<a>\n" + "\t <b>\n\t <x>x0</x>\n" + "\t <y>y0</y>\n" + "\t </b>\n" + "\t <b>\n\t <x>x1</x>\n" + "\t <y>y1</y>\n" + "\t </b>\n" + "\t </a>\n" + "\t<a>\n" + "\t <b>\n\t <x>x3</x>\n\t </b>\n" + "\t <b>\n\t <y>y4</y>\n\t </b>\n" + "\t </a>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a"); rr.addField("a", "/root/a/b/x", true); rr.addField("b", "/root/a/b/y", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(2, l.size()); assertNull(((List) l.get(1).get("a")).get(1)); assertNull(((List) l.get(1).get("b")).get(0)); } @Test public void testElems2LevelEmpty() { String xml="<root>\n" + "\t<a>\n" + "\t <b>\n\t <x>x0</x>\n" + "\t <y>y0</y>\n" + "\t </b>\n" + "\t <b>\n\t <x></x>\n" // empty + "\t <y>y1</y>\n" + "\t </b>\n" + "\t</a>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a"); rr.addField("a", "/root/a/b/x", true); rr.addField("b", "/root/a/b/y", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(1, l.size()); assertEquals("x0",((List) l.get(0).get("a")).get(0)); assertEquals("y0",((List) l.get(0).get("b")).get(0)); assertEquals("",((List) l.get(0).get("a")).get(1)); assertEquals("y1",((List) l.get(0).get("b")).get(1)); } @Test public void testMixedContent() { String xml = "<xhtml:p xmlns:xhtml=\"http://xhtml.com/\" >This text is \n" + " <xhtml:b>bold</xhtml:b> and this text is \n" + " <xhtml:u>underlined</xhtml:u>!\n" + "</xhtml:p>"; XPathRecordReader rr = new XPathRecordReader("/p"); rr.addField("p", "/p", true); rr.addField("b", "/p/b", true); rr.addField("u", "/p/u", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); Map<String, Object> row = l.get(0); assertEquals("bold", ((List) row.get("b")).get(0)); assertEquals("underlined", ((List) row.get("u")).get(0)); String p = (String) ((List) row.get("p")).get(0); assertTrue(p.contains("This text is")); assertTrue(p.contains("and this text is")); assertTrue(p.contains("!")); // Should not contain content from child elements assertFalse(p.contains("bold")); } @Test public void testMixedContentFlattened() { String xml = "<xhtml:p xmlns:xhtml=\"http://xhtml.com/\" >This text is \n" + " <xhtml:b>bold</xhtml:b> and this text is \n" + " <xhtml:u>underlined</xhtml:u>!\n" + "</xhtml:p>"; XPathRecordReader rr = new XPathRecordReader("/p"); rr.addField("p", "/p", false, XPathRecordReader.FLATTEN); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); Map<String, Object> row = l.get(0); assertEquals("This text is \n" + " bold and this text is \n" + " underlined!", ((String)row.get("p")).trim() ); } @Test public void testElems2LevelWithAttrib() { String xml = "<root>\n\t<a>\n\t <b k=\"x\">\n" + "\t <x>x0</x>\n" + "\t <y></y>\n" // empty + "\t </b>\n" + "\t <b k=\"y\">\n" + "\t <x></x>\n" // empty + "\t <y>y1</y>\n" + "\t </b>\n" + "\t <b k=\"z\">\n" + "\t <x>x2</x>\n" + "\t <y>y2</y>\n" + "\t </b>\n" + "\t </a>\n" + "\t <a>\n\t <b>\n" + "\t <x>x3</x>\n" + "\t </b>\n" + "\t <b>\n" + "\t <y>y4</y>\n" + "\t </b>\n" + "\t </a>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a"); rr.addField("x", "/root/a/b[@k]/x", true); rr.addField("y", "/root/a/b[@k]/y", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(2, l.size()); assertEquals(3, ((List) l.get(0).get("x")).size()); assertEquals(3, ((List) l.get(0).get("y")).size()); assertEquals("x0", ((List) l.get(0).get("x")).get(0)); assertEquals("", ((List) l.get(0).get("y")).get(0)); assertEquals("", ((List) l.get(0).get("x")).get(1)); assertEquals("y1", ((List) l.get(0).get("y")).get(1)); assertEquals("x2", ((List) l.get(0).get("x")).get(2)); assertEquals("y2", ((List) l.get(0).get("y")).get(2)); assertEquals(0, l.get(1).size()); } @Test public void testElems2LevelWithAttribMultiple() { String xml="<root>\n" + "\t<a>\n\t <b k=\"x\" m=\"n\" >\n" + "\t <x>x0</x>\n" + "\t <y>y0</y>\n" + "\t </b>\n" + "\t <b k=\"y\" m=\"p\">\n" + "\t <x>x1</x>\n" + "\t <y>y1</y>\n" + "\t </b>\n" + "\t </a>\n" + "\t<a>\n\t <b k=\"x\">\n" + "\t <x>x3</x>\n" + "\t </b>\n" + "\t <b m=\"n\">\n" + "\t <y>y4</y>\n" + "\t </b>\n" + "\t </a>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a"); rr.addField("x", "/root/a/b[@k][@m='n']/x", true); rr.addField("y", "/root/a/b[@k][@m='n']/y", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(2, l.size()); assertEquals(1, ((List) l.get(0).get("x")).size()); assertEquals(1, ((List) l.get(0).get("y")).size()); assertEquals(0, l.get(1).size()); } @Test public void testElems2LevelWithAttribVal() { String xml="<root>\n\t<a>\n <b k=\"x\">\n" + "\t <x>x0</x>\n" + "\t <y>y0</y>\n" + "\t </b>\n" + "\t <b k=\"y\">\n" + "\t <x>x1</x>\n" + "\t <y>y1</y>\n" + "\t </b>\n" + "\t </a>\n" + "\t <a>\n <b><x>x3</x></b>\n" + "\t <b><y>y4</y></b>\n" + "\t</a>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/a"); rr.addField("x", "/root/a/b[@k='x']/x", true); rr.addField("y", "/root/a/b[@k='x']/y", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(2, l.size()); assertEquals(1, ((List) l.get(0).get("x")).size()); assertEquals(1, ((List) l.get(0).get("y")).size()); assertEquals(0, l.get(1).size()); } @Test public void testAttribValWithSlash() { String xml = "<root><b>\n" + " <a x=\"a/b\" h=\"hello-A\"/> \n" + "</b></root>"; XPathRecordReader rr = new XPathRecordReader("/root/b"); rr.addField("x", "/root/b/a[@x='a/b']/@h", false); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(1, l.size()); Map<String, Object> m = l.get(0); assertEquals("hello-A", m.get("x")); } @Test public void testUnsupported_Xpaths() { String xml = "<root><b><a x=\"a/b\" h=\"hello-A\"/> </b></root>"; XPathRecordReader rr=null; try { rr = new XPathRecordReader("//b"); fail("A RuntimeException was expected: //b forEach cannot begin with '//'."); } catch (RuntimeException ex) { } try { rr.addField("bold" ,"b", false); fail("A RuntimeException was expected: 'b' xpaths must begin with '/'."); } catch (RuntimeException ex) { } } @Test public void testAny_decendent_from_root() { XPathRecordReader rr = new XPathRecordReader("/anyd/contenido"); rr.addField("descdend", "//boo", true); rr.addField("inr_descd","//boo/i", false); rr.addField("cont", "/anyd/contenido", false); rr.addField("id", "/anyd/contenido/@id", false); rr.addField("status", "/anyd/status", false); rr.addField("title", "/anyd/contenido/titulo", false,XPathRecordReader.FLATTEN); rr.addField("resume", "/anyd/contenido/resumen",false); rr.addField("text", "/anyd/contenido/texto", false); String xml="<anyd>\n" + " this <boo>top level</boo> is ignored because it is external to the forEach\n" + " <status>as is <boo>this element</boo></status>\n" + " <contenido id=\"10097\" idioma=\"cat\">\n" + " This one is <boo>not ignored as it's</boo> inside a forEach\n" + " <antetitulo><i> big <boo>antler</boo></i></antetitulo>\n" + " <titulo> My <i>flattened <boo>title</boo></i> </titulo>\n" + " <resumen> My summary <i>skip this!</i> </resumen>\n" + " <texto> <boo>Within the body of</boo>My text</texto>\n" + " <p>Access <boo>inner <i>sub clauses</i> as well</boo></p>\n" + " </contenido>\n" + "</anyd>"; List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(1, l.size()); Map<String, Object> m = l.get(0); assertEquals("This one is inside a forEach", m.get("cont").toString().trim()); assertEquals("10097" ,m.get("id")); assertEquals("My flattened title" ,m.get("title").toString().trim()); assertEquals("My summary" ,m.get("resume").toString().trim()); assertEquals("My text" ,m.get("text").toString().trim()); assertEquals("not ignored as it's",(String) ((List) m.get("descdend")).get(0) ); assertEquals("antler" ,(String) ((List) m.get("descdend")).get(1) ); assertEquals("Within the body of" ,(String) ((List) m.get("descdend")).get(2) ); assertEquals("inner as well" ,(String) ((List) m.get("descdend")).get(3) ); assertEquals("sub clauses" ,m.get("inr_descd").toString().trim()); } @Test public void testAny_decendent_of_a_child1() { XPathRecordReader rr = new XPathRecordReader("/anycd"); rr.addField("descdend", "/anycd//boo", true); // same test string as above but checking to see if *all* //boo's are collected String xml="<anycd>\n" + " this <boo>top level</boo> is ignored because it is external to the forEach\n" + " <status>as is <boo>this element</boo></status>\n" + " <contenido id=\"10097\" idioma=\"cat\">\n" + " This one is <boo>not ignored as it's</boo> inside a forEach\n" + " <antetitulo><i> big <boo>antler</boo></i></antetitulo>\n" + " <titulo> My <i>flattened <boo>title</boo></i> </titulo>\n" + " <resumen> My summary <i>skip this!</i> </resumen>\n" + " <texto> <boo>Within the body of</boo>My text</texto>\n" + " <p>Access <boo>inner <i>sub clauses</i> as well</boo></p>\n" + " </contenido>\n" + "</anycd>"; List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(1, l.size()); Map<String, Object> m = l.get(0); assertEquals("top level" ,(String) ((List) m.get("descdend")).get(0) ); assertEquals("this element" ,(String) ((List) m.get("descdend")).get(1) ); assertEquals("not ignored as it's",(String) ((List) m.get("descdend")).get(2) ); assertEquals("antler" ,(String) ((List) m.get("descdend")).get(3) ); assertEquals("title" ,(String) ((List) m.get("descdend")).get(4) ); assertEquals("Within the body of" ,(String) ((List) m.get("descdend")).get(5) ); assertEquals("inner as well" ,(String) ((List) m.get("descdend")).get(6) ); } @Test public void testAny_decendent_of_a_child2() { XPathRecordReader rr = new XPathRecordReader("/anycd"); rr.addField("descdend", "/anycd/contenido//boo", true); // same test string as above but checking to see if *some* //boo's are collected String xml="<anycd>\n" + " this <boo>top level</boo> is ignored because it is external to the forEach\n" + " <status>as is <boo>this element</boo></status>\n" + " <contenido id=\"10097\" idioma=\"cat\">\n" + " This one is <boo>not ignored as it's</boo> inside a forEach\n" + " <antetitulo><i> big <boo>antler</boo></i></antetitulo>\n" + " <titulo> My <i>flattened <boo>title</boo></i> </titulo>\n" + " <resumen> My summary <i>skip this!</i> </resumen>\n" + " <texto> <boo>Within the body of</boo>My text</texto>\n" + " <p>Access <boo>inner <i>sub clauses</i> as well</boo></p>\n" + " </contenido>\n" + "</anycd>"; List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(1, l.size()); Map<String, Object> m = l.get(0); assertEquals("not ignored as it's",((List) m.get("descdend")).get(0) ); assertEquals("antler" ,((List) m.get("descdend")).get(1) ); assertEquals("title" ,((List) m.get("descdend")).get(2) ); assertEquals("Within the body of" ,((List) m.get("descdend")).get(3) ); assertEquals("inner as well" ,((List) m.get("descdend")).get(4) ); } @Test public void testAnother() { String xml="<root>\n" + " <contenido id=\"10097\" idioma=\"cat\">\n" + " <antetitulo></antetitulo>\n" + " <titulo> This is my title </titulo>\n" + " <resumen> This is my summary </resumen>\n" + " <texto> This is the body of my text </texto>\n" + " </contenido>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/contenido"); rr.addField("id", "/root/contenido/@id", false); rr.addField("title", "/root/contenido/titulo", false); rr.addField("resume","/root/contenido/resumen",false); rr.addField("text", "/root/contenido/texto", false); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals(1, l.size()); Map<String, Object> m = l.get(0); assertEquals("10097", m.get("id")); assertEquals("This is my title", m.get("title").toString().trim()); assertEquals("This is my summary", m.get("resume").toString().trim()); assertEquals("This is the body of my text", m.get("text").toString() .trim()); } @Test public void testSameForEachAndXpath(){ String xml="<root>\n" + " <cat>\n" + " <name>hello</name>\n" + " </cat>\n" + " <item name=\"item name\"/>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/cat/name"); rr.addField("catName", "/root/cat/name",false); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); assertEquals("hello",l.get(0).get("catName")); } @Test public void testPutNullTest(){ String xml = "<root>\n" + " <i>\n" + " <x>\n" + " <a>A.1.1</a>\n" + " <b>B.1.1</b>\n" + " </x>\n" + " <x>\n" + " <b>B.1.2</b>\n" + " <c>C.1.2</c>\n" + " </x>\n" + " </i>\n" + " <i>\n" + " <x>\n" + " <a>A.2.1</a>\n" + " <c>C.2.1</c>\n" + " </x>\n" + " <x>\n" + " <b>B.2.2</b>\n" + " <c>C.2.2</c>\n" + " </x>\n" + " </i>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/i"); rr.addField("a", "/root/i/x/a", true); rr.addField("b", "/root/i/x/b", true); rr.addField("c", "/root/i/x/c", true); List<Map<String, Object>> l = rr.getAllRecords(new StringReader(xml)); Map<String, Object> map = l.get(0); List<String> a = (List<String>) map.get("a"); List<String> b = (List<String>) map.get("b"); List<String> c = (List<String>) map.get("c"); assertEquals("A.1.1",a.get(0)); assertEquals("B.1.1",b.get(0)); assertNull(c.get(0)); assertNull(a.get(1)); assertEquals("B.1.2",b.get(1)); assertEquals("C.1.2",c.get(1)); map = l.get(1); a = (List<String>) map.get("a"); b = (List<String>) map.get("b"); c = (List<String>) map.get("c"); assertEquals("A.2.1",a.get(0)); assertNull(b.get(0)); assertEquals("C.2.1",c.get(0)); assertNull(a.get(1)); assertEquals("B.2.2",b.get(1)); assertEquals("C.2.2",c.get(1)); } @Test public void testError(){ String malformedXml = "<root>\n" + " <node>\n" + " <id>1</id>\n" + " <desc>test1</desc>\n" + " </node>\n" + " <node>\n" + " <id>2</id>\n" + " <desc>test2</desc>\n" + " </node>\n" + " <node>\n" + " <id/>3</id>\n" + // invalid XML " <desc>test3</desc>\n" + " </node>\n" + "</root>"; XPathRecordReader rr = new XPathRecordReader("/root/node"); rr.addField("id", "/root/node/id", true); rr.addField("desc", "/root/node/desc", true); try { rr.getAllRecords(new StringReader(malformedXml)); fail("A RuntimeException was expected: the input XML is invalid."); } catch (Exception e) { } } }
42.621035
96
0.469487
e3339a2b8a77fb66d297e34bc52c8065c15f765a
2,086
package api_testing.lfuentes.restassured; import org.junit.*; import static io.restassured.RestAssured.*; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; public class Covid_Data { //variables del encabezado String key; String host; //parametros String name; String date; @Before public void init() { baseURI = "https://covid-19-data.p.rapidapi.com"; //parametros this.name = "USA"; this.date = "2020-04-01"; //encabezados this.key = "65c3a8ec1emsh38db88917d7c333p1cd20ajsn923976797f86"; this.host = "covid-19-data.p.rapidapi.com"; } @Test public void ATC01_Respuesta_Valida() { given().header("x-rapidapi-key", this.key). and().header("x-rapidapi-host", this.host). param("name", this.name). param("date", this.date). when(). get("/report/country/name"). then().assertThat().statusCode(200); } @Test public void ATC02_PaisSolicitado() { given().header("x-rapidapi-key", this.key). and().header("x-rapidapi-host", this.host). param("name", this.name). param("date", this.date). when(). get("/report/country/name"). then(). assertThat().statusCode(200). body("country[0]", equalTo("USA")); } @Test public void ATC04_Estructura() { given().header("x-rapidapi-key", this.key). and().header("x-rapidapi-host", this.host). param("name", this.name). param("date", this.date). when(). get("/report/country/name"). then(). body("[0]", hasKey("country")). body("[0]", hasKey("provinces")). body("[0]", hasKey("latitude")). body("[0]", hasKey("longitude")). body("[0]", hasKey("date")); } }
27.447368
72
0.511985
d80f3e1d9fcb0ba16d6c2fc2f768168fa5b0e412
8,353
package ecommercejava.cms.icommyjava.helper; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; import ecommercejava.cms.icommyjava.Helpers; import ecommercejava.cms.icommyjava.entity.Lang; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; import java.lang.reflect.Type; import java.util.List; import java.util.Map; @Component public class Language extends HelpersJson{ public static List<String> engLang = null; /** * will translate by string for multilanguage * @param text * @return */ public static String getTranslateByLang(String text, String lang) { ObjectMapper objectMapper = new ObjectMapper(); //myList.stream().anyMatch(str -> str.trim().equals("B")) if(engLang ==null){ try{ engLang = getEnLang(); }catch (Exception e){ } }else { String newTxt = text.toLowerCase().trim(); if(!engLang.stream().anyMatch(str -> str.trim().equals(newTxt)) && !newTxt.isEmpty()){ engLang.add(newTxt); } } if(lang.contains("en") || lang.isEmpty()) return text; //create ObjectMapper instance String value = text; String newTxt = text.trim().toLowerCase(); try{ //convert json file to map Map<String, String> map = objectMapper.readValue(readFile("content/lang/"+lang+".json"), Map.class); value = map.containsKey(newTxt) ? map.get(newTxt) : text; }catch (Exception e){ //System.out.println( "Error read file: " + e); } return value; } /** * Get lang file * @return */ public static Map<String, String> getLang(String name){ if(name == null || name.contains("en")) return null; try{ String langFiele = readFile("content/lang/"+name+".json"); Type type = new TypeToken<Map<String, String>>(){}.getType(); return (new Gson()).fromJson(langFiele, type); }catch (Exception e){return null;} } /** * Get lang file * @return */ public static List<String> getEnLang(){ String langFiele = readFile("content/lang/en.json"); Type type = new TypeToken<List<String>>(){}.getType(); return (new Gson()).fromJson(langFiele, type); } public static String splitLang(String json){ String lang = currentLang(); try{ Gson gson = new Gson(); Lang language = gson.fromJson(json, Lang.class); return language.get(lang); }catch (Exception e){ return json; } } public static String splitLangByLang(String json, String lang){ try{ Gson gson = new Gson(); Lang language = gson.fromJson(json, Lang.class); return language.get(lang); }catch (Exception e){ return json; } } public static String getLangDataByLang(Lang ittem, String Lang){ if(ittem == null){ return ""; }else{ Lang lang = ittem; return lang.get(Lang); } } public static String getLangData(Lang ittem){ String currentLang = currentLang(); if(ittem == null){ return ""; }else{ Lang lang = ittem; return lang.get(currentLang); } } public static Lang saveSimple(String text, Lang existing, String lang ){ Lang mlang = existing == null ? new Lang(): existing; mlang.set(lang, text==null? "": text ); return mlang; } public static String saveLang(String text, String existin, String lang ){ lang = lang.isEmpty() ? "en" : lang; Lang lanCheck = new Lang(); lanCheck.set(lang, "nothing"); lang = lanCheck.get(lang).isEmpty() ? "en" : lang; Gson gson = new GsonBuilder().disableHtmlEscaping().create(); try{ Lang language = gson.fromJson(existin, Lang.class); language.set(lang, text); return gson.toJson(language); }catch (Exception e){ System.out.println("eeeerrr:"+e); try{ Lang language = new Lang(); language.set(lang, text); return gson.toJson(language); }catch (Exception dd){ System.out.println("eeeerrr2:"+dd); return text; } } } public static JsonElement getConfigVar(String key, String secondKey){ String data = stringConfig(); JsonElement element = returnAttr(data, key); if(element !=null) { if (secondKey != null) { return element.getAsJsonObject().get(secondKey); } } return element; } public static String getLangFromUrl(){ //ServletUriComponentsBuilder.fromCurrentContextPath() // return http://localhost:8999 //ServletUriComponentsBuilder.fromCurrentServletMapping().toUriString() // return the domain name http://localhost:8999 //ServletUriComponentsBuilder.fromCurrentRequest().toUriString() // return full url http://localhost:8999/cat/become-milionare/laptops?id=dsg // add on the end .toUriString() String lang=""; String uri = ServletUriComponentsBuilder.fromCurrentRequest().toUriString(); try { MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(uri).build().getQueryParams(); lang = parameters.get("wlang").get(0); }catch (Exception e){} lang = lang == null || lang.isEmpty() ? HelpersJson.getConfig().getLanguages().get(0) : lang; // if(uri.contains("/admin")) { // }else{ //lang = getCookie("language").isEmpty()? HelpersJson.getConfig().getLanguages().get(0) : getCookie("language"); //} return lang; } public static List<String> listLang(){ return getConfig().getLanguages(); } public static String adminLanguage(){ List<String> listlang= getConfig().getLanguages(); String baseurl = getConfig().getMinOptions().getBaseurl(); String ll= "<div class=\"col-md-12\">"+ "<p class=\"lang_menu\">"; String currentLang = getLangFromUrl(); String uri = ServletUriComponentsBuilder.fromCurrentRequest().toUriString(); for(int i=0; i<listlang.size(); i++){ String urifinal = !uri.contains("wlang") ? (uri.contains("?") ? uri+"&wlang="+listlang.get(i) : uri+"?wlang="+listlang.get(i)): uri.replace("wlang="+currentLang,"wlang="+listlang.get(i)); String line = i == 0 ? "" : "|"; String className = currentLang.contains(listlang.get(i)) || ( currentLang.isEmpty() && i == 0 ) ? "activLang":""; ll= ll+ line+ "<a href=\""+urifinal+"\" class=\""+className+"\"> <img src=\""+baseurl+"content/views/assets/langicon/"+listlang.get(i).toUpperCase()+".png\"/> "+listlang.get(i).toUpperCase()+"</a>"; } ll= ll + " <a href=\""+baseurl+"admin/general-settings/language\" target=\"_blank\"><i class=\"fa fa-pencil\"></i></a> \n" + " </p>\n" + " </div>\n" + " <div class=\"clear\"> </div>"; return ll; } public static String currentLang(){ List<String> listlang= Helpers.listLang(); String currentLang = getLangFromUrl(); return currentLang.isEmpty() ? listlang.get(0) : currentLang; } public static String currentLangForUrl(){ List<String> listlang= Helpers.listLang(); String currentLang = getLangFromUrl(); return currentLang.isEmpty()? "": (listlang.get(0).contains(currentLang)? "" : "/"+currentLang ); } }
32.885827
216
0.57189
8d3bd5c2bd70290485d83b606245cc23a6b648dd
1,142
package org.xson.web.handler; import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletResponse; import org.xson.common.object.XCO; import org.xson.web.RequestContext; import org.xson.web.ResponseHandler; public class DefaultXCOResponseHandler implements ResponseHandler { @Override public void onSuccess(RequestContext context) throws IOException { XCO result = (XCO) context.getResult(); if (null != result) { HttpServletResponse response = context.getResponse(); response.setContentType("text/xml;charset=utf-8"); response.setCharacterEncoding("UTF-8"); Writer write = response.getWriter(); write.write(result.toString()); write.close(); } } @Override public void onError(RequestContext context) throws IOException { XCO errorResult = new XCO(); setXCOResult(errorResult, context.getCode(), context.getMessage()); context.setResult(errorResult); onSuccess(context); } private void setXCOResult(XCO xco, int code, String message) { xco.setIntegerValue("$$CODE", code); xco.setStringValue("$$MESSAGE", message); } }
27.190476
70
0.723292
cd34caf1c9d0e588ff1523865ac2269c1ba9cc09
7,347
package com.guo.android_extend.widget; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.hardware.Camera.Size; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.guo.android_extend.tools.FrameHelper; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * create by gqjjqg,. * easy to use camera. */ public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback, PreviewCallback, CameraGLSurfaceView.OnRenderListener { private final String TAG = this.getClass().getSimpleName(); private Camera mCamera; private int mWidth, mHeight, mFormat; private OnCameraListener mOnCameraListener; private FrameHelper mFrameHelper; private CameraGLSurfaceView mGLSurfaceView; private BlockingQueue<CameraFrameData> mImageDataBuffers; public interface OnCameraListener { /** * setup camera. * @return the camera */ public Camera setupCamera(); /** * reset on surfaceChanged. * @param format image format. * @param width width * @param height height. */ public void setupChanged(int format, int width, int height); /** * start preview immediately, after surfaceCreated * @return true or false. */ public boolean startPreviewImmediately(); /** * on ui thread. * @param data image data * @param width width * @param height height * @param format format * @param timestamp time stamp * @return image params. */ public Object onPreview(byte[] data, int width, int height, int format, long timestamp); public void onBeforeRender(CameraFrameData data); public void onAfterRender(CameraFrameData data); } public CameraSurfaceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub onCreate(); } public CameraSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub onCreate(); } public CameraSurfaceView(Context context) { super(context); // TODO Auto-generated constructor stub onCreate(); } private void onCreate() { SurfaceHolder arg0 = getHolder(); arg0.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); arg0.addCallback(this); mFrameHelper = new FrameHelper(); mImageDataBuffers = new LinkedBlockingQueue<>(); mGLSurfaceView = null; } public boolean startPreview() { Size imageSize = mCamera.getParameters().getPreviewSize(); int lineBytes = imageSize.width * ImageFormat.getBitsPerPixel(mCamera.getParameters().getPreviewFormat()) / 8; mCamera.setPreviewCallbackWithBuffer(this); mCamera.addCallbackBuffer(new byte[lineBytes * imageSize.height]); mCamera.addCallbackBuffer(new byte[lineBytes * imageSize.height]); mCamera.addCallbackBuffer(new byte[lineBytes * imageSize.height]); mCamera.startPreview(); return true; } public boolean stopPreview() { mCamera.setPreviewCallbackWithBuffer(null); mCamera.stopPreview(); return true; } /** * used for front and rear exchange. * * @return */ public boolean resetCamera() { if (closeCamera()) { if (openCamera()) { return true; } } Log.e(TAG, "resetCamera fail!"); return false; } private boolean openCamera() { try { if (mCamera != null) { mCamera.reconnect(); } else { if (mOnCameraListener != null) { mCamera = mOnCameraListener.setupCamera(); } } if (mCamera != null) { mCamera.setPreviewDisplay(getHolder()); Size imageSize = mCamera.getParameters().getPreviewSize(); mWidth = imageSize.width; mHeight = imageSize.height; mFormat = mCamera.getParameters().getPreviewFormat(); if (mGLSurfaceView != null) { mGLSurfaceView.setImageConfig(mWidth, mHeight, mFormat); mGLSurfaceView.setAspectRatio(mWidth, mHeight); int lineBytes = imageSize.width * ImageFormat.getBitsPerPixel(mFormat) / 8; mImageDataBuffers.offer(new CameraFrameData(mWidth, mHeight, mFormat, lineBytes * mHeight)); mImageDataBuffers.offer(new CameraFrameData(mWidth, mHeight, mFormat, lineBytes * mHeight)); mImageDataBuffers.offer(new CameraFrameData(mWidth, mHeight, mFormat, lineBytes * mHeight)); } if (mOnCameraListener != null) { if (mOnCameraListener.startPreviewImmediately()) { startPreview(); } else { Log.w(TAG, "Camera not start preview!"); } } return true; } } catch (Exception e) { e.printStackTrace(); } return false; } private boolean closeCamera() { try { if (mCamera != null) { mCamera.setPreviewCallbackWithBuffer(null); mCamera.stopPreview(); mCamera.release(); mCamera = null; } mImageDataBuffers.clear(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub if (mOnCameraListener != null) { mOnCameraListener.setupChanged(format, width, height); } } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub if (!openCamera()) { Log.e(TAG, "camera start fail!"); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub if (!closeCamera()) { Log.e(TAG, "camera close fail!"); } } @Override public void onPreviewFrame(byte[] data, Camera camera) { // TODO Auto-generated method stub long timestamp = System.nanoTime(); mFrameHelper.printFPS(); if (mGLSurfaceView != null) { CameraFrameData imageData = mImageDataBuffers.poll(); if (imageData != null) { byte[] buffer = imageData.mData; System.arraycopy(data, 0, buffer, 0, buffer.length); if (mOnCameraListener != null) { imageData.mParams = mOnCameraListener.onPreview(buffer, mWidth, mHeight, mFormat, timestamp); } mGLSurfaceView.requestRender(imageData); } } else { if (mOnCameraListener != null) { mOnCameraListener.onPreview(data.clone(), mWidth, mHeight, mFormat, timestamp); } } if (mCamera != null) { mCamera.addCallbackBuffer(data); } } @Override public void onBeforeRender(CameraFrameData data) { if (mOnCameraListener != null) { data.mTimeStamp = System.nanoTime(); mOnCameraListener.onBeforeRender(data); } } @Override public void onAfterRender(CameraFrameData data) { if (mOnCameraListener != null) { data.mTimeStamp = System.nanoTime(); mOnCameraListener.onAfterRender(data); } if (!mImageDataBuffers.offer(data)) { Log.e(TAG, "PREVIEW QUEUE FULL!"); } } public void setOnCameraListener(OnCameraListener l) { mOnCameraListener = l; } public void setupGLSurafceView(CameraGLSurfaceView glv, boolean autofit, int mirror, int render_egree) { mGLSurfaceView = glv; mGLSurfaceView.setOnRenderListener(this); mGLSurfaceView.setRenderConfig(render_egree, mirror); mGLSurfaceView.setAutoFitMax(autofit); } public void debug_print_fps(boolean preview, boolean render) { if (mGLSurfaceView != null) { mGLSurfaceView.debug_print_fps(render); } mFrameHelper.enable(preview); } }
26.912088
141
0.717163
8e5eab7b24bf7de97730cae02086f884fc6a7d08
1,201
/* * (C) Copyright 2010 Nuxeo SA (http://nuxeo.com/) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Nuxeo - initial API and implementation */ package org.nuxeo.ecm.platform.ui.web.auth.simple; import java.util.HashMap; import java.util.Map; import org.jboss.seam.mock.MockHttpServletResponse; public class MockHttpResponse extends MockHttpServletResponse { protected final Map<String, String> headers = new HashMap<String, String>(); @Override public void setHeader(String key, String value) { if (value == null) { headers.remove(value); } else { headers.put(key, value); } } }
29.292683
80
0.698585
9c7ab459d9b29aed6d4c80bd1955277d4741f5ce
1,108
// github.com/RodneyShag package _17_08_Circus_Tower; import java.util.*; public class CircusTower { public static int findMax(int[][] persons) { if (persons == null || persons.length == 0 || persons[0].length != 2) { return 0; } Arrays.sort(persons, (a, b) -> { if (a[0] != b[0]) { return a[0] - b[0]; } else { return b[1] - a[1]; } }); int[] sortedArray = new int[persons.length]; int size = 0; for (int[] person : persons) { int num = person[1]; int start = 0; int end = size; // 1 element past end of our sortedArray while (start != end) { int mid = (start + end) / 2; if (sortedArray[mid] < num) { start = mid + 1; } else { end = mid; } } sortedArray[start] = num; if (start == size) { size++; } } return size; } }
26.380952
79
0.400722
aeff123611239970d563b12ad6b4a43a90bd92db
2,789
package com.zuoxiaolong.deerlet.redis.client.util; import com.zuoxiaolong.deerlet.redis.client.io.MultibulkOutputStream; import java.io.IOException; /** * * 协议工具类,封装了一些响应解析的操作 * * @author zuoxiaolong * @since 2015 2015年3月6日 下午11:44:47 * */ public abstract class ProtocolUtil { private static final int defaultNumber = 1; private static final String trueResultPrefix = "+"; private static final String falseResultPrefix = "-"; private static final String intResultPrefix = ":"; private static final String stringLengthResultPrefix = "$"; private static final String arrayLengthResultPrefix = "*"; private static final byte stringLengthResultPrefixByte = '$'; private static final byte arrayLengthResultPrefixByte = '*'; public static void sendCommand(MultibulkOutputStream outputStream, final byte[] command, final byte[]... args) { try { outputStream.write(arrayLengthResultPrefixByte); outputStream.writeIntCrLf(args.length + 1); outputStream.write(stringLengthResultPrefixByte); outputStream.writeIntCrLf(command.length); outputStream.write(command); outputStream.writeCrLf(); for (final byte[] arg : args) { outputStream.write(stringLengthResultPrefixByte); outputStream.writeIntCrLf(arg.length); outputStream.write(arg); outputStream.writeCrLf(); } } catch (IOException e) { throw new RuntimeException(e); } } public static boolean isOk(String response) { return response != null && response.startsWith(trueResultPrefix); } public static boolean isError(String response) { return response != null && response.startsWith(falseResultPrefix); } public static boolean isStringLengthResultOk(String response) { return response != null && response.startsWith(stringLengthResultPrefix); } public static boolean isIntResultOk(String response) { return response != null && response.startsWith(intResultPrefix); } public static boolean isArrayLengthResultOk(String response) { return response != null && response.startsWith(arrayLengthResultPrefix); } public static boolean intResultToBooleanResult(String response) { return intResultToBooleanResult(defaultNumber, response); } public static boolean intResultToBooleanResult(int number, String response) { return response != null && isIntResultOk(response) && intResultToBooleanResult(number, Integer.valueOf(extractResult(response))); } public static boolean intResultToBooleanResult(int intResult) { return intResultToBooleanResult(defaultNumber, intResult); } public static boolean intResultToBooleanResult(int number, int intResult) { return intResult >= number; } public static String extractResult(String response) { return (response == null || response.length() == 0) ? null : response.substring(1); } }
29.989247
131
0.760846
dbe69aa0b2b93d263c41c32b5088560e6b752ed5
1,194
package com.example.myapplication.Utils; import android.content.Context; import android.os.Bundle; import com.example.myapplication.R; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentTransaction; public class ChangeFragments { private Context context; public ChangeFragments(Context context) { this.context=context; } public void change(Fragment fragment) { ((FragmentActivity)context).getSupportFragmentManager().beginTransaction() .replace(R.id.mainFrameLayout,fragment, "fragment") .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); } public void changeWidthParameter(Fragment fragment,String petId) { Bundle bundle = new Bundle(); bundle.putString("petid",petId); fragment.setArguments(bundle); ((FragmentActivity)context).getSupportFragmentManager().beginTransaction() .replace(R.id.mainFrameLayout,fragment, "fragment") .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); } }
29.85
82
0.695142
14af6b4ade552946a3dabf6c3eee2b28c9856ce8
12,022
/* * Copyright 2018 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.internal; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import io.grpc.Attributes; import io.grpc.ChannelLogger.ChannelLogLevel; import io.grpc.ConnectivityState; import io.grpc.ConnectivityStateInfo; import io.grpc.EquivalentAddressGroup; import io.grpc.LoadBalancer; import io.grpc.LoadBalancer.Helper; import io.grpc.LoadBalancer.PickResult; import io.grpc.LoadBalancer.PickSubchannelArgs; import io.grpc.LoadBalancer.SubchannelPicker; import io.grpc.LoadBalancerProvider; import io.grpc.LoadBalancerRegistry; import io.grpc.Status; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import javax.annotation.Nullable; @VisibleForTesting public final class AutoConfiguredLoadBalancerFactory extends LoadBalancer.Factory { private static final Logger logger = Logger.getLogger(AutoConfiguredLoadBalancerFactory.class.getName()); private final LoadBalancerRegistry registry; private final String defaultPolicy; public AutoConfiguredLoadBalancerFactory(String defaultPolicy) { this(LoadBalancerRegistry.getDefaultRegistry(), defaultPolicy); } @VisibleForTesting AutoConfiguredLoadBalancerFactory(LoadBalancerRegistry registry, String defaultPolicy) { this.registry = checkNotNull(registry, "registry"); this.defaultPolicy = checkNotNull(defaultPolicy, "defaultPolicy"); } @Override public LoadBalancer newLoadBalancer(Helper helper) { return new AutoConfiguredLoadBalancer(helper); } private static final class NoopLoadBalancer extends LoadBalancer { @Override public void handleResolvedAddressGroups(List<EquivalentAddressGroup> s, Attributes a) {} @Override public void handleNameResolutionError(Status error) {} @Override public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {} @Override public void shutdown() {} } @VisibleForTesting public final class AutoConfiguredLoadBalancer extends LoadBalancer { private final Helper helper; private LoadBalancer delegate; private LoadBalancerProvider delegateProvider; private boolean roundRobinDueToGrpclbDepMissing; AutoConfiguredLoadBalancer(Helper helper) { this.helper = helper; delegateProvider = registry.getProvider(defaultPolicy); if (delegateProvider == null) { throw new IllegalStateException("Could not find policy '" + defaultPolicy + "'. Make sure its implementation is either registered to LoadBalancerRegistry or" + " included in META-INF/services/io.grpc.LoadBalancerProvider from your jar files."); } delegate = delegateProvider.newLoadBalancer(helper); } // Must be run inside ChannelExecutor. @Override public void handleResolvedAddressGroups( List<EquivalentAddressGroup> servers, Attributes attributes) { if (attributes.get(ATTR_LOAD_BALANCING_CONFIG) != null) { throw new IllegalArgumentException( "Unexpected ATTR_LOAD_BALANCING_CONFIG from upstream: " + attributes.get(ATTR_LOAD_BALANCING_CONFIG)); } Map<String, Object> configMap = attributes.get(GrpcAttributes.NAME_RESOLVER_SERVICE_CONFIG); PolicySelection selection; try { selection = decideLoadBalancerProvider(servers, configMap); } catch (PolicyException e) { Status s = Status.INTERNAL.withDescription(e.getMessage()); helper.updateBalancingState(ConnectivityState.TRANSIENT_FAILURE, new FailingPicker(s)); delegate.shutdown(); delegateProvider = null; delegate = new NoopLoadBalancer(); return; } if (delegateProvider == null || !selection.provider.getPolicyName().equals(delegateProvider.getPolicyName())) { helper.updateBalancingState(ConnectivityState.CONNECTING, new EmptyPicker()); delegate.shutdown(); delegateProvider = selection.provider; LoadBalancer old = delegate; delegate = delegateProvider.newLoadBalancer(helper); helper.getChannelLogger().log( ChannelLogLevel.INFO, "Load balancer changed from {0} to {1}", old.getClass().getSimpleName(), delegate.getClass().getSimpleName()); } if (selection.config != null) { helper.getChannelLogger().log( ChannelLogLevel.DEBUG, "Load-balancing config: {0}", selection.config); attributes = attributes.toBuilder().set(ATTR_LOAD_BALANCING_CONFIG, selection.config).build(); } LoadBalancer delegate = getDelegate(); if (selection.serverList.isEmpty() && !delegate.canHandleEmptyAddressListFromNameResolution()) { delegate.handleNameResolutionError( Status.UNAVAILABLE.withDescription( "Name resolver returned no usable address. addrs=" + servers + ", attrs=" + attributes)); } else { delegate.handleResolvedAddressGroups(selection.serverList, attributes); } } @Override public void handleNameResolutionError(Status error) { getDelegate().handleNameResolutionError(error); } @Override public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) { getDelegate().handleSubchannelState(subchannel, stateInfo); } @Override public boolean canHandleEmptyAddressListFromNameResolution() { return true; } @Override public void shutdown() { delegate.shutdown(); delegate = null; } @VisibleForTesting public LoadBalancer getDelegate() { return delegate; } @VisibleForTesting void setDelegate(LoadBalancer lb) { delegate = lb; } @VisibleForTesting LoadBalancerProvider getDelegateProvider() { return delegateProvider; } /** * Picks a load balancer based on given criteria. In order of preference: * * <ol> * <li>User provided lb on the channel. This is a degenerate case and not handled here.</li> * <li>"grpclb" if any gRPC LB balancer addresses are present</li> * <li>The policy picked by the service config</li> * <li>"pick_first" if the service config choice does not specify</li> * </ol> * * @param servers The list of servers reported * @param config the service config object * @return the new load balancer factory, never null */ @VisibleForTesting PolicySelection decideLoadBalancerProvider( List<EquivalentAddressGroup> servers, @Nullable Map<String, Object> config) throws PolicyException { // Check for balancer addresses boolean haveBalancerAddress = false; List<EquivalentAddressGroup> backendAddrs = new ArrayList<>(); for (EquivalentAddressGroup s : servers) { if (s.getAttributes().get(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY) != null) { haveBalancerAddress = true; } else { backendAddrs.add(s); } } if (haveBalancerAddress) { LoadBalancerProvider grpclbProvider = registry.getProvider("grpclb"); if (grpclbProvider == null) { if (backendAddrs.isEmpty()) { throw new PolicyException( "Received ONLY balancer addresses but grpclb runtime is missing"); } if (!roundRobinDueToGrpclbDepMissing) { roundRobinDueToGrpclbDepMissing = true; String errorMsg = "Found balancer addresses but grpclb runtime is missing." + " Will use round_robin. Please include grpc-grpclb in your runtime depedencies."; helper.getChannelLogger().log(ChannelLogLevel.ERROR, errorMsg); logger.warning(errorMsg); } return new PolicySelection( getProviderOrThrow( "round_robin", "received balancer addresses but grpclb runtime is missing"), backendAddrs, null); } else { return new PolicySelection(grpclbProvider, servers, null); } } roundRobinDueToGrpclbDepMissing = false; List<Map<String, Object>> lbConfigs = null; if (config != null) { lbConfigs = ServiceConfigUtil.getLoadBalancingConfigsFromServiceConfig(config); } if (lbConfigs != null && !lbConfigs.isEmpty()) { LinkedHashSet<String> policiesTried = new LinkedHashSet<>(); for (Map<String, Object> lbConfig : lbConfigs) { if (lbConfig.size() != 1) { throw new PolicyException( "There are " + lbConfig.size() + " load-balancing configs in a list item. Exactly one is expected. Config=" + lbConfig); } Entry<String, Object> entry = lbConfig.entrySet().iterator().next(); String policy = entry.getKey(); LoadBalancerProvider provider = registry.getProvider(policy); if (provider != null) { if (!policiesTried.isEmpty()) { helper.getChannelLogger().log( ChannelLogLevel.DEBUG, "{0} specified by Service Config are not available", policiesTried); } return new PolicySelection(provider, servers, (Map) entry.getValue()); } policiesTried.add(policy); } throw new PolicyException( "None of " + policiesTried + " specified by Service Config are available."); } return new PolicySelection( getProviderOrThrow(defaultPolicy, "using default policy"), servers, null); } } private LoadBalancerProvider getProviderOrThrow(String policy, String choiceReason) throws PolicyException { LoadBalancerProvider provider = registry.getProvider(policy); if (provider == null) { throw new PolicyException( "Trying to load '" + policy + "' because " + choiceReason + ", but it's unavailable"); } return provider; } @VisibleForTesting static class PolicyException extends Exception { private static final long serialVersionUID = 1L; private PolicyException(String msg) { super(msg); } } @VisibleForTesting static final class PolicySelection { final LoadBalancerProvider provider; final List<EquivalentAddressGroup> serverList; @Nullable final Map<String, Object> config; @SuppressWarnings("unchecked") PolicySelection( LoadBalancerProvider provider, List<EquivalentAddressGroup> serverList, @Nullable Map<?, ?> config) { this.provider = checkNotNull(provider, "provider"); this.serverList = Collections.unmodifiableList(checkNotNull(serverList, "serverList")); this.config = (Map<String, Object>) config; } } private static final class EmptyPicker extends SubchannelPicker { @Override public PickResult pickSubchannel(PickSubchannelArgs args) { return PickResult.withNoResult(); } } private static final class FailingPicker extends SubchannelPicker { private final Status failure; FailingPicker(Status failure) { this.failure = failure; } @Override public PickResult pickSubchannel(PickSubchannelArgs args) { return PickResult.withError(failure); } } }
36.210843
99
0.687822
ca367118fab02c7d5c1546bb0bb424340090b38c
105
/** View groups that do not pass their states to children. */ package com.stanfy.enroscar.views.nostate;
35
61
0.761905
88a5941e6cf2732bb28de94e5a135767c246bd08
973
package com.ruoyi.project.device.devUserCompany.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.framework.web.domain.BaseEntity; /** * 用户公司表 dev_user_company * * @author ruoyi * @date 2019-02-02 */ public class DevUserCompany extends BaseEntity { private static final long serialVersionUID = 1L; /** 公司主键ID */ private Integer companyId; /** 用户主键ID */ private Integer userId; public void setCompanyId(Integer companyId) { this.companyId = companyId; } public Integer getCompanyId() { return companyId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getUserId() { return userId; } public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("companyId", getCompanyId()) .append("userId", getUserId()) .toString(); } }
20.270833
71
0.700925
6a4effca0079447a81849fa35fc22d2f9219bbad
5,489
// Generated by data binding compiler. Do not edit! package com.example.lunchtray.databinding; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.Bindable; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import com.example.lunchtray.R; import com.example.lunchtray.model.OrderViewModel; import java.lang.Deprecated; import java.lang.Object; public abstract class FragmentEntreeMenuBinding extends ViewDataBinding { @NonNull public final Button cancelButton; @NonNull public final RadioButton cauliflower; @NonNull public final TextView cauliflowerDescription; @NonNull public final TextView cauliflowerPrice; @NonNull public final RadioButton chili; @NonNull public final TextView chiliDescription; @NonNull public final TextView chiliPrice; @NonNull public final View divider; @NonNull public final RadioGroup entreeOptions; @NonNull public final Button nextButton; @NonNull public final RadioButton pasta; @NonNull public final TextView pastaDescription; @NonNull public final TextView pastaPrice; @NonNull public final RadioButton skillet; @NonNull public final TextView skilletDescription; @NonNull public final TextView skilletPrice; @NonNull public final TextView subtotal; @Bindable protected OrderViewModel mViewModel; protected FragmentEntreeMenuBinding(Object _bindingComponent, View _root, int _localFieldCount, Button cancelButton, RadioButton cauliflower, TextView cauliflowerDescription, TextView cauliflowerPrice, RadioButton chili, TextView chiliDescription, TextView chiliPrice, View divider, RadioGroup entreeOptions, Button nextButton, RadioButton pasta, TextView pastaDescription, TextView pastaPrice, RadioButton skillet, TextView skilletDescription, TextView skilletPrice, TextView subtotal) { super(_bindingComponent, _root, _localFieldCount); this.cancelButton = cancelButton; this.cauliflower = cauliflower; this.cauliflowerDescription = cauliflowerDescription; this.cauliflowerPrice = cauliflowerPrice; this.chili = chili; this.chiliDescription = chiliDescription; this.chiliPrice = chiliPrice; this.divider = divider; this.entreeOptions = entreeOptions; this.nextButton = nextButton; this.pasta = pasta; this.pastaDescription = pastaDescription; this.pastaPrice = pastaPrice; this.skillet = skillet; this.skilletDescription = skilletDescription; this.skilletPrice = skilletPrice; this.subtotal = subtotal; } public abstract void setViewModel(@Nullable OrderViewModel viewModel); @Nullable public OrderViewModel getViewModel() { return mViewModel; } @NonNull public static FragmentEntreeMenuBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup root, boolean attachToRoot) { return inflate(inflater, root, attachToRoot, DataBindingUtil.getDefaultComponent()); } /** * This method receives DataBindingComponent instance as type Object instead of * type DataBindingComponent to avoid causing too many compilation errors if * compilation fails for another reason. * https://issuetracker.google.com/issues/116541301 * @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.fragment_entree_menu, root, attachToRoot, component) */ @NonNull @Deprecated public static FragmentEntreeMenuBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup root, boolean attachToRoot, @Nullable Object component) { return ViewDataBinding.<FragmentEntreeMenuBinding>inflateInternal(inflater, R.layout.fragment_entree_menu, root, attachToRoot, component); } @NonNull public static FragmentEntreeMenuBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, DataBindingUtil.getDefaultComponent()); } /** * This method receives DataBindingComponent instance as type Object instead of * type DataBindingComponent to avoid causing too many compilation errors if * compilation fails for another reason. * https://issuetracker.google.com/issues/116541301 * @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.fragment_entree_menu, null, false, component) */ @NonNull @Deprecated public static FragmentEntreeMenuBinding inflate(@NonNull LayoutInflater inflater, @Nullable Object component) { return ViewDataBinding.<FragmentEntreeMenuBinding>inflateInternal(inflater, R.layout.fragment_entree_menu, null, false, component); } public static FragmentEntreeMenuBinding bind(@NonNull View view) { return bind(view, DataBindingUtil.getDefaultComponent()); } /** * This method receives DataBindingComponent instance as type Object instead of * type DataBindingComponent to avoid causing too many compilation errors if * compilation fails for another reason. * https://issuetracker.google.com/issues/116541301 * @Deprecated Use DataBindingUtil.bind(view, component) */ @Deprecated public static FragmentEntreeMenuBinding bind(@NonNull View view, @Nullable Object component) { return (FragmentEntreeMenuBinding)bind(component, view, R.layout.fragment_entree_menu); } }
33.469512
142
0.781927
422e33d6a600c0b113985acd4d2ebb5c1086c6a5
6,285
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.iso.dashboard.utils; import com.iso.dashboard.dto.CProcedure; import com.iso.dashboard.ui.ProcedureSearchUI; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.data.util.IndexedContainer; import com.vaadin.server.Resource; import com.vaadin.server.Sizeable; import com.vaadin.ui.Button; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.Table; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.themes.ValoTheme; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; /** * * * Khai bao: Uploader uploader = new Uploader(); * * Doc cac url: uploader.getUrl(); * */ public class DataWrapper extends CustomComponent { Logger log = Logger.getLogger(DataWrapper.class); final VerticalLayout layout = new VerticalLayout(); Button button = new Button(); Table table = new Table(); BeanItemContainer<String> containerLink; List<CProcedure> cProcedures = new ArrayList<>(); VerticalLayout vLayoutAttach; public DataWrapper(String caption) { cProcedures.clear(); initGUI(); } public DataWrapper(Date date) { addUpload(); } private void initGUI() { button.setCaption(BundleUtils.getString("flowProcedure.chooseProc")); button.setDescription(BundleUtils.getString("flowProcedure.chooseProc")); button.setImmediate(true); button.setWidth(Constants.STYLE_CONF.AUTO_VALUE); button.setHeight(Constants.STYLE_CONF.AUTO_VALUE); button.addClickListener((Button.ClickEvent event) -> { addUpload(); }); table.setImmediate(true); table.setWidth("100%"); table.setHeight("100%"); table.setVisible(false); table.setColumnHeaderMode(Table.ColumnHeaderMode.HIDDEN); table.addContainerProperty("button", String.class, null); table.addContainerProperty("File", String.class, null); table.setColumnWidth("button", 50); table.addGeneratedColumn("button", new Table.ColumnGenerator() { @Override public Object generateCell(Table source, final Object itemId, Object columnId) { Resource iconVi = ISOIcons.DELETE; Button btnDelete = new Button(); // btnDelete.setStyleName(Constants.STYLE_CONF.BUTTON_LINK_LARGE); btnDelete.setStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED); btnDelete.setDescription(BundleUtils.getString("common.button.delete")); btnDelete.setIcon(iconVi); btnDelete.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { CProcedure cProcedure = (CProcedure) itemId; table.removeItem(itemId); cProcedures.remove(cProcedure); } }); return btnDelete; } }); layout.addComponent(button); // vLayoutAttach = new VerticalLayout(); // vLayoutAttach.setImmediate(true); // vLayoutAttach.setWidth("100%"); // vLayoutAttach.setHeight("60px"); // vLayoutAttach.setMargin(false); // vLayoutAttach.setSpacing(false); // vLayoutAttach.setStyleName("verticalLayOut-Scroll"); // vLayoutAttach.addComponent(table); Panel panel = new Panel(); panel.addStyleName(ValoTheme.PANEL_SCROLL_INDICATOR); panel.setHeight("100px"); panel.setContent(table); layout.addComponent(panel); setCompositionRoot(layout); } private void addUpload() { ProcedureSearchUI ui = new ProcedureSearchUI(""); Window window = new Window("", ui); float height = UI.getCurrent().getWidth() * 7f / 10; window.setWidth(String.valueOf(height) + "%"); window.setHeight(50.0f, Sizeable.Unit.PERCENTAGE); ui.setWidth("100%"); ui.setHeight(Constants.STYLE_CONF.AUTO_VALUE); ui.getBtnSelect().addClickListener((Button.ClickEvent event) -> { List<CProcedure> list = ui.getTreeTaskSelected(); if (list != null) { list.stream().filter((emp) -> (!cProcedures.contains(emp))).forEach((emp) -> { addProcedure(emp); }); } window.close(); }); window.setModal(true); DataUtil.reloadWindow(window); UI.getCurrent().addWindow(window); } public void addProcedure(CProcedure cProcedure) { try { if (!cProcedures.contains(cProcedure)) { cProcedures.add(cProcedure); // Add a row the hard way table.setVisible(true); Item row1 = table.addItem(cProcedure); row1.getItemProperty("File").setValue(cProcedure.getName()); table.setPageLength(table.getItemIds().size()); } } catch (Exception e) { e.printStackTrace(); } } public Table getTable() { return table; } public void setTable(Table table) { this.table = table; } public void setRequired(boolean require) { if (require) { setCaptionAsHtml(true); setCaption(getCaption() + Constants.FILE_CONF.REQUIRE); } } public void setEnableToEdit(Boolean enabled) { button.setEnabled(enabled); if (!enabled) { table.setColumnCollapsingAllowed(true); table.setColumnCollapsed("button", true); table.addStyleName("hidecollapse"); } else { table.setColumnCollapsingAllowed(false); table.removeStyleName("hidecollapse"); } } public List<CProcedure> getcProcedures() { return cProcedures; } public void setcProcedures(List<CProcedure> cProcedures) { this.cProcedures = cProcedures; } }
33.609626
94
0.620048
5fe4694a4730fae4f7ac5de91ef2867062f5a34e
999
/** * Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package io.k8s.client.models; import com.fasterxml.jackson.annotation.JsonProperty; /** * LocalObjectReference contains enough information to let you locate the * referenced object inside the same namespace. */ public class V1LocalObjectReference { /** * Name of the referent. More info: * http://kubernetes.io/docs/user-guide/identifiers#names. */ @JsonProperty(value = "name") private String name; /** * Get the name value. * * @return the name value */ public String name() { return this.name; } /** * Set the name value. * * @param name the name value to set * @return the V1LocalObjectReference object itself. */ public V1LocalObjectReference withName(String name) { this.name = name; return this; } }
22.704545
73
0.644645
1e8491d376275c46d9968e6c47eaeec62244dafb
4,830
/** * Copyright (C) 2016-2019 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hotels.bdp.waggledance.api.model; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import org.junit.Test; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class PrimaryMetaStoreTest extends AbstractMetaStoreTest<PrimaryMetaStore> { private final String name = "name"; private final String remoteMetaStoreUris = "remoteMetaStoreUris"; private final List<String> whitelist = new ArrayList<>(); private final AccessControlType accessControlType = AccessControlType.READ_AND_WRITE_ON_DATABASE_WHITELIST; public PrimaryMetaStoreTest() { super(new PrimaryMetaStore()); } @Test public void testAccessControlTypeDefaultReadOnly() { assertThat(metaStore.getAccessControlType(), is(AccessControlType.READ_ONLY)); // override metaStore.setAccessControlType(AccessControlType.READ_AND_WRITE_ON_DATABASE_WHITELIST); assertThat(metaStore.getAccessControlType(), is(AccessControlType.READ_AND_WRITE_ON_DATABASE_WHITELIST)); } @Test public void testFederationType() { assertThat(metaStore.getFederationType(), is(FederationType.PRIMARY)); } @Test public void testDefaultDatabaseWhiteListIsEmpty() { assertThat(metaStore.getWritableDatabaseWhiteList(), is(notNullValue())); assertThat(metaStore.getWritableDatabaseWhiteList().size(), is(0)); } @Test public void emptyDatabasePrefix() { metaStore.setDatabasePrefix(""); Set<ConstraintViolation<PrimaryMetaStore>> violations = validator.validate(metaStore); assertThat(violations.size(), is(0)); assertThat(metaStore.getDatabasePrefix(), is("")); } @Test public void nullDatabasePrefix() { metaStore.setDatabasePrefix(null); Set<ConstraintViolation<PrimaryMetaStore>> violations = validator.validate(metaStore); // Violation is not triggered cause EMPTY STRING is always returned. Warning is logged instead assertThat(violations.size(), is(0)); assertThat(metaStore.getDatabasePrefix(), is("")); } @Test public void nonEmptyDatabasePrefix() { String prefix = "abc"; metaStore.setDatabasePrefix(prefix); Set<ConstraintViolation<PrimaryMetaStore>> violations = validator.validate(metaStore); assertThat(violations.size(), is(0)); assertThat(metaStore.getDatabasePrefix(), is(prefix)); } @Test public void toJson() throws Exception { String expected = "{\"accessControlType\":\"READ_ONLY\",\"connectionType\":\"DIRECT\",\"databasePrefix\":\"\",\"federationType\":\"PRIMARY\",\"latency\":0,\"mappedDatabases\":null,\"metastoreTunnel\":null,\"name\":\"name\",\"remoteMetaStoreUris\":\"uri\",\"status\":\"UNKNOWN\",\"writableDatabaseWhiteList\":[]}"; ObjectMapper mapper = new ObjectMapper(); // Sorting to get deterministic test behaviour mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); String json = mapper.writerFor(PrimaryMetaStore.class).writeValueAsString(metaStore); assertThat(json, is(expected)); } @Test public void nonEmptyConstructor() { whitelist.add("databaseOne"); whitelist.add("databaseTwo"); PrimaryMetaStore store = new PrimaryMetaStore(name, remoteMetaStoreUris, accessControlType, whitelist.get(0), whitelist.get(1)); assertThat(store.getName(), is(name)); assertThat(store.getRemoteMetaStoreUris(), is(remoteMetaStoreUris)); assertThat(store.getAccessControlType(), is(accessControlType)); assertThat(store.getWritableDatabaseWhiteList(), is(whitelist)); } @Test public void constructorWithArrayListForWhitelist() { whitelist.add("databaseOne"); whitelist.add("databaseTwo"); PrimaryMetaStore store = new PrimaryMetaStore(name, remoteMetaStoreUris, accessControlType, whitelist); assertThat(store.getName(), is(name)); assertThat(store.getRemoteMetaStoreUris(), is(remoteMetaStoreUris)); assertThat(store.getAccessControlType(), is(accessControlType)); assertThat(store.getWritableDatabaseWhiteList(), is(whitelist)); } }
38.951613
317
0.75383
0dfe763faca6522b553ae44cb4dd8313cf6a6489
2,821
/** * Promise.java * * @author Sidharth Mishra <[email protected]> * @description * @created Feb 15, 2018 12:28:48 AM * @last-modified Feb 15, 2018 12:28:48 AM * @copyright 2018 Sidharth Mishra */ package io.sidmishraw.job_pooler; import java.util.Objects; import java.util.Observable; import java.util.Observer; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import lombok.Getter; /** * @author sidmishraw * * Qualified Name: io.sidmishraw.job_pooler.Promise * */ public class Promise<R> implements Observer { public static enum PromiseState { PENDING, FULFILLED, REJECTED; } private @Getter PromiseState state; private Function<R, ?> thenable; private Consumer<Exception> failable; /** * */ private @Getter UUID id; private @Getter R result; /** * */ private Job<R> theJob; /** * @param theJob */ public Promise(Job<R> theJob) { this.state = PromiseState.PENDING; this.id = UUID.randomUUID(); this.theJob = theJob; this.theJob.addObserver(this); } /* * (non-Javadoc) * * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ @SuppressWarnings("unchecked") @Override public void update(Observable job, Object arg) { if (Objects.isNull(arg)) rejected(new Exception("The Job has has failed")); else fulfilled((R) arg); } /** * */ @SuppressWarnings("unchecked") private void fulfilled(R result) { if (this.state != PromiseState.PENDING) return; this.state = PromiseState.FULFILLED; this.result = result; if (Objects.isNull(this.result)) return; this.result = (R) this.thenable.apply(this.result); } /** * */ private void rejected(Exception e) { if (this.state != PromiseState.PENDING) return; this.state = PromiseState.REJECTED; this.result = null; this.failable.accept(e); } /** * @param transformer * @return * @throws Exception */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Promise<R> then(Function transformer) { if (Objects.isNull(this.thenable)) this.thenable = transformer; else this.thenable.andThen(transformer); return this; } /** * @param failable * @return */ public Promise<R> error(Consumer<Exception> failable) { this.failable = failable; return this; } }
21.210526
77
0.559731
53af3bc42403e5297ea1f3a6dfb61db9fccda799
2,753
package de.tub.dima.condor.benchmark.efficiency.oneOffImplementation.utils; import de.tub.dima.condor.core.synopsis.NonMergeableSynopsisManager; import de.tub.dima.condor.core.synopsis.Wavelets.WaveletSynopsis; import java.util.ArrayList; public class SliceCointMinSketchManager<Input> extends NonMergeableSynopsisManager<Input, CountMinSketchOrderBased<Input>> { int slicesPerWindow; ArrayList<Integer> sliceStartIndices; public SliceCointMinSketchManager(ArrayList<CountMinSketchOrderBased<Input>> unifiedSynopses) { this.unifiedSynopses = unifiedSynopses; this.slicesPerWindow = unifiedSynopses.size(); sliceStartIndices = new ArrayList<>(slicesPerWindow); elementsProcessed = 0; for (int i = 0; i < slicesPerWindow; i++) { sliceStartIndices.add(i, elementsProcessed); } } public SliceCointMinSketchManager() { super(); sliceStartIndices = new ArrayList<>(); } @Override public void update(Object element) { if (!unifiedSynopses.isEmpty()) { unifiedSynopses.get(unifiedSynopses.size() - 1).update((Input) element); } } @Override public int getSynopsisIndex(int streamIndex) { int index = -1; for (int i = 0; i < sliceStartIndices.size(); i++) { if (sliceStartIndices.get(i) > streamIndex) { return index; } index++; } return index; } @Override public void addSynopsis(CountMinSketchOrderBased<Input> synopsis) { if (sliceStartIndices == null){ sliceStartIndices = new ArrayList<>(); } slicesPerWindow++; elementsProcessed += synopsis.getElementsProcessed(); if (unifiedSynopses.isEmpty()) { sliceStartIndices.add(0); } else { sliceStartIndices.add(sliceStartIndices.get(sliceStartIndices.size() - 1) + unifiedSynopses.get(unifiedSynopses.size() - 1).getElementsProcessed()); } super.addSynopsis(synopsis); } @Override public void unify(NonMergeableSynopsisManager other) { // if (other instanceof SliceWaveletsManager){ SliceCointMinSketchManager o = (SliceCointMinSketchManager) other; for (int i = 0; i < o.getUnifiedSynopses().size(); i++) { this.addSynopsis((CountMinSketchOrderBased<Input>) o.getUnifiedSynopses().get(i)); } // } // Environment.out.println(other.getClass()); // throw new IllegalArgumentException("It is only possible to unify two objects of type NonMergeableSynopsisManager with each other."); } }
35.753247
161
0.633854
186da381cb4d04a69b1b163bfa9c33d1e06e09bb
4,900
package com.mrkirby153.snowsgivingbot.commands; import com.mrkirby153.botcore.command.Command; import com.mrkirby153.botcore.command.Context; import com.mrkirby153.botcore.command.args.CommandContext; import com.mrkirby153.snowsgivingbot.services.setting.SettingService; import com.mrkirby153.snowsgivingbot.services.setting.Settings; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.awt.Color; @Component public class HelpCommand { public static final String DEFAULT_PERMISSIONS = "379968"; public static final String DISCORD_OAUTH_INVITE = "https://discord.com/api/oauth2/authorize?client_id=%s&permissions=%s&scope=bot%%20applications.commands"; private final SettingService settingService; private final String dashUrlFormat; private final String permissions; private final String supportInvite; public HelpCommand(@Value("${bot.dash-url-format}") String dashUrlFormat, @Value("${bot.permissions:" + DEFAULT_PERMISSIONS + "}") String permissions, @Value("${bot.support-server:}") String supportInvite, SettingService settingService) { this.dashUrlFormat = dashUrlFormat; this.permissions = permissions; this.supportInvite = supportInvite; this.settingService = settingService; } @Command(name = "help", clearance = 100, permissions = {Permission.MESSAGE_EMBED_LINKS}) public void help(Context context, CommandContext commandContext) { EmbedBuilder builder = new EmbedBuilder(); builder.setTitle(String.format("%s Help", context.getJDA().getSelfUser().getName())); StringBuilder desc = new StringBuilder(); String prefix = settingService.get(Settings.COMMAND_PREFIX, context.getGuild()); desc.append("**Commands**\n"); desc.append(prefix).append( "start <duration> [winners] <prize> - Starts a giveaway in the current channel. (Example: `") .append(prefix).append("start 30m 2w Cool steam key").append("`)\n"); desc.append(prefix).append("end <message id> - Ends the giveaway with the message id\n"); desc.append(prefix) .append("winners <message id> - Displays the winners of the provided giveaway\n"); desc.append(prefix) .append( "winners set <message id> <winner count> - Sets the amount of winners for a giveaway\n"); desc.append(prefix) .append("reroll <message id> - Picks new winners for the provided giveaway\n"); desc.append(prefix) .append("export - Exports a CSV of all the giveaways ran in this server\n"); desc.append("\n"); desc.append( "**Giveaway Hosts**\nUsers with **Manage Server** or a giveaway host role can start giveaways.\n\n"); desc.append(prefix) .append("role add <role id> - Adds the provided role as a giveaway host\n"); desc.append(prefix) .append("role remove <role id> - Removes the provided role as a giveaway host\n"); desc.append(prefix).append("role list - Lists roles configured as a giveaway host\n"); desc.append(prefix).append("help - Displays this help message\n"); desc.append(prefix).append("invite - Gets an invite for the bot\n"); desc.append("\n"); desc.append("`[ ]` indicates optional arguments, `< >` indicates required arguments\n\n"); desc.append("Click [here](") .append(String.format(dashUrlFormat, context.getGuild().getId())) .append(") to view the giveaway dashboard.\n"); if (!this.supportInvite.isBlank()) { desc.append("Join the [support server](").append(this.supportInvite) .append(") for additional help\n"); } builder.setDescription(desc); builder.setColor(Color.BLUE); context.getChannel().sendMessage(builder.build()).queue(); } @Command(name = "invite", permissions = {Permission.MESSAGE_EMBED_LINKS}) public void invite(Context context, CommandContext commandContext) { String prefix = settingService.get(Settings.COMMAND_PREFIX, context.getGuild()); EmbedBuilder builder = new EmbedBuilder(); builder.setTitle(String.format("%s Invite", context.getJDA().getSelfUser().getName())); builder.setDescription("You can invite me to your server by clicking [here](" + String .format(DISCORD_OAUTH_INVITE, context.getJDA().getSelfUser().getId(), permissions) + "). \n\nBy default only users with **Manage Server** can start giveaways, but this can be changed. See **" + prefix + "help** for more information"); builder.setColor(Color.BLUE); context.getChannel().sendMessage(builder.build()).queue(); } }
52.688172
160
0.677959
5da86acfbf628247242ba4aae3320309b7e35fbc
1,682
package com.metaopsis.icsapi.v3.dom; public class Query { private StringBuilder query; private boolean _IsFirstParam = true; public Query() { query = new StringBuilder(); query.append("?q="); } public void andType(Asset type, boolean isEqual) { if (!isFirstParam()) query.append(" and "); query.append("type" + (isEqual ? "==" : "!=") + "'" + type.toString() + "'"); } public void andLocation(String location) { if (!isFirstParam()) query.append(" and "); query.append("location=='" + location + "'"); } public void andUpdateTime(String tstamp, Operator operator) { if (!this.isFirstParam()) query.append(" and "); query.append("updateTime" + operator.toString() + tstamp); } public void andUpdatedBy(String user, boolean isEqual) { if (!isFirstParam()) query.append(" and "); query.append("updatedBy" + (isEqual ? "==" : "!=") + "'" + user + "'"); } public void andTag(String tag) { if (!isFirstParam()) query.append(" and "); query.append("tag=='" + tag + "'"); } public void limit(int limit) { query.append("&limit=" + limit); } public void skip(int skip) { query.append("&skip=" + skip); } private boolean isFirstParam() { boolean currentState = this._IsFirstParam; if (this._IsFirstParam) this._IsFirstParam = false; return currentState; } @Override public String toString() { return this.query.toString(); } }
21.291139
85
0.532105
dbd1226420db46c302fbe1deda58e71e16e6c51f
77
package com.estontorise.simplersa.interfaces; public interface RSAKey { }
11
45
0.792208
f56aeb4032b0f236c5ad3a713a69342674ac05f4
2,143
/* * 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 com.acidmanic.pactdoc.dcoumentstructure.renderers.pagecontexts.pdfcontext; import com.itextpdf.text.Font; /** * * @author diego */ public class Palette { private Font font; private int fontStyle; private int deltaItalic; private int deltaBold; public Palette(Font font) { this.font = font; this.fontStyle = font.getStyle(); deltaItalic = 0; } public Palette() { } public Font getFont() { return font; } public void setFont(Font font) { this.font = font; this.fontStyle = font.getStyle(); } public void setBold() { if (!font.isBold()) { int style = font.getStyle(); style += Font.BOLD; font.setStyle(style); deltaBold = Font.BOLD; } } public void setItalic() { if (!font.isItalic()) { int style = font.getStyle(); style += Font.ITALIC; font.setStyle(style); deltaItalic += Font.ITALIC; } } public void resetBold() { if (this.deltaBold > 0) { int style = font.getStyle(); style -= this.deltaBold; font.setStyle(style); this.deltaBold = 0; } } public void resetItalic() { if (this.deltaItalic > 0) { int style = font.getStyle(); style -= this.deltaItalic; font.setStyle(style); this.deltaItalic = 0; } } public void resetFont() { font.setSize(fontStyle); this.deltaBold = 0; this.deltaItalic = 0; } @Override @SuppressWarnings({"CloneDeclaresCloneNotSupported", "CloneDoesntCallSuperClone"}) public Palette clone(){ Palette clone = new Palette(font); clone.font.setStyle(fontStyle); return new Palette(font); } }
18.316239
86
0.544564
ffad965678908e7448831230a1cb9d2591ec7ad8
21,347
package org.protege.editor.owl.ui.preferences; import org.protege.editor.owl.model.entity.*; import org.protege.editor.owl.ui.UIHelper; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import org.semanticweb.owlapi.vocab.OWLRDFVocabulary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.net.URISyntaxException; /** * Author: drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jul 24, 2008<br><br> * * see http://protegewiki.stanford.edu/index.php/Protege4NamingAndRendering */ public class NewEntitiesPreferencesPanel extends OWLPreferencesPanel implements ActionListener { private static final long serialVersionUID = -319986509127880607L; private static final String SEP_COLON = ":"; private static final String SEP_HASH = "#"; private static final String SEP_SLASH = "/"; private final Logger logger = LoggerFactory.getLogger(NewEntitiesPreferencesPanel.class); // Entity IRI panel private JRadioButton autoIDIriFragment; private JRadioButton colonButton; private JRadioButton hashButton; private JRadioButton nameAsIriFragment; private JRadioButton slashButton; private JRadioButton iriBaseActiveOntology; private JRadioButton iriBaseSpecifiedIri; private JTextField iriDefaultBaseField; // Entity Label panel private IRI labelAnnotation = null; private JButton annotationSelectButton; private JComboBox annotationLangSelector; private JLabel langLabel; private JLabel iriLabel; private JRadioButton customLabelButton; private JRadioButton sameAsRendererLabelButton; private JTextField annotationIriLabel; // Auto-generated ID panel private JCheckBox saveIterativeIds; private JLabel digitCountLabel; private JLabel endLabel; private JLabel prefixLabel; private JLabel startLabel; private JLabel suffixLabel; private JPanel autoGeneratedIDPanel; private JRadioButton iterativeButton; private JRadioButton uniqueIdButton; private JSpinner autoIDEnd; private JSpinner autoIDStart; private JSpinner autoIDDigitCount; private JTextField autoIDPrefix; private JTextField autoIDSuffix; private JRadioButton ideIdButton; public void initialise() throws Exception { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(createEntityIriPanel()); add(Box.createVerticalStrut(7)); add(createEntityLabelPanel()); add(Box.createVerticalStrut(7)); add(createAutoGeneratedIDPanel()); } private JPanel createEntityIriPanel() { JPanel panel = new JPanel(); panel.setBorder(new TitledBorder("Entity IRI")); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); // "Start with:" section c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.fill = GridBagConstraints.NONE; c.insets = new Insets(12,12,0,12); c.anchor = GridBagConstraints.FIRST_LINE_START; panel.add(new JLabel("Start with:"), c); c.gridx = 1; c.gridy = 0; c.gridwidth = 2; c.insets = new Insets(12,0,0,0); iriBaseActiveOntology = new JRadioButton("Active ontology IRI"); iriBaseActiveOntology.setSelected(!EntityCreationPreferences.useDefaultBaseIRI()); panel.add(iriBaseActiveOntology, c); c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.insets = new Insets(0,0,0,5); iriBaseSpecifiedIri = new JRadioButton("Specified IRI:"); iriBaseSpecifiedIri.setSelected(EntityCreationPreferences.useDefaultBaseIRI()); panel.add(iriBaseSpecifiedIri, c); c.gridx = 2; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.insets = new Insets(0,0,0,12); iriDefaultBaseField = new JTextField(); iriDefaultBaseField.setText(EntityCreationPreferences.getDefaultBaseIRI().toString()); panel.add(iriDefaultBaseField, c); ButtonGroup group = new ButtonGroup(); group.add(iriBaseActiveOntology); group.add(iriBaseSpecifiedIri); // "Followed by:" section c.gridx = 0; c.gridy = 2; c.fill = GridBagConstraints.NONE; c.insets = new Insets(11,12,0,12); c.weightx = 0; panel.add(new JLabel("Followed by:"), c); c.gridx = 1; c.insets = new Insets(11,0,0,0); hashButton = new JRadioButton(SEP_HASH); hashButton.setSelected(EntityCreationPreferences.getDefaultSeparator().equals(SEP_HASH)); panel.add(hashButton, c); c.gridy = 3; c.insets = new Insets(0,0,0,0); slashButton = new JRadioButton(SEP_SLASH); slashButton.setSelected(EntityCreationPreferences.getDefaultSeparator().equals(SEP_SLASH)); panel.add(slashButton, c); c.gridy = 4; c.insets = new Insets(0,0,0,0); colonButton = new JRadioButton(SEP_COLON); colonButton.setSelected(EntityCreationPreferences.getDefaultSeparator().equals(SEP_COLON)); panel.add(colonButton, c); ButtonGroup group2 = new ButtonGroup(); group2.add(hashButton); group2.add(slashButton); group2.add(colonButton); // "End with:" section c.gridx = 0; c.gridy = 5; c.insets = new Insets(11,12,0,12); panel.add(new JLabel("End with:"), c); c.gridx = 1; c.insets = new Insets(11,0,0,0); c.gridwidth = 2; nameAsIriFragment = new JRadioButton("User supplied name"); nameAsIriFragment.setSelected(!EntityCreationPreferences.isFragmentAutoGenerated()); nameAsIriFragment.addActionListener(e -> { handleActionEndWithName(); }); panel.add(nameAsIriFragment, c); c.gridy = 6; c.insets = new Insets(0,0,12,0); c.weighty = 1.0; autoIDIriFragment = new JRadioButton("Auto-generated ID"); autoIDIriFragment.setSelected(EntityCreationPreferences.isFragmentAutoGenerated()); autoIDIriFragment.addActionListener(e -> { handleActionEndWithID(); }); panel.add(autoIDIriFragment, c); ButtonGroup group3 = new ButtonGroup(); group3.add(nameAsIriFragment); group3.add(autoIDIriFragment); return panel; } private JPanel createEntityLabelPanel() { final Class<? extends LabelDescriptor> labelDescrCls = EntityCreationPreferences.getLabelDescriptorClass(); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder("Entity Label (for use with Auto-generated ID)")); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.gridheight = 1; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(0,12,0,0); /*sameAsRendererLabelButton = new JRadioButton("Same as label renderer (currently " + new SimpleIRIShortFormProvider().getShortForm(getFirstRendererLabel()) + ")");*/ sameAsRendererLabelButton = new JRadioButton("Same as label renderer"); sameAsRendererLabelButton.setSelected(labelDescrCls.equals(MatchRendererLabelDescriptor.class)); panel.add(sameAsRendererLabelButton, c); c.gridy = 1; customLabelButton = new JRadioButton("Custom label"); customLabelButton.setSelected(labelDescrCls.equals(CustomLabelDescriptor.class)); panel.add(customLabelButton, c); ButtonGroup group = new ButtonGroup(); group.add(sameAsRendererLabelButton); group.add(customLabelButton); c.gridy = 2; c.gridwidth = 1; c.insets = new Insets(5,30,0,5); iriLabel = new JLabel("IRI"); panel.add(iriLabel, c); c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5,0,0,0); c.weightx = 1.0; annotationIriLabel = new JTextField(); labelAnnotation = EntityCreationPreferences.getNameLabelIRI(); if (labelAnnotation == null){ labelAnnotation = OWLRDFVocabulary.RDFS_LABEL.getIRI(); } annotationIriLabel.setText(labelAnnotation.toString()); annotationIriLabel.setEditable(false); panel.add(annotationIriLabel, c); c.gridx = 2; c.fill = GridBagConstraints.NONE; c.insets = new Insets(5,5,0,12); c.weightx = 0; annotationSelectButton = new JButton(new AbstractAction("...") { private static final long serialVersionUID = 7759812643136092837L; public void actionPerformed(ActionEvent event) { handleSelectAnnotation(); } }); panel.add(annotationSelectButton, c); c.gridx = 0; c.gridy = 3; c.insets = new Insets(5,30,12,5); langLabel = new JLabel("Lang"); panel.add(langLabel, c); c.gridx = 1; c.insets = new Insets(5,0,12,0); c.weighty = 1.0; annotationLangSelector = new UIHelper(getOWLEditorKit()).getLanguageSelector(); annotationLangSelector.setSelectedItem(EntityCreationPreferences.getNameLabelLang()); panel.add(annotationLangSelector, c); return panel; } private JPanel createAutoGeneratedIDPanel() { autoGeneratedIDPanel = new JPanel(); autoGeneratedIDPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); autoGeneratedIDPanel.setBorder(new TitledBorder("Auto-generated ID")); JPanel interiorPanel = new JPanel(new BorderLayout(32, 0)); interiorPanel.setBorder(BorderFactory.createEmptyBorder(7, 7, 0, 0)); // Left panel - radio buttons JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS)); iterativeButton = new JRadioButton("Numeric (iterative)"); uniqueIdButton = new JRadioButton("Globally unique"); ideIdButton = new JRadioButton("Identitas"); final Class<? extends AutoIDGenerator> autoIDGenCls = EntityCreationPreferences.getAutoIDGeneratorClass(); iterativeButton.setSelected(autoIDGenCls.equals(IterativeAutoIDGenerator.class)); uniqueIdButton.setSelected(autoIDGenCls.equals(UniqueIdGenerator.class)); ideIdButton.setSelected(autoIDGenCls.equals(RandomProlong.class)); ButtonGroup group = new ButtonGroup(); group.add(iterativeButton); group.add(uniqueIdButton); group.add(ideIdButton); iterativeButton.addActionListener(this); uniqueIdButton.addActionListener(this); ideIdButton.addActionListener(this); leftPanel.add(iterativeButton); leftPanel.add(uniqueIdButton); leftPanel.add(ideIdButton); leftPanel.add(Box.createVerticalGlue()); // Center panel - random group of components JPanel centerPanel = new JPanel(); centerPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); // Prefix label c.gridx = 0; c.gridy = 0; c.insets = new Insets(0,0,5,0); c.anchor = GridBagConstraints.LINE_END; prefixLabel = new JLabel("Prefix: "); centerPanel.add(prefixLabel, c); // Prefix text field c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.FIRST_LINE_START; autoIDPrefix = new JTextField(); autoIDPrefix.setText(EntityCreationPreferences.getPrefix()); autoIDPrefix.setColumns(30); centerPanel.add(autoIDPrefix, c); // Suffix label c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.LINE_END; suffixLabel = new JLabel("Suffix: "); centerPanel.add(suffixLabel, c); // Suffix text field c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.FIRST_LINE_START; autoIDSuffix = new JTextField(); autoIDSuffix.setText(EntityCreationPreferences.getSuffix()); autoIDSuffix.setColumns(30); centerPanel.add(autoIDSuffix, c); // Digit count label c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.LINE_END; digitCountLabel = new JLabel("Digit count: "); centerPanel.add(digitCountLabel, c); // Digit count spinner c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.FIRST_LINE_START; c.weightx = 0.5; autoIDDigitCount = new JSpinner(new SpinnerNumberModel(6, 0, 255, 1)); autoIDDigitCount.setValue(EntityCreationPreferences.getAutoIDDigitCount()); autoIDDigitCount.setPreferredSize(new Dimension(100, 20)); centerPanel.add(autoIDDigitCount, c); // Start label c.gridx = 0; c.gridy = 3; c.weightx = 0; c.anchor = GridBagConstraints.LINE_END; startLabel = new JLabel("Start: "); startLabel.setEnabled(iterativeButton.isSelected()); centerPanel.add(startLabel, c); // Start spinner c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.FIRST_LINE_START; autoIDStart = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); autoIDStart.setPreferredSize(new Dimension(100, 20)); autoIDStart.setValue(EntityCreationPreferences.getAutoIDStart()); autoIDStart.setEnabled(iterativeButton.isSelected()); autoIDStart.addChangeListener(event -> { if ((Integer)autoIDEnd.getValue() != -1 && (Integer)autoIDEnd.getValue() <= (Integer)autoIDStart.getValue()) { autoIDEnd.setValue(autoIDStart.getValue()); } }); centerPanel.add(autoIDStart, c); // End label c.gridx = 0; c.gridy = 4; c.anchor = GridBagConstraints.LINE_END; endLabel = new JLabel("End: "); endLabel.setEnabled(iterativeButton.isSelected()); centerPanel.add(endLabel, c); // End spinner c.gridx = 1; c.gridy = 4; c.anchor = GridBagConstraints.FIRST_LINE_START; autoIDEnd = new JSpinner(new SpinnerNumberModel(-1, -1, Integer.MAX_VALUE, 1)); autoIDEnd.setPreferredSize(new Dimension(100, 20)); autoIDEnd.setValue(EntityCreationPreferences.getAutoIDEnd()); autoIDEnd.setEnabled(iterativeButton.isSelected()); autoIDEnd.addChangeListener(event -> { if ((Integer)autoIDEnd.getValue() != -1 && (Integer)autoIDEnd.getValue() <= (Integer)autoIDStart.getValue()) { autoIDStart.setValue(autoIDEnd.getValue()); } }); centerPanel.add(autoIDEnd, c); // Remember last ID checkbox c.gridx = 1; c.gridy = 5; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; c.weighty = 1.0; saveIterativeIds = new JCheckBox("Remember last ID between Prot\u00E9g\u00E9 sessions"); saveIterativeIds.setSelected(EntityCreationPreferences.getSaveAutoIDStart()); saveIterativeIds.setEnabled(iterativeButton.isSelected()); centerPanel.add(saveIterativeIds, c); // Dummy label for spacing purposes c.gridx = 2; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 0; centerPanel.add(new JLabel("")); enableAutoGeneratedIDPanel(autoIDIriFragment.isSelected()); enableLabelCreationPanel(autoIDIriFragment.isSelected()); interiorPanel.add(leftPanel, BorderLayout.LINE_START); interiorPanel.add(centerPanel, BorderLayout.CENTER); autoGeneratedIDPanel.add(interiorPanel); return autoGeneratedIDPanel; } private void enableAutoGeneratedIDPanel(boolean b) { autoIDDigitCount.setEnabled(b); autoIDEnd.setEnabled(b); autoIDPrefix.setEnabled(b); autoIDStart.setEnabled(b); autoIDSuffix.setEnabled(b); autoGeneratedIDPanel.setEnabled(b); digitCountLabel.setEnabled(b); endLabel.setEnabled(b); iterativeButton.setEnabled(b); prefixLabel.setEnabled(b); saveIterativeIds.setEnabled(b); startLabel.setEnabled(b); suffixLabel.setEnabled(b); uniqueIdButton.setEnabled(b); ideIdButton.setEnabled(b); enableNumericIterativeOptions((iterativeButton.isSelected()) && (iterativeButton.isEnabled())); } private void enableLabelCreationPanel(boolean b) { annotationSelectButton.setEnabled(b); annotationLangSelector.setEnabled(b); customLabelButton.setEnabled(b); sameAsRendererLabelButton.setEnabled(b); annotationIriLabel.setEnabled(b); } private void enableNumericIterativeOptions(boolean b) { startLabel.setEnabled(b); autoIDStart.setEnabled(b); endLabel.setEnabled(b); autoIDEnd.setEnabled(b); saveIterativeIds.setEnabled(b); } public void actionPerformed(ActionEvent e) { Object object = e.getSource(); if (object == iterativeButton) { // "Numeric (iterative)" enableNumericIterativeOptions(true); } else if (object == uniqueIdButton) { // "Numeric (pseudo random)", "Unique and meaningless" enableNumericIterativeOptions(false); } else if (object == ideIdButton) { enableNumericIterativeOptions(false); } } public void applyChanges() { EntityCreationPreferences.setUseDefaultBaseIRI(iriBaseSpecifiedIri.isSelected()); try { IRI defaultBase = IRI.create(new URI(iriDefaultBaseField.getText())); EntityCreationPreferences.setDefaultBaseIRI(defaultBase); } catch (URISyntaxException e) { logger.error("Ignoring invalid base IRI ({})", iriDefaultBaseField.getText(), e); } if (hashButton.isSelected()){ EntityCreationPreferences.setDefaultSeparator(SEP_HASH); } else if (slashButton.isSelected()){ EntityCreationPreferences.setDefaultSeparator(SEP_SLASH); } else if (colonButton.isSelected()){ EntityCreationPreferences.setDefaultSeparator(SEP_COLON); } EntityCreationPreferences.setFragmentAutoGenerated(autoIDIriFragment.isSelected()); EntityCreationPreferences.setGenerateNameLabel(autoIDIriFragment.isSelected()); EntityCreationPreferences.setGenerateIDLabel(false); if (sameAsRendererLabelButton.isSelected()){ EntityCreationPreferences.setLabelDescriptorClass(MatchRendererLabelDescriptor.class); } if (customLabelButton.isSelected()){ EntityCreationPreferences.setLabelDescriptorClass(CustomLabelDescriptor.class); } EntityCreationPreferences.setNameLabelIRI(IRI.create(annotationIriLabel.getText())); Object lang = annotationLangSelector.getSelectedItem(); if (lang != null && !lang.equals("")){ EntityCreationPreferences.setNameLabelLang((String)lang); } else{ EntityCreationPreferences.setNameLabelLang(null); } if (iterativeButton.isSelected()){ EntityCreationPreferences.setAutoIDGeneratorClass(IterativeAutoIDGenerator.class); } if (uniqueIdButton.isSelected()) { EntityCreationPreferences.setAutoIDGeneratorClass(UniqueIdGenerator.class); } if (ideIdButton.isSelected()) { EntityCreationPreferences.setAutoIDGeneratorClass(RandomProlong.class); } EntityCreationPreferences.setAutoIDStart((Integer)autoIDStart.getValue()); EntityCreationPreferences.setAutoIDEnd((Integer)autoIDEnd.getValue()); EntityCreationPreferences.setAutoIDDigitCount((Integer)autoIDDigitCount.getValue()); EntityCreationPreferences.setPrefix(autoIDPrefix.getText()); EntityCreationPreferences.setSuffix(autoIDSuffix.getText()); EntityCreationPreferences.setSaveAutoIDStart(saveIterativeIds.isSelected()); } private void handleActionEndWithID() { boolean selected = autoIDIriFragment.isSelected(); enableAutoGeneratedIDPanel(selected); enableLabelCreationPanel(selected); } private void handleActionEndWithName() { boolean selected = nameAsIriFragment.isSelected(); if (selected) { enableAutoGeneratedIDPanel(false); enableLabelCreationPanel(false); } } protected void handleSelectAnnotation() { OWLAnnotationProperty prop = new UIHelper(getOWLEditorKit()).pickAnnotationProperty(); if (prop != null){ labelAnnotation = prop.getIRI(); annotationIriLabel.setText(labelAnnotation.toString()); } } public IRI getFirstRendererLabel() { final java.util.List<IRI> iris = OWLRendererPreferences.getInstance().getAnnotationIRIs(); if (!iris.isEmpty()){ return iris.get(0); } return OWLRDFVocabulary.RDFS_LABEL.getIRI(); } public void dispose() throws Exception { } }
36.805172
122
0.675224
d872ac1d6d8a8775394053d5e372c09a260e1e3f
1,637
package mage.cards.l; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.keyword.HeroicAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.TargetController; import mage.filter.FilterPermanent; import mage.target.TargetPermanent; /** * * @author LevelX2 */ public final class LeoninIconoclast extends CardImpl { private static final FilterPermanent filter = new FilterPermanent("enchantment creature an opponent controls"); static { filter.add(CardType.ENCHANTMENT.getPredicate()); filter.add(CardType.CREATURE.getPredicate()); filter.add(TargetController.OPPONENT.getControllerPredicate()); } public LeoninIconoclast(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{W}"); this.subtype.add(SubType.CAT); this.subtype.add(SubType.MONK); this.power = new MageInt(3); this.toughness = new MageInt(2); // Heroic — Whenever you cast a spell that targets Leonin Iconoclast, destroy target enchantment creature an opponent controls. Ability ability = new HeroicAbility(new DestroyTargetEffect()); ability.addTarget(new TargetPermanent(filter)); this.addAbility(ability); } private LeoninIconoclast(final LeoninIconoclast card) { super(card); } @Override public LeoninIconoclast copy() { return new LeoninIconoclast(this); } }
30.314815
135
0.725718
4fd9160256973e619ab701e1532e5eb2cf49698e
915
package io.eventuate.tram.commands.consumer; import io.eventuate.tram.messaging.common.Message; import java.util.List; import java.util.Optional; import java.util.Set; import static java.util.stream.Collectors.toSet; public class CommandHandlers { private List<CommandHandler> handlers; public CommandHandlers(List<CommandHandler> handlers) { this.handlers = handlers; } public Set<String> getChannels() { return handlers.stream().map(CommandHandler::getChannel).collect(toSet()); } public Optional<CommandHandler> findTargetMethod(Message message) { return handlers.stream().filter(h -> h.handles(message)).findFirst(); } public Optional<CommandExceptionHandler> findExceptionHandler(Throwable cause) { cause.printStackTrace(); throw new UnsupportedOperationException("implement me", cause); } public List<CommandHandler> getHandlers() { return handlers; } }
26.142857
82
0.756284
d0779d4503b860b2ea1d2027b7b422e470bb3f84
4,048
package com.github.emm035.openapi.schema.generator.internal.visitors; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.github.emm035.openapi.core.v3.references.Referenceable; import com.github.emm035.openapi.core.v3.schemas.ObjectSchema; import com.github.emm035.openapi.core.v3.schemas.Schema; import com.github.emm035.openapi.schema.generator.annotations.Extension; import com.github.emm035.openapi.schema.generator.annotations.SchemaProperty; import com.github.emm035.openapi.schema.generator.extension.PropertyExtension; import com.github.emm035.openapi.schema.generator.extension.SchemaExtension; import com.github.emm035.openapi.schema.generator.internal.Generator; import com.github.emm035.openapi.schema.generator.internal.RefFactory; import com.github.emm035.openapi.schema.generator.internal.SchemasCache; import com.github.emm035.openapi.schema.generator.internal.TypeUtils; import com.github.emm035.openapi.schema.generator.internal.generators.NestedSchemaGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import java.util.Optional; public class ObjectFormatVisitor extends JsonObjectFormatVisitor.Base implements Generator { private final JavaType javaType; private final SchemasCache schemasCache; private final SchemaExtension schemaExtension; private final PropertyExtension propertyExtension; private final RefFactory refFactory; private final NestedSchemaGenerator nestedSchemaGenerator; private final ObjectSchema.Builder schemaBuilder; @Inject public ObjectFormatVisitor( @Assisted JavaType javaType, @Extension SchemaExtension schemaExtension, @Extension PropertyExtension propertyExtension, SchemasCache schemasCache, RefFactory refFactory, NestedSchemaGenerator nestedSchemaGenerator ) { this.javaType = javaType; this.schemasCache = schemasCache; this.schemaExtension = schemaExtension; this.propertyExtension = propertyExtension; this.refFactory = refFactory; this.nestedSchemaGenerator = nestedSchemaGenerator; this.schemaBuilder = ObjectSchema.builder(); } @Override public void property(BeanProperty prop) throws JsonMappingException { this.schemaBuilder.addRequired(prop.getName()); optionalProperty(prop); } @Override public void optionalProperty(BeanProperty prop) throws JsonMappingException { String typeName = TypeUtils.toTypeName(TypeUtils.unwrap(prop.getType())); Referenceable<Schema> schema; if (schemasCache.contains(typeName)) { schema = refFactory.create(typeName); } else { schema = nestedSchemaGenerator.generateSchema(TypeUtils.unwrap(prop.getType()), false); } Schema modifiedSchema = propertyExtension.modify(schemasCache.resolve(schema), prop); // Overwrite schema if needed if (schema.isReferential()) { this.schemaBuilder.putProperties( getPropertyName(prop), schemasCache.putSchema(prop.getName(), modifiedSchema) ); } else { this.schemaBuilder.putProperties(getPropertyName(prop), modifiedSchema); } } private String getPropertyName(BeanProperty prop) { return Optional .ofNullable(prop.getAnnotation(SchemaProperty.class)) .map(SchemaProperty::value) .orElseGet(prop::getName); } //===============// // Generator API // //===============// @Override public Referenceable<Schema> emit(boolean asReference) throws JsonMappingException { Schema schema = schemaExtension.modify(schemaBuilder.build(), javaType); if (asReference) { return schemasCache.putSchema(TypeUtils.toTypeName(javaType), schema); } return schema; } //==================// // Assisted Factory // //==================// public interface Factory { ObjectFormatVisitor create(JavaType javaType); } }
36.8
92
0.763587
dbb4123a910ad1799bc6a1645d849cb9ccb414c3
3,878
/** * Copyright 2003-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package org.codehaus.groovy.ast; import junit.framework.TestCase; import org.codehaus.groovy.ast.expr.VariableExpression; /** * Tests the VariableExpressionNode * * @author <a href="mailto:[email protected]">Martin Kempf</a> * */ public class VariableExpressionTest extends TestCase { public void testPrimitiveOriginType() { VariableExpression boolExpression = new VariableExpression("fo",ClassHelper.boolean_TYPE); VariableExpression intExpression = new VariableExpression("foo", ClassHelper.int_TYPE); assertEquals(boolExpression.getOriginType().getName(),"boolean"); assertEquals(intExpression.getOriginType().getName(),"int"); } public void testNonPrimitiveOriginType() { VariableExpression boolExpression = new VariableExpression("foo",ClassHelper.Boolean_TYPE); VariableExpression intExpression = new VariableExpression("foo", ClassHelper.Integer_TYPE); assertEquals(boolExpression.getOriginType().getName(),"java.lang.Boolean"); assertEquals(intExpression.getOriginType().getName(),"java.lang.Integer"); } public void testPrimitiveOriginTypeConstructorVariableExpression() { VariableExpression boolExpression = new VariableExpression("foo",ClassHelper.boolean_TYPE); VariableExpression intExpression = new VariableExpression("foo", ClassHelper.int_TYPE); VariableExpression newBoolExpression = new VariableExpression(boolExpression); VariableExpression newIntExpression = new VariableExpression(intExpression); assertEquals(newBoolExpression.getOriginType().getName(),"boolean"); assertEquals(newIntExpression.getOriginType().getName(),"int"); } public void testPrimitiveOriginTypeConstructorParameter() { Parameter boolParameter = new Parameter(ClassHelper.boolean_TYPE,"foo"); Parameter intParameter = new Parameter(ClassHelper.int_TYPE,"foo"); VariableExpression newBoolExpression = new VariableExpression(boolParameter); VariableExpression newIntExpression = new VariableExpression(intParameter); assertEquals(newBoolExpression.getOriginType().getName(),"boolean"); assertEquals(newIntExpression.getOriginType().getName(),"int"); } public void testPrimitiveOriginTypeConstructorDynVariable() { DynamicVariable dynVariable = new DynamicVariable("foo",false); assertEquals(dynVariable.getOriginType().getName(),"java.lang.Object"); } public void testIsDynamicTypedExplicitObject() { VariableExpression intExpression = new VariableExpression("foo", new ClassNode(Object.class)); assertFalse(intExpression.isDynamicTyped()); } public void testIsDynamicTyped_DYNMAMIC_TYPE() { VariableExpression intExpression = new VariableExpression("foo", ClassHelper.DYNAMIC_TYPE); assertTrue(intExpression.isDynamicTyped()); } public void testIsDynamicTyped_DynamicVariable() { VariableExpression intExpression = new VariableExpression(new DynamicVariable("foo",false)); assertTrue(intExpression.isDynamicTyped()); } }
45.623529
103
0.721248
f702768fc3baef11af6700f51bb15f8602949a70
615
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.model.entry.AuthorList; /** * <ul> * <li>Names are given as first name, von and last name.</li> * <li>First names will not be abbreviated.</li> * <li>Individual authors separated by comma.</li> * <li>There is no comma before the and of a list of three or more authors.</li> * </ul> */ public class AuthorFirstLastCommas implements LayoutFormatter { @Override public String format(String fieldText) { return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, false, false); } }
27.954545
81
0.723577
817d129d2aa6258a3971c6ddef442af81f7d61ca
6,782
package com.adsdk.sdk.nativeformats; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.Thread.UncaughtExceptionHandler; import java.nio.charset.Charset; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpGet; import android.content.Context; import android.net.http.AndroidHttpClient; import android.os.Build; import android.os.Handler; import android.view.ViewGroup; import com.adsdk.sdk.Log; import com.adsdk.sdk.RequestException; import com.adsdk.sdk.Util; import com.adsdk.sdk.nativeformats.creative.Creative; import com.adsdk.sdk.nativeformats.creative.CreativesManager; /** * Created by itamar on 16/03/15. */ public class NativeFormat { private static final String BASE_URL = "http://my.mobfox.com/request.php"; private Handler handler; String publicationId; CreativesManager creative_manager; int width; int height; Context ctx; final static String TYPE_BLOCK = "block"; final static String TYPE_STRIPE = "stripe"; // public void WriteTemp(String data) { // // FileOutputStream fop = null; // // try { // // File temp = File.createTempFile("creative", ".html"); // fop = new FileOutputStream(temp); // // fop.write(data.getBytes(Charset.forName("UTF-8"))); // // android.util.Log.d("FilePath", temp.getAbsolutePath()); // android.util.Log.d("FileData", data); // // } catch(IOException e) { // // e.printStackTrace(); // // } // } public interface Listener { public void onSuccess(String template, String data); public void onError(Exception e); } NativeFormat(Context ctx, int width, int height, String publicationId) { this.ctx = ctx; this.width = width; this.height = height; this.publicationId = publicationId; this.creative_manager = CreativesManager.getInstance(this.ctx,publicationId); } // --------------------------------------------------------- public void loadAd(String webviewUserAgent, final Listener listener) { float ratio = height / width; String type = NativeFormat.TYPE_BLOCK; if ( ratio < 0.5 ) { type = NativeFormat.TYPE_STRIPE; } if(Build.FINGERPRINT.startsWith("generic")){ webviewUserAgent = ""; } final Creative creative = creative_manager.getCreative(type,webviewUserAgent); final NativeFormatRequest request = new NativeFormatRequest(); request.setRequestUrl(BASE_URL); request.setPublisherId(this.publicationId); // TODO: check if correctly set String ipAddress = Utils.getIPAddress(); //TODO: can we remove it? Other requests don't send IP if (ipAddress.indexOf("10.") == 0 || ipAddress.length() == 0) { ipAddress = "2.122.29.194"; } request.ip = ipAddress; // request.add("o_androidid", Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID)); //TODO: we cannot use this ID anymore (only Google Advertising ID) // params.add("o_andadvid", "c86f7529-33e2-4346-be0d-777ac53be320");//AdvertisingIdClient.getAdvertisingIdInfo(this.getContext()).getId()); request.setAndroidAdId(Util.getAndroidAdId()); request.setAdDoNotTrack(Util.hasAdDoNotTrack()); request.setUserAgent(Util.getDefaultUserAgentString(ctx)); request.setUserAgent2(Util.buildUserAgent()); request.setTemplateName(creative.getName()); Log.d("starting build"); Log.d("native req: "+request.toUri()); handler = new Handler(); Thread requestThread = new Thread(new Runnable() { @Override public void run() { AndroidHttpClient client = null; try { client = AndroidHttpClient.newInstance(System.getProperty("http.agent")); final String url = request.toString(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", System.getProperty("http.agent")); HttpResponse response = client.execute(request); Log.v("sent request"); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { Log.v("start build response"); StringBuilder builder = new StringBuilder(); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } final String data = builder.toString(); android.util.Log.d("builder.toString()", builder.toString()); Log.v("build got data"); if (data.length() == 0) { handler.post(new Runnable() { @Override public void run() { listener.onError(new RequestException("empty response from: " + url)); } }); return; } Log.v("builder: "+data); handler.post(new Runnable() { @Override public void run() { listener.onSuccess(creative.getTemplate(), data); } }); } else { handler.post(new Runnable() { @Override public void run() { listener.onError(new RequestException("request failed: " + url)); } }); return; } } catch (final Exception e) { handler.post(new Runnable() { @Override public void run() { listener.onError(e); } }); } finally { if (client != null) { client.close(); } } } }); requestThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { listener.onError(new Exception(ex)); } }); requestThread.start(); }; // --------------------------------------------------------- }
30.687783
195
0.576231
035c4a7e92b239ad306adcfd5904461d453498a9
33,171
/* * This file is part of OpenTSDB. * Copyright (C) 2021 Yahoo. * * 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 net.opentsdb.aura.metrics; import com.aerospike.client.AerospikeException; import com.aerospike.client.Operation; import com.aerospike.client.ResultCode; import com.aerospike.client.Value; import com.aerospike.client.cdt.MapReturnType; import com.aerospike.client.cluster.Cluster; import com.aerospike.client.cluster.Connection; import com.aerospike.client.cluster.Node; import com.aerospike.client.cluster.Partition; import com.aerospike.client.command.Buffer; import com.aerospike.client.command.Command; import com.aerospike.client.command.FieldType; import com.aerospike.client.command.OperateArgs; import com.aerospike.client.command.ParticleType; import com.aerospike.client.command.SyncCommand; import com.aerospike.client.policy.Policy; import com.aerospike.client.policy.WritePolicy; import com.aerospike.client.util.Util; import net.opentsdb.aura.metrics.operation.MapOperation; import net.opentsdb.aura.metrics.operation.MapPolicy; import net.opentsdb.aura.metrics.operation.OperationLocal; import io.ultrabrew.metrics.Counter; import io.ultrabrew.metrics.MetricRegistry; import io.ultrabrew.metrics.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * A pared down Aerospike client that attempts to avoid copying byte arrays and * instantiating objects as much as possible. The client is thread safe and makes use of * thread locals. Instantiate one of these per namespace per app and share. Return * codes are used instead of {@link AerospikeException}s as well * though some exceptions may be thrown. * <p> * <b>WARNING:</b> Once you call a write or read method, do NOT pass the results * to another thread or modify any of the given arrays in another thread otherwise * the results will be indeterminate. * * TODO - We can make the reads a bit more efficient by unpacking the unpacking library * and pulling out it's methods into the record iterator. * TODO - There will likely be more calls to implement. * TODO - May want to make the namespace a param for calls as well. * TODO - We're only dealing with single calls for now. Batching can come later and * async as well. Throttling is a pain in the neck with async as is safely handling * all of the arrays. * TODO - Some logging please. */ public class ASSyncClient { private static final Logger LOGGER = LoggerFactory.getLogger(ASSyncClient.class); /** The cluster we're working with. */ private final Cluster cluster; /** The namespace this client works on. */ private final String namespace; /** Where we're reporting metrics. */ private final MetricRegistry metricRegistry; /** The thread local commands list. */ private ThreadLocal<ASCommand> operations; /** Policies. TODO - set these. */ private final WritePolicy defaultWritePolicy; private final Policy defaultReadPolicy; /** Metric tags. */ private final String[] tags; // Interactions private volatile long rawWrites; private volatile long rawReads; private volatile long mapWrites; private volatile long mapReads; // AS IO private volatile long timeouts; private volatile long exceptions; private volatile long retries; private volatile long ioExceptions; private volatile long socketTimeouts; private volatile long closedNodeConnections; private volatile long rePooledConnections; private volatile long bytesSent; private volatile long bytesRead; private volatile long bytesDiscarded; private volatile Timer callTimer; private volatile Timer overallTimer; /** * Default ctor. * @param cluster The non-null cluster to work with. * @param namespace The non-null namespace to write to. * @param metricRegistry The metric registry to write metrics to. * @param executorService A thread to schedule writes to the registry for * high-perf counters, etc. */ public ASSyncClient(final Cluster cluster, final String namespace, final MetricRegistry metricRegistry, final ScheduledExecutorService executorService) { this.cluster = cluster; this.namespace = namespace; this.metricRegistry = metricRegistry; operations = new ThreadLocal<ASCommand>() { @Override protected ASCommand initialValue() { return new ASCommand(); } }; defaultWritePolicy = new WritePolicy(); defaultReadPolicy = new Policy(); tags = new String[] { "namespace", namespace, "callType", "singleSync" }; executorService.scheduleAtFixedRate(new MetricFlusher(), TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); callTimer = metricRegistry.timer("AerospikeClient.tcp.call.latency"); overallTimer = metricRegistry.timer("AerospikeClient.overall.call.latency"); } /** * Attempts to write or overwrite the record in the cluster. * @param key The non-null and non-empty key to write. * @param setBytes An optional set. * @param bin An optional bin. * @param value The non-null (I think) value to write. * @return A {@link ResultCode}. */ public int write(final byte[] key, final byte[] setBytes, final byte[] bin, final byte[] value) { ++rawWrites; final ASCommand cmd = operations.get(); cmd.byteValue.bytes = value; final OperationLocal op = new OperationLocal( Operation.Type.WRITE, bin, cmd.byteValue); return cmd.write(defaultWritePolicy, key, setBytes, op); } /** * Attempts to write or overwrite the key in the map in the record. These keys are * 4 byte integers. * TODO - may want to do shorts or even bytes. * @param key The non-null and non-empty key to write. * @param setBytes An optional set. * @param bin An optional bin. * @param mapKey The key for the map entry. * @param value The non-null (I think) value to write. * @return A {@link ResultCode}. */ public int putInMap(final byte[] key, final byte[] setBytes, final byte[] bin, final int mapKey, final byte[] value) { ++mapWrites; final ASCommand cmd = operations.get(); cmd.byteValue.bytes = value; final OperationLocal op = cmd.mapOp.put( MapPolicy.Default, bin, mapKey, cmd.byteValue); return cmd.write(defaultWritePolicy, key, setBytes, op); } /** * Attempts to write or overwrite the key in the map in the record. These keys are * 4 byte integers. * TODO - may want to do shorts or even bytes. * @param key The non-null and non-empty key to write. * @param setBytes An optional set. * @param bin An optional bin. * @param mapKey The key for the map entry. * @param value The non-null (I think) value to write. * @return A {@link ResultCode}. */ public int putInMap(final byte[] key, final byte[] setBytes, final byte[] bin, final int mapKey, final Value value) { ++mapWrites; final ASCommand cmd = operations.get(); final OperationLocal op = cmd.mapOp.put(MapPolicy.Default, bin, mapKey, value); return cmd.write(defaultWritePolicy, key, setBytes, op); } /** * Attempts to read the record from the cluster. See * {@link RecordIterator#getResultCode()} before advancing the records. * @param key The non-null and non-empty key to fetch. * @param setBytes An optional set. * @param bin An optional bin. * @return The thread-local {@link RecordIterator}, always non-null. */ public RecordIterator get(final byte[] key, final byte[] setBytes, final byte[] bin) { ++rawReads; final ASCommand cmd = operations.get(); final OperationLocal op = new OperationLocal(Operation.Type.READ, bin); return cmd.read(defaultReadPolicy, key, setBytes, op); } /** * Attempts to read a range of map entries from the cluster. See * {@link RecordIterator#getResultCode()} before advancing the records. * @param key The non-null and non-empty key to fetch. * @param setBytes An optional set. * @param bin An optional bin. * @param start The first key to read, inclusive. * @param end The key to read up to, exclusive. * @return The thread-local {@link RecordIterator}, always non-null. */ public RecordIterator mapRangeQuery(final byte[] key, final byte[] setBytes, final byte[] bin, final int start, final int end) { ++mapReads; final ASCommand cmd = operations.get(); final OperationLocal op = cmd.mapOp.getByKeyRange(bin, start, end, MapReturnType.KEY_VALUE); return cmd.read(defaultReadPolicy, key, setBytes, op); } /** * <b>WARNING:</b> This will shutdown the CLUSTER passed here! Only call it if you are * finished with all clients. Or just close the cluster directly. There isn't anything * to shutdown here EXCEPT for the metric gathering task that's in the shared scheduler * thread. This client will stick around until that executor is killed. */ public void shutdown() { cluster.close(); } /** * A thread local command that is reset on each of the preceding calls with * memory re-used as much as possible. */ private class ASCommand extends SyncCommand { /** The policy we're currently working with. */ private Policy policy; /** Hasher that avoids creating new byte arrays. */ private UpdatingRipeMD160 hasher; /** The AS Set we're writing to. Optional. */ private byte[] setBytes; /** The operating args. */ private OperateArgs args; /** The operation we're executing. */ private OperationLocal op; /** An optional map operation. */ private MapOperation mapOp; /** The results of a call if it returns data. */ private RecordIterator recordIterator; /** A value to store the byte array when applicable. */ private ByteValue byteValue; /** * Defautl ctor. */ ASCommand() { super(); hasher = new UpdatingRipeMD160(); args = new OperateArgs(); mapOp = new MapOperation(); recordIterator = new RecordIterator(); byteValue = new ByteValue(null); } /** * Resets the state. */ private void clearOperationArgs() { args.hasWrite = false; args.readAttr = 0; args.size = 0; args.writeAttr = 0; } /** * Hopefully obvious, attempts to write data to the cluster. * @param writePolicy The non-null write policy. * @param key The non-null and non-empty key. * @param setBytes An optional set. * @param op The non-null operation to execute. * @return A {@link ResultCode}. */ private int write(final WritePolicy writePolicy, final byte[] key, final byte[] setBytes, final OperationLocal op) { clearOperationArgs(); args.writeAttr = Command.INFO2_WRITE; args.hasWrite = true; this.policy = writePolicy; this.setBytes = setBytes; hasher.update(setBytes, 0, setBytes.length); hasher.update((byte) ParticleType.BLOB); hasher.update(key, 0, key.length); hasher.digest(); // updates in the ByteValue this.op = op; // estimate the size and set our dataOffset: dataOffset += op.binName.length + OPERATION_HEADER_SIZE; dataOffset += op.value.estimateSize(); if (writePolicy.respondAllOps) { args.writeAttr |= Command.INFO2_RESPOND_ALL_OPS; } args.size = dataOffset; return executeLocal(cluster, writePolicy, null, false); } /** * Hopefully obvious. Attempts to read something from the cluster. * @param policy The non-null write policy. * @param key The non-null and non-empty key. * @param setBytes An optional set. * @param op The non-null operation to execute. * @return A {@link ResultCode}. */ private RecordIterator read(final Policy policy, final byte[] key, final byte[] setBytes, final OperationLocal op) { clearOperationArgs(); this.policy = policy; hasher.update(setBytes, 0, setBytes.length); hasher.update((byte) ParticleType.BLOB); hasher.update(key, 0, key.length); hasher.digest(); // updates in the ByteValue this.op = op; // estimate the size and set our dataOffset: dataOffset += op.binName.length + OPERATION_HEADER_SIZE; dataOffset += op.value.estimateSize(); args.readAttr = Command.INFO1_READ; args.size = dataOffset; executeLocal(cluster, policy, null, false); return recordIterator; } @Override protected void writeBuffer() { begin(); int fieldCount = estimateKeySize(); dataOffset += args.size; sizeBuffer(); writeHeader(policy, args.readAttr, args.writeAttr, fieldCount, 1); writeKey(); writeOperation(op); end(); } /** * Local override to figure out how big the key is going to be. Increments * the data offset. * @return The number of fields. */ private final int estimateKeySize() { int fieldCount = 0; if (namespace != null) { dataOffset += Buffer.estimateSizeUtf8(namespace) + FIELD_HEADER_SIZE; fieldCount++; } if (setBytes != null) { dataOffset += setBytes.length + FIELD_HEADER_SIZE; fieldCount++; } dataOffset += hasher.getDigest().length + FIELD_HEADER_SIZE; fieldCount++; /* NOT using at this time. if (policy.sendKey) { dataOffset += key.userKey.estimateSize() + FIELD_HEADER_SIZE + 1; fieldCount++; }*/ return fieldCount; } /** * Writes what {@link #estimateKeySize()} estimated. */ private final void writeKey() { // Write key into buffer. if (namespace != null) { writeField(namespace, FieldType.NAMESPACE); } if (setBytes != null) { writeField(setBytes, FieldType.TABLE); } writeField(hasher.getDigest(), FieldType.DIGEST_RIPE); /* NOT using at this time if (policy.sendKey) { writeField(key.userKey, FieldType.KEY); }*/ } /** * Serializes the operation. * @param operation The non-null operation to serialize. */ private void writeOperation(final OperationLocal operation) { System.arraycopy(op.binName, 0, dataBuffer, dataOffset + OPERATION_HEADER_SIZE, op.binName.length); int nameLength = op.binName.length; int valueLength = operation.value.write(dataBuffer, dataOffset + OPERATION_HEADER_SIZE + nameLength); Buffer.intToBytes(nameLength + valueLength + 4, dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = (byte) operation.type.protocolType; dataBuffer[dataOffset++] = (byte) operation.value.getType(); dataBuffer[dataOffset++] = (byte) 0; dataBuffer[dataOffset++] = (byte) nameLength; dataOffset += nameLength + valueLength; } /** * Cribbed from the super class. All of this to avoid allocations in the * {@link Partition} class (which we still have to instantiate since the fields * are final but at least it's small). * @param cluster The non-null cluster. * @param policy The non-null policy. * @param node Optional node to write to. * @param isRead Whether or not the op is a read or write. * @return The {@link ResultCode}. */ public int executeLocal(final Cluster cluster, final Policy policy, Node node, final boolean isRead) { int partitionId = (Buffer.littleBytesToInt(hasher.getDigest(), 0) & 0xFFFF) % Node.PARTITIONS; final Partition partition = new Partition(namespace, partitionId); AerospikeException exception = null; long deadline = 0; int socketTimeout = policy.socketTimeout; int totalTimeout = policy.totalTimeout; int iteration = 0; int commandSentCounter = 0; boolean isClientTimeout; if (totalTimeout > 0) { deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(totalTimeout); if (socketTimeout == 0 || socketTimeout > totalTimeout) { socketTimeout = totalTimeout; } } // Execute command until successful, timed out or maximum iterations have been reached. long overallStart = System.nanoTime(); while (true) { try { if (partition != null) { // Single record command node retrieval. node = getNode(cluster, partition, policy.replica, isRead); } Connection conn = node.getConnection(socketTimeout); try { // Set command buffer. writeBuffer(); // Check if total timeout needs to be changed in send buffer. if (totalTimeout != policy.totalTimeout) { // Reset timeout in send buffer (destined for server) and socket. Buffer.intToBytes(totalTimeout, dataBuffer, 22); } // Send command. bytesSent += dataOffset; conn.write(dataBuffer, dataOffset); commandSentCounter++; // Parse results. parseResult(conn); // Put connection back in pool. node.putConnection(conn); ++rePooledConnections; // Command has completed successfully. Exit method. overallTimer.update(System.nanoTime() - overallStart, tags); return ResultCode.OK; } catch (AerospikeException ae) { LOGGER.debug("AS Ex", ae); if (ae.keepConnection()) { // Put connection back in pool. node.putConnection(conn); ++rePooledConnections; } else { // Close socket to flush out possible garbage. Do not put back in pool. node.closeConnection(conn); ++closedNodeConnections; } if (ae.getResultCode() == ResultCode.TIMEOUT) { ++timeouts; // Go through retry logic on server timeout. LOGGER.warn("Server timeout: {}, {}, {}", node, sequence, iteration); exception = new AerospikeException.Timeout(node, policy, iteration + 1, false); isClientTimeout = false; if (isRead) { super.sequence++; } } else { ++exceptions; LOGGER.debug("Throw AerospikeException: {}, {}, {}, {}", node, sequence, iteration, ae.getResultCode()); ae.setInDoubt(isRead, commandSentCounter); throw ae; } } catch (RuntimeException re) { ++exceptions; // All runtime exceptions are considered fatal. Do not retry. // Close socket to flush out possible garbage. Do not put back in pool. LOGGER.debug("Throw RuntimeException: {}, {}, {}", node, sequence, iteration); node.closeConnection(conn); throw re; } catch (SocketTimeoutException ste) { ++socketTimeouts; // Full timeout has been reached. LOGGER.warn("Socket timeout: {}, {}, {}", node, sequence, iteration); node.closeConnection(conn); isClientTimeout = true; if (isRead) { super.sequence++; } } catch (IOException ioe) { ++ioExceptions; // IO errors are considered temporary anomalies. Retry. LOGGER.warn("IOException: {}, {}, {}", node, sequence, iteration); node.closeConnection(conn); exception = new AerospikeException(ioe); isClientTimeout = false; super.sequence++; } } catch (AerospikeException.Connection ce) { // Socket connection error has occurred. Retry. LOGGER.warn("Connection error: {}, {}, {}", node, sequence, iteration); exception = ce; isClientTimeout = false; super.sequence++; } // Check maxRetries. if (++iteration > policy.maxRetries) { break; } ++retries; if (policy.totalTimeout > 0) { // Check for total timeout. long remaining = deadline - System.nanoTime() - TimeUnit.MILLISECONDS.toNanos(policy.sleepBetweenRetries); if (remaining <= 0) { break; } // Convert back to milliseconds for remaining check. remaining = TimeUnit.NANOSECONDS.toMillis(remaining); if (remaining < totalTimeout) { totalTimeout = (int)remaining; if (socketTimeout > totalTimeout) { socketTimeout = totalTimeout; } } } if (!isClientTimeout && policy.sleepBetweenRetries > 0) { // Sleep before trying again. Util.sleep(policy.sleepBetweenRetries); } } // Retries have been exhausted. Throw last exception. if (isClientTimeout) { LOGGER.warn("SocketTimeoutException: {}, {}", sequence, iteration); //exception = new AerospikeException.Timeout(node, policy, iteration, true); ++timeouts; overallTimer.update(System.nanoTime() - overallStart, tags); return ResultCode.TIMEOUT; } LOGGER.debug(String.format("Runtime exception: %s, %d, %d", node.toString(), sequence, iteration), exception); exception.setInDoubt(isRead, commandSentCounter); ++exceptions; throw exception; } @Override protected void parseResult(final Connection conn) throws AerospikeException, IOException { // Read header. long start = System.nanoTime(); conn.readFully(dataBuffer, MSG_TOTAL_HEADER_SIZE); long timeTaken = System.nanoTime() - start; callTimer.update(timeTaken, tags); bytesRead += MSG_TOTAL_HEADER_SIZE; int resultCode = dataBuffer[13] & 0xFF; if (resultCode != 0) { if (resultCode == ResultCode.KEY_NOT_FOUND_ERROR || resultCode == ResultCode.LARGE_ITEM_NOT_FOUND) { // no-op; recordIterator.reset(resultCode); bytesDiscarded += emptySocket2(conn); return; } // TODO - UDF errors if we use em. if (policy instanceof WritePolicy) { recordIterator.reset(ResultCode.OK); bytesDiscarded += emptySocket2(conn); } return; } if (policy instanceof WritePolicy) { // don't care about the records and don't want em. recordIterator.reset(ResultCode.OK); bytesDiscarded += emptySocket2(conn); return; } // keep parsing long sz = Buffer.bytesToLong(dataBuffer, 0); byte headerLength = dataBuffer[8]; int generation = Buffer.bytesToInt(dataBuffer, 14); int expiration = Buffer.bytesToInt(dataBuffer, 18); int fieldCount = Buffer.bytesToShort(dataBuffer, 26); // almost certainly 0 int opCount = Buffer.bytesToShort(dataBuffer, 28); int receiveSize = ((int) (sz & 0xFFFFFFFFFFFFL)) - headerLength; if (receiveSize > 0) { sizeBuffer(receiveSize); conn.readFully(dataBuffer, receiveSize); bytesRead += receiveSize; } if (opCount == 0) { // Bin data was not returned. recordIterator.reset(ResultCode.OK); return; } recordIterator.parseRecord(opCount, fieldCount, generation, expiration, dataBuffer); } protected int emptySocket2(Connection conn) throws IOException { // There should not be any more bytes. // Empty the socket to be safe. long sz = Buffer.bytesToLong(dataBuffer, 0); int headerLength = dataBuffer[8]; int receiveSize = ((int)(sz & 0xFFFFFFFFFFFFL)) - headerLength; // Read remaining message bytes. if (receiveSize > 0) { sizeBuffer(receiveSize); conn.readFully(dataBuffer, receiveSize); } return receiveSize; } } /** * Ugly but it's a way to avoid lookups and writes in the Ultrabrew tables on every client * interaction. */ class MetricFlusher implements Runnable { // Interactions private final Counter rawWrites; private final Counter mapWrites; private final Counter rawReads; private final Counter mapReads; // AS IO private final Counter timeouts; private final Counter exceptions; private final Counter retries; private final Counter ioExceptions; private final Counter socketTimeouts; private final Counter closedNodeConnections; private final Counter rePooledConnections; private final Counter bytesSent; private final Counter bytesRead; private final Counter bytesDiscarded; // Interactions private long prevRawWrites; private long prevRawReads; private long prevMapWrites; private long prevMapReads; // AS IO private long prevTimeouts; private long prevExceptions; private long prevRetries; private long prevIoExceptions; private long prevSocketTimeouts; private long prevClosedNodeConnection; private long prevRePooledConnection; private long prevBytesSent; private long prevBytesRead; private long prevBytesDiscarded; MetricFlusher() { rawWrites = metricRegistry.counter("AerospikeClient.raw.writes.attempts"); rawReads = metricRegistry.counter("AerospikeClient.raw.reads.attempts"); mapWrites = metricRegistry.counter("AerospikeClient.map.writes.attempts"); mapReads = metricRegistry.counter("AerospikeClient.map.reads.attempts"); timeouts = metricRegistry.counter("AerospikeClient.io.timeouts"); exceptions = metricRegistry.counter("AerospikeClient.io.exceptions"); retries = metricRegistry.counter("AerospikeClient.io.retries"); ioExceptions = metricRegistry.counter("AerospikeClient.io.ioExceptions"); socketTimeouts = metricRegistry.counter("AerospikeClient.io.socketTimeout"); closedNodeConnections = metricRegistry.counter("AerospikeClient.io.closedNodeConnections"); rePooledConnections = metricRegistry.counter("AerospikeClient.io.rePooledConnections"); bytesSent = metricRegistry.counter("AerospikeClient.io.bytesSent"); bytesRead = metricRegistry.counter("AerospikeClient.io.bytesRead"); bytesDiscarded = metricRegistry.counter("AerospikeClient.io.bytesSkipped"); } @Override public void run() { prevRawWrites = updateCounter(ASSyncClient.this.rawWrites, prevRawWrites, rawWrites); prevRawReads = updateCounter(ASSyncClient.this.rawReads, prevRawReads, rawReads); prevMapWrites = updateCounter(ASSyncClient.this.mapWrites, prevMapWrites, mapWrites); prevMapReads = updateCounter(ASSyncClient.this.mapReads, prevMapReads, mapReads); prevTimeouts = updateCounter(ASSyncClient.this.timeouts, prevTimeouts, timeouts); prevExceptions = updateCounter(ASSyncClient.this.exceptions, prevExceptions, exceptions); prevRetries = updateCounter(ASSyncClient.this.retries, prevRetries, retries); prevIoExceptions = updateCounter(ASSyncClient.this.ioExceptions, prevIoExceptions, ioExceptions); prevSocketTimeouts = updateCounter(ASSyncClient.this.socketTimeouts, prevSocketTimeouts, socketTimeouts); prevClosedNodeConnection = updateCounter(ASSyncClient.this.closedNodeConnections, prevClosedNodeConnection, closedNodeConnections); prevRePooledConnection = updateCounter(ASSyncClient.this.rePooledConnections, prevRePooledConnection, rePooledConnections); prevBytesSent = updateCounter(ASSyncClient.this.bytesSent, prevBytesSent, bytesSent); prevBytesRead = updateCounter(ASSyncClient.this.bytesRead, prevBytesRead, bytesRead); prevBytesDiscarded = updateCounter(ASSyncClient.this.bytesDiscarded, prevBytesDiscarded, bytesDiscarded); } long updateCounter(long latest, long previous, Counter counter) { long delta = latest - previous; counter.inc(delta, tags); return latest; } } }
41.002472
143
0.575774
373628e7af960d1d913da3fd2aacedfdaea94a01
383
package com.testing.jacoco; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class JacocoApplicationTests { @Test public void whenEmptyString_thenAccept() { Palindrome palindromeTester = new Palindrome(); Assertions.assertTrue(palindromeTester.isPalindrome("")); } }
21.277778
60
0.798956
896d2eb978eec253618c98134c2cf8204eac77af
3,184
package Listeners; import Database.*; import Frontend.WordSender; import Tools.JSONWordsDatabase; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; public class RateMessage extends ListenerAdapter { public static String ToS; /*@Override public void onMessageReceived(MessageReceivedEvent event) { String[] words = event.getMessage().getContentRaw().split(" "); for (int i = 0; i < words.length; i++) { if(!SaveTypeOfSpeech.propExist(words[i]) && words[i].length() > 0) { SaveTypeOfSpeech.save(words[i], "0"); } } if(event.getTextChannel().getId().contains(Config.load("channel"))) { event.getMessage().addReaction("✅").and(event.getMessage().addReaction("❌")).queue(); wordCount++; } Messages.save(event.getMessageId(), event.getMessage().getContentRaw()); }*/ @Override public void onMessageReceived(MessageReceivedEvent event) { if(event.getMessage().getEmbeds().size() != 1 || event.getMember().getUser() != event.getJDA().getSelfUser()) return; if(event.getMessage().getEmbeds().get(0).getFields().size() == 0) return; String[] words = event.getMessage().getEmbeds().get(0).getFooter().getText().split(" "); for (int i = 0; i < words.length; i++) { if(!SaveTypeOfSpeech.propExist(words[i]) && words[i].length() > 0) { SaveTypeOfSpeech.save(words[i], "0"); } } // if(event.getTextChannel().getId().contains(Config.load("channel"))) { // } event.getMessage().addReaction("✅").and(event.getMessage().addReaction("❌")).queue(); } @Override public void onMessageReactionAdd(MessageReactionAddEvent event) { Message msg = event.retrieveMessage().complete(); if(!event.getMember().getUser().isBot() || msg.getEmbeds().size() != 1) { if (msg.getEmbeds().get(0).getFields().size() == 0) return; if (event.getReactionEmote().getName().contains("❌")) { String[] voted = msg.getEmbeds().get(0).getFooter().getText().split(" "); for (int i = 0; i < voted.length; i++) { // NeutralCount.save(upvoted[i], Rating.addNeutralScore(upvoted[i])); JSONWordsDatabase.WordDetails.WordRating.RateWord(voted[i].toLowerCase(), false); } // WordSender.sendWord(event); } else if (event.getReactionEmote().getName().contains("✅")) { String[] voted = msg.getEmbeds().get(0).getFooter().getText().split(" "); for (int i = 0; i < voted.length; i++) { // BadCount.save(downvoted[i], Rating.addBadScore(downvoted[i])); JSONWordsDatabase.WordDetails.WordRating.RateWord(voted[i].toLowerCase(), true); } // WordSender.sendWord(event); } } } }
37.458824
117
0.584799
cb01375d5b55cbbb2ea8a4d909d096b43349cb54
2,846
package seedu.address.logic.commands.editcommand; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.TEAM_DESC_ALFRED; import static seedu.address.logic.commands.CommandTestUtil.TEAM_DESC_BRUCE; import static seedu.address.logic.commands.CommandTestUtil.VALID_LOCATION_BRUCE; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BRUCE; import static seedu.address.logic.commands.CommandTestUtil.VALID_PROJECT_NAME_BRUCE; import static seedu.address.logic.commands.CommandTestUtil.VALID_SCORE_BRUCE; import static seedu.address.logic.commands.CommandTestUtil.VALID_SUBJECT_BRUCE; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.editcommand.EditTeamCommand.EditTeamDescriptor; import seedu.address.testutil.EditTeamDescriptorBuilder; //import static seedu.address.logic.commands.CommandTestUtil.VALID_PROJECT_TYPE_BRUCE; public class EditTeamDescriptorTest { @Test public void equals() { // same values -> returns true EditTeamDescriptor descriptorWithSameValues = new EditTeamDescriptor(TEAM_DESC_ALFRED); assertTrue(TEAM_DESC_ALFRED.equals(descriptorWithSameValues)); // same object -> returns true assertTrue(TEAM_DESC_ALFRED.equals(TEAM_DESC_ALFRED)); // null -> returns false assertFalse(TEAM_DESC_ALFRED.equals(null)); // different types -> returns false assertFalse(TEAM_DESC_ALFRED.equals(5)); // different values -> returns false assertFalse(TEAM_DESC_ALFRED.equals(TEAM_DESC_BRUCE)); // different name -> returns false EditTeamDescriptor editedAlfred = new EditTeamDescriptorBuilder(TEAM_DESC_ALFRED) .withName(VALID_NAME_BRUCE).build(); assertFalse(TEAM_DESC_ALFRED.equals(editedAlfred)); // different subject -> returns false editedAlfred = new EditTeamDescriptorBuilder(TEAM_DESC_ALFRED).withSubject(VALID_SUBJECT_BRUCE).build(); assertFalse(TEAM_DESC_ALFRED.equals(editedAlfred)); // different score -> returns false editedAlfred = new EditTeamDescriptorBuilder(TEAM_DESC_ALFRED).withScore(VALID_SCORE_BRUCE).build(); assertFalse(TEAM_DESC_ALFRED.equals(editedAlfred)); // different project name -> returns false editedAlfred = new EditTeamDescriptorBuilder(TEAM_DESC_ALFRED) .withProjectName(VALID_PROJECT_NAME_BRUCE).build(); assertFalse(TEAM_DESC_ALFRED.equals(editedAlfred)); // different location -> returns false editedAlfred = new EditTeamDescriptorBuilder(TEAM_DESC_ALFRED) .withLocation(VALID_LOCATION_BRUCE).build(); assertFalse(TEAM_DESC_ALFRED.equals(editedAlfred)); } }
43.784615
112
0.762474
996300b107516542cdf6177979d34477ab3af3f1
3,996
package seedu.intern.commons.core.selection; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.intern.testutil.Assert.assertThrows; import org.junit.jupiter.api.Test; public class SelectionTest { @Test public void createAllSelection() { Selection selection = Selection.fromAllFlag(); // check no Index assertFalse(selection.hasIndex()); assertThrows(NullPointerException.class, selection::getIndexOneBased); assertThrows(NullPointerException.class, selection::getIndexZeroBased); // check All flag present assertTrue(selection.hasAllSelectFlag()); assertTrue(selection.checkAllSelected()); } @Test public void createOneBasedSelection() { // invalid selection assertThrows(IndexOutOfBoundsException.class, () -> Selection.fromIndex(Index.fromOneBased(0))); // check equality using the same base assertEquals(1, Selection.fromIndex(Index.fromOneBased(1)).getIndexOneBased()); assertEquals(5, Selection.fromIndex(Index.fromOneBased(5)).getIndexOneBased()); // convert from one-based selection to zero-based selection assertEquals(0, Selection.fromIndex(Index.fromOneBased(1)).getIndexZeroBased()); assertEquals(4, Selection.fromIndex(Index.fromOneBased(5)).getIndexZeroBased()); // Check All flag not present assertFalse(Selection.fromIndex(Index.fromOneBased(1)).hasAllSelectFlag()); assertThrows(NullPointerException.class, () -> Selection.fromIndex(Index.fromOneBased(1)).checkAllSelected()); } @Test public void createZeroBasedSelection() { // invalid selection assertThrows(IndexOutOfBoundsException.class, () -> Selection.fromIndex(Index.fromOneBased(-1))); // check equality using the same base assertEquals(0, Selection.fromIndex(Index.fromZeroBased(0)).getIndexZeroBased()); assertEquals(5, Selection.fromIndex(Index.fromZeroBased(5)).getIndexZeroBased()); // convert from zero-based selection to one-based selection assertEquals(1, Selection.fromIndex(Index.fromZeroBased(0)).getIndexOneBased()); assertEquals(6, Selection.fromIndex(Index.fromZeroBased(5)).getIndexOneBased()); // Check All flag assertFalse(Selection.fromIndex(Index.fromZeroBased(0)).hasAllSelectFlag()); assertThrows(NullPointerException.class, () -> Selection.fromIndex(Index.fromZeroBased(0)).checkAllSelected()); } @Test public void equals() { final Selection fifthApplicantSelection = Selection.fromIndex(Index.fromOneBased(5)); final Selection allApplicantSelection = Selection.fromAllFlag(); // same values -> returns true assertEquals(Selection.fromIndex(Index.fromOneBased(5)), fifthApplicantSelection); assertEquals(Selection.fromIndex(Index.fromZeroBased(4)), fifthApplicantSelection); // same object -> returns true assertEquals(fifthApplicantSelection, fifthApplicantSelection); // null -> returns false assertNotEquals(fifthApplicantSelection, null); // different types -> returns false assertFalse(fifthApplicantSelection.equals(5.0f)); // different selection -> returns false assertNotEquals(Selection.fromIndex(Index.fromZeroBased(1)), fifthApplicantSelection); // same values -> returns true assertEquals(Selection.fromAllFlag(), allApplicantSelection); // same object -> returns true assertEquals(allApplicantSelection, allApplicantSelection); // null -> returns false assertNotEquals(allApplicantSelection, null); // different types -> returns false assertNotEquals(allApplicantSelection, Boolean.TRUE); } }
41.625
119
0.714965
63f1f58511315e192aa1c735b2ff2c6b84bb287b
692
package org.advanze.springframework.security.provisioning; import org.advanze.springframework.security.provisioning.domain.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.validation.BindException; public interface UserManager extends UserDetailsService { void createUser(User user) throws BindException; void updateUser(User user) throws BindException; void deleteUser(String username) throws BindException; boolean userExists(String username); void changePassword(String oldPassword, String newPassword); void changePasswordNoAuthentication(String username, String oldPassword, String newPassword); }
32.952381
97
0.823699
7ea803a4b26aca0dba81a6090b30a8e4eaf22cca
16,715
package com.zebra.scannercontrol.app.activities; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.util.Xml; import android.view.Menu; import android.view.View; import android.widget.CheckedTextView; import android.widget.Toast; import com.zebra.scannercontrol.DCSSDKDefs; import com.zebra.scannercontrol.app.R; import com.zebra.scannercontrol.RMDAttributes; import com.zebra.scannercontrol.app.application.Application; import com.zebra.scannercontrol.app.helpers.Constants; import com.zebra.scannercontrol.app.helpers.CustomProgressDialog; import org.xmlpull.v1.XmlPullParser; import java.io.StringReader; import static com.zebra.scannercontrol.RMDAttributes.*; public class BeeperSettingsActivity extends BaseActivity implements View.OnClickListener{ private static final String MSG_FETCH = "Fetching settings"; private boolean settingsFetched; private CustomProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beeper_settings); Configuration configuration = getResources().getConfiguration(); if(configuration.orientation == Configuration.ORIENTATION_LANDSCAPE){ if(configuration.smallestScreenWidthDp<Application.minScreenWidth){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } }else{ if(configuration.screenWidthDp<Application.minScreenWidth){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } findViewById(R.id.lowVolume).setOnClickListener(this); findViewById(R.id.mediumVolume).setOnClickListener(this); findViewById(R.id.highVolume).setOnClickListener(this); findViewById(R.id.lowFrequency).setOnClickListener(this); findViewById(R.id.mediumFrequency).setOnClickListener(this); findViewById(R.id.highFrequency).setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.no_items, menu); return true; } @Override protected void onResume() { super.onResume(); fetchBeeperSettings(); } private void fetchBeeperSettings() { int scannerID = getIntent().getIntExtra(Constants.SCANNER_ID, -1); if (scannerID != -1) { String inXML = "<inArgs><scannerID>" + scannerID + "</scannerID><cmdArgs><arg-xml><attrib_list>" + RMD_ATTR_BEEPER_VOLUME + "," + RMDAttributes.RMD_ATTR_BEEPER_FREQUENCY + "</attrib_list></arg-xml></cmdArgs></inArgs>"; new MyAsyncTask(scannerID, DCSSDKDefs.DCSSDK_COMMAND_OPCODE.DCSSDK_RSM_ATTR_GET).execute(new String[]{inXML}); } else { Toast.makeText(this, Constants.INVALID_SCANNER_ID_MSG, Toast.LENGTH_SHORT).show(); } } private void performBeeperSettings(String inXML) { int scannerID = getIntent().getIntExtra(Constants.SCANNER_ID, -1); if (scannerID != -1) { new MyAsyncTask(scannerID, DCSSDKDefs.DCSSDK_COMMAND_OPCODE.DCSSDK_RSM_ATTR_SET).execute(new String[]{inXML}); } } private void prepareInXML(int attribID, int attribValue){ if(settingsFetched) { String inXML = "<inArgs><scannerID>" + getIntent().getIntExtra(Constants.SCANNER_ID, -1) + "</scannerID><cmdArgs><arg-xml><attrib_list><attribute><id>" + attribID + "</id><datatype>B</datatype><value>" + attribValue + "</value></attribute></attrib_list></arg-xml></cmdArgs></inArgs>"; performBeeperSettings(inXML); }else{ Toast.makeText(this, "Beeper settings have not been retrieved. Action will not be performed", Toast.LENGTH_SHORT).show(); } } @Override public void onClick(View view) { if(((CheckedTextView)view).isChecked()){ Toast.makeText(this, "Already Active!!", Toast.LENGTH_SHORT).show(); }else{ int attribId = -1; int attribValue = -1; if(view == findViewById(R.id.lowVolume)){ ((CheckedTextView)findViewById(R.id.mediumVolume)).setChecked(false); ((CheckedTextView)findViewById(R.id.highVolume)).setChecked(false); ((CheckedTextView)findViewById(R.id.lowVolume)).setChecked(true); attribId = RMD_ATTR_BEEPER_VOLUME; attribValue = RMD_ATTR_VALUE_BEEPER_VOLUME_LOW; }else if(view == findViewById(R.id.mediumVolume)){ ((CheckedTextView)findViewById(R.id.lowVolume)).setChecked(false); ((CheckedTextView)findViewById(R.id.highVolume)).setChecked(false); ((CheckedTextView)findViewById(R.id.mediumVolume)).setChecked(true); attribId = RMD_ATTR_BEEPER_VOLUME; attribValue = RMD_ATTR_VALUE_BEEPER_VOLUME_MEDIUM; }else if(view == findViewById(R.id.highVolume)){ ((CheckedTextView)findViewById(R.id.mediumVolume)).setChecked(false); ((CheckedTextView)findViewById(R.id.lowVolume)).setChecked(false); ((CheckedTextView)findViewById(R.id.highVolume)).setChecked(true); attribId = RMD_ATTR_BEEPER_VOLUME; attribValue = RMD_ATTR_VALUE_BEEPER_VOLUME_HIGH; }else if(view == findViewById(R.id.lowFrequency)){ ((CheckedTextView)findViewById(R.id.mediumFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.highFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.lowFrequency)).setChecked(true); attribId = RMDAttributes.RMD_ATTR_BEEPER_FREQUENCY; attribValue = RMD_ATTR_VALUE_BEEPER_FREQ_LOW; }else if(view == findViewById(R.id.mediumFrequency)){ ((CheckedTextView)findViewById(R.id.highFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.lowFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.mediumFrequency)).setChecked(true); attribId = RMDAttributes.RMD_ATTR_BEEPER_FREQUENCY; attribValue = RMD_ATTR_VALUE_BEEPER_FREQ_MEDIUM; }else if(view == findViewById(R.id.highFrequency)){ ((CheckedTextView)findViewById(R.id.mediumFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.lowFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.highFrequency)).setChecked(true); attribId = RMDAttributes.RMD_ATTR_BEEPER_FREQUENCY; attribValue = RMD_ATTR_VALUE_BEEPER_FREQ_HIGH; } if(attribId != -1) prepareInXML(attribId, attribValue); } } /*RHBJ36:Issue reported from IOS.SSDK-3471. *Change for fix for crashing when scanning barcode while fetching Beeper settings. *Dialog is dismisses after Activity finished. Added check to confirm if the activity is not in Finishing state *before cancelling the dialog. */ private void dismissDailog(){ if (progressDialog != null && progressDialog.isShowing()&&!this.isFinishing()) progressDialog.cancel(); } private class MyAsyncTask extends AsyncTask<String,Integer,Boolean>{ int scannerId; DCSSDKDefs.DCSSDK_COMMAND_OPCODE opcode; public MyAsyncTask(int scannerId, DCSSDKDefs.DCSSDK_COMMAND_OPCODE opcode){ this.scannerId=scannerId; this.opcode=opcode; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new CustomProgressDialog(BeeperSettingsActivity.this, "Execute Command..."); progressDialog.show(); } @Override protected Boolean doInBackground(String... strings) { StringBuilder sb = new StringBuilder() ; boolean result = executeCommand(opcode, strings[0], sb, scannerId); if (opcode == DCSSDKDefs.DCSSDK_COMMAND_OPCODE.DCSSDK_RSM_ATTR_GET) { if (result) { try { Log.i(TAG, sb.toString()); int i = 0; int attrId = -1; int attrVal; XmlPullParser parser = Xml.newPullParser(); parser.setInput(new StringReader(sb.toString())); int event = parser.getEventType(); String text = null; while (event != XmlPullParser.END_DOCUMENT) { String name = parser.getName(); switch (event) { case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = parser.getText(); break; case XmlPullParser.END_TAG: Log.i(TAG,"Name of the end tag: "+name); if (name.equals("id")) { attrId = Integer.parseInt(text != null ? text.trim() : null); Log.i(TAG,"ID tag found: ID: "+attrId); } else if (name.equals("value")) { settingsFetched = true; attrVal = Integer.parseInt(text != null ? text.trim() : null); Log.i(TAG,"Value tag found: Value: "+attrVal); if (RMD_ATTR_BEEPER_VOLUME == attrId) { if (RMD_ATTR_VALUE_BEEPER_VOLUME_LOW == attrVal) { Log.i(TAG,"RMD_ATTR_BEEPER_VOLUME = RMD_ATTR_VALUE_BEEPER_VOLUME_LOW"); runOnUiThread(new Runnable() { @Override public void run() { ((CheckedTextView) findViewById(R.id.lowVolume)).setChecked(true); ((CheckedTextView) findViewById(R.id.mediumVolume)).setChecked(false); ((CheckedTextView) findViewById(R.id.highVolume)).setChecked(false); } }); }else if (RMD_ATTR_VALUE_BEEPER_VOLUME_MEDIUM == attrVal) { Log.i(TAG,"RMD_ATTR_BEEPER_VOLUME = RMD_ATTR_VALUE_BEEPER_VOLUME_MEDIUM"); runOnUiThread(new Runnable() { @Override public void run() { ((CheckedTextView) findViewById(R.id.mediumVolume)).setChecked(true); ((CheckedTextView) findViewById(R.id.lowVolume)).setChecked(false); ((CheckedTextView) findViewById(R.id.highVolume)).setChecked(false); } }); } else if (RMD_ATTR_VALUE_BEEPER_VOLUME_HIGH == attrVal) { Log.i(TAG,"RMD_ATTR_BEEPER_VOLUME = RMD_ATTR_VALUE_BEEPER_VOLUME_HIGH"); runOnUiThread(new Runnable() { @Override public void run() { ((CheckedTextView) findViewById(R.id.highVolume)).setChecked(true); ((CheckedTextView) findViewById(R.id.lowVolume)).setChecked(false); ((CheckedTextView) findViewById(R.id.mediumVolume)).setChecked(false); } }); } } else if (RMD_ATTR_BEEPER_FREQUENCY == attrId) { if (RMD_ATTR_VALUE_BEEPER_FREQ_LOW == attrVal) { Log.i(TAG,"RMD_ATTR_BEEPER_FREQUENCY = RMD_ATTR_VALUE_BEEPER_FREQ_LOW"); runOnUiThread(new Runnable() { @Override public void run() { ((CheckedTextView)findViewById(R.id.lowFrequency)).setChecked(true); ((CheckedTextView)findViewById(R.id.mediumFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.highFrequency)).setChecked(false); } }); } else if (RMD_ATTR_VALUE_BEEPER_FREQ_MEDIUM == attrVal) { Log.i(TAG,"RMD_ATTR_BEEPER_FREQUENCY = RMD_ATTR_VALUE_BEEPER_FREQ_MEDIUM"); runOnUiThread(new Runnable() { @Override public void run() { ((CheckedTextView)findViewById(R.id.mediumFrequency)).setChecked(true); ((CheckedTextView)findViewById(R.id.lowFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.highFrequency)).setChecked(false); } }); } else if (RMD_ATTR_VALUE_BEEPER_FREQ_HIGH == attrVal) { Log.i(TAG,"RMD_ATTR_BEEPER_FREQUENCY = RMD_ATTR_VALUE_BEEPER_FREQ_HIGH"); runOnUiThread(new Runnable() { @Override public void run() { ((CheckedTextView)findViewById(R.id.highFrequency)).setChecked(true); ((CheckedTextView)findViewById(R.id.mediumFrequency)).setChecked(false); ((CheckedTextView)findViewById(R.id.lowFrequency)).setChecked(false); } }); } } } break; } event = parser.next(); } } catch (Exception e) { Log.e(TAG,e.toString()); } } } return result; } @Override protected void onPostExecute(Boolean b) { super.onPostExecute(b); dismissDailog(); if(!b){ if(opcode==DCSSDKDefs.DCSSDK_COMMAND_OPCODE.DCSSDK_RSM_ATTR_GET) Toast.makeText(BeeperSettingsActivity.this, "Unable to fetch beeper settings", Toast.LENGTH_SHORT).show(); else if(opcode==DCSSDKDefs.DCSSDK_COMMAND_OPCODE.DCSSDK_RSM_ATTR_SET){ Toast.makeText(BeeperSettingsActivity.this, "Cannot perform the action", Toast.LENGTH_SHORT).show(); } } } } }
54.983553
165
0.515884
cc28462a8bfc6e8771f90f7c97eff8db3cec3fb5
1,797
package com.akkademy; import static org.junit.Assert.assertEquals; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.Status; import akka.testkit.TestActorRef; import akka.testkit.TestProbe; import com.akkademy.messages.SetRequest; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; import java.util.Arrays; import java.util.List; public class AkkademyDbTest { ActorSystem system = ActorSystem.create("system", ConfigFactory.empty()); //Ignore the config for remoting @Test public void itShouldPlaceKeyValueFromSetMessageIntoMap() { TestProbe testProbe = TestProbe.apply(system); TestActorRef<AkkademyDb> actorRef = TestActorRef.create(system, Props.create(AkkademyDb.class)); AkkademyDb akkademyDb = actorRef.underlyingActor(); actorRef.tell(new SetRequest("key", "value", testProbe.ref()), ActorRef.noSender()); assertEquals(akkademyDb.map.get("key"), "value"); } @Test public void itShouldPlaceKeyValuesFromListOfSetMessageIntoMap() { TestProbe testProbe = TestProbe.apply(system); TestActorRef<AkkademyDb> actorRef = TestActorRef.create(system, Props.create(AkkademyDb.class)); AkkademyDb akkademyDb = actorRef.underlyingActor(); List list = Arrays.asList( new SetRequest("key2", "value2", testProbe.ref()), new SetRequest("key3", "value3", testProbe.ref())); actorRef.tell(list, ActorRef.noSender()); assertEquals(akkademyDb.map.get("key2"), "value2"); assertEquals(akkademyDb.map.get("key3"), "value3"); testProbe.expectMsg(new Status.Success("key2")); testProbe.expectMsg(new Status.Success("key3")); } }
33.90566
110
0.711185
b2667497c3fe3ce08be43b96306788ee43d7470c
1,156
package de.stormboomer.chunky.plugin.models; import javafx.scene.shape.Arc; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.software.os.OperatingSystem; public class CPU{ public int LogicalCoreCount; public int PhysicalCoreCount; public int SocketCount; public long MaxFreq; public String Name; public String Vendor; public String Architecture; public long VendorFreq; public String ProcessorID; public CPU(SystemInfo systemInfo){ CentralProcessor processor = systemInfo.getHardware().getProcessor(); CentralProcessor.ProcessorIdentifier processorID = processor.getProcessorIdentifier(); LogicalCoreCount = processor.getLogicalProcessorCount(); PhysicalCoreCount = processor.getPhysicalProcessorCount(); SocketCount = processor.getPhysicalPackageCount(); MaxFreq = processor.getMaxFreq(); Name = processorID.getName(); Vendor = processorID.getVendor(); Architecture = processorID.getMicroarchitecture(); VendorFreq = processorID.getVendorFreq(); ProcessorID = processorID.getProcessorID(); } }
35.030303
94
0.734429
994106860417aa8159948cf255a65620fede7c02
1,233
package mage.abilities.keyword; import mage.abilities.ActivatedAbilityImpl; import mage.abilities.costs.Cost; import mage.abilities.effects.common.AttachEffect; import mage.constants.Outcome; import mage.constants.TimingRule; import mage.constants.Zone; import mage.filter.common.FilterControlledCreaturePermanent; import mage.target.common.TargetControlledCreaturePermanent; /** * @author TheElk801 */ public class EquipFilterAbility extends ActivatedAbilityImpl { private final FilterControlledCreaturePermanent filter; public EquipFilterAbility(FilterControlledCreaturePermanent filter, Cost cost) { super(Zone.BATTLEFIELD, new AttachEffect(Outcome.AddAbility, "Equip"), cost); this.addTarget(new TargetControlledCreaturePermanent(filter)); this.filter = filter; this.timing = TimingRule.SORCERY; } private EquipFilterAbility(final EquipFilterAbility ability) { super(ability); this.filter = ability.filter; } @Override public EquipFilterAbility copy() { return new EquipFilterAbility(this); } @Override public String getRule() { return "Equip " + filter.getMessage() + costs.getText() + manaCosts.getText(); } }
30.073171
86
0.743715
5a1416009e9e52ea38c0a61d3a8cda390eb88ac0
22,801
/** * Copyright © Microsoft Open Technologies, Inc. * * 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 * * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. * * See the Apache License, Version 2.0 for the specific language * governing permissions and limitations under the License. */ package com.msopentech.odatajclient.proxy.api.impl; import com.msopentech.odatajclient.engine.communication.request.retrieve.ODataMediaRequest; import com.msopentech.odatajclient.engine.communication.request.retrieve.ODataRetrieveRequestFactory; import com.msopentech.odatajclient.engine.communication.response.ODataRetrieveResponse; import com.msopentech.odatajclient.engine.data.ODataEntity; import com.msopentech.odatajclient.engine.data.ODataInlineEntity; import com.msopentech.odatajclient.engine.data.ODataInlineEntitySet; import com.msopentech.odatajclient.engine.data.ODataLink; import com.msopentech.odatajclient.engine.data.ODataOperation; import com.msopentech.odatajclient.engine.data.ODataProperty; import com.msopentech.odatajclient.engine.data.metadata.EdmMetadata; import com.msopentech.odatajclient.engine.data.metadata.edm.Association; import com.msopentech.odatajclient.engine.data.metadata.edm.AssociationSet; import com.msopentech.odatajclient.engine.data.metadata.edm.EntityContainer; import com.msopentech.odatajclient.engine.data.metadata.edm.Schema; import com.msopentech.odatajclient.engine.format.ODataMediaFormat; import com.msopentech.odatajclient.engine.utils.URIUtils; import com.msopentech.odatajclient.proxy.api.AbstractEntityCollection; import com.msopentech.odatajclient.proxy.api.context.AttachedEntityStatus; import com.msopentech.odatajclient.proxy.api.EntityContainerFactory; import com.msopentech.odatajclient.proxy.api.context.EntityContext; import com.msopentech.odatajclient.proxy.api.annotations.EntityType; import com.msopentech.odatajclient.proxy.api.annotations.FunctionImport; import com.msopentech.odatajclient.proxy.api.annotations.NavigationProperty; import com.msopentech.odatajclient.proxy.api.annotations.Property; import com.msopentech.odatajclient.proxy.api.context.EntityUUID; import com.msopentech.odatajclient.proxy.utils.ClassUtils; import com.msopentech.odatajclient.proxy.utils.EngineUtils; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; public class EntityTypeInvocationHandler extends AbstractInvocationHandler { private static final long serialVersionUID = 2629912294765040037L; private final String entityContainerName; private ODataEntity entity; private final Class<?> typeRef; private Map<String, Object> propertyChanges = new HashMap<String, Object>(); private Map<String, InputStream> streamedPropertyChanges = new HashMap<String, InputStream>(); private Map<NavigationProperty, Object> linkChanges = new HashMap<NavigationProperty, Object>(); private InputStream stream; private EntityUUID uuid; private final EntityContext entityContext = EntityContainerFactory.getContext().entityContext(); private int propertiesTag; private int linksTag; static EntityTypeInvocationHandler getInstance( final ODataEntity entity, final EntitySetInvocationHandler entitySet, final Class<?> typeRef) { return getInstance( entity, entitySet.containerHandler.getEntityContainerName(), entitySet.getEntitySetName(), typeRef, entitySet.containerHandler); } static EntityTypeInvocationHandler getInstance( final ODataEntity entity, final String entityContainerName, final String entitySetName, final Class<?> typeRef, final EntityContainerInvocationHandler containerHandler) { return new EntityTypeInvocationHandler(entity, entityContainerName, entitySetName, typeRef, containerHandler); } private EntityTypeInvocationHandler( final ODataEntity entity, final String entityContainerName, final String entitySetName, final Class<?> typeRef, final EntityContainerInvocationHandler containerHandler) { super(containerHandler); this.entityContainerName = entityContainerName; this.typeRef = typeRef; this.entity = entity; this.entity.setMediaEntity(typeRef.getAnnotation(EntityType.class).hasStream()); this.uuid = new EntityUUID( ClassUtils.getNamespace(typeRef), entityContainerName, entitySetName, entity.getName(), EngineUtils.getKey(containerHandler.getFactory().getMetadata(), typeRef, entity)); this.stream = null; this.propertiesTag = 0; this.linksTag = 0; } public void setEntity(final ODataEntity entity) { this.entity = entity; this.entity.setMediaEntity(typeRef.getAnnotation(EntityType.class).hasStream()); this.uuid = new EntityUUID( getUUID().getSchemaName(), getUUID().getContainerName(), getUUID().getEntitySetName(), getUUID().getName(), EngineUtils.getKey(containerHandler.getFactory().getMetadata(), typeRef, entity)); this.propertyChanges.clear(); this.linkChanges.clear(); this.streamedPropertyChanges.clear(); this.propertiesTag = 0; this.linksTag = 0; this.stream = null; } public EntityUUID getUUID() { return uuid; } public String getName() { return this.entity.getName(); } public String getEntityContainerName() { return uuid.getContainerName(); } public String getEntitySetName() { return uuid.getEntitySetName(); } public Class<?> getTypeRef() { return typeRef; } public ODataEntity getEntity() { return entity; } public Map<String, Object> getPropertyChanges() { return propertyChanges; } public Map<NavigationProperty, Object> getLinkChanges() { return linkChanges; } /** * Gets the current ETag defined into the wrapped entity. * * @return */ public String getETag() { return this.entity.getETag(); } /** * Overrides ETag value defined into the wrapped entity. * * @param eTag ETag. */ public void setETag(final String eTag) { this.entity.setETag(eTag); } @Override @SuppressWarnings("unchecked") public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final Annotation[] methodAnnots = method.getAnnotations(); if (isSelfMethod(method, args)) { return invokeSelfMethod(method, args); } else if (!ArrayUtils.isEmpty(methodAnnots) && methodAnnots[0] instanceof FunctionImport) { final ODataOperation operation = this.entity.getOperation(((FunctionImport) methodAnnots[0]).name()); if (operation == null) { throw new IllegalArgumentException( "Could not find any FunctionImport named " + ((FunctionImport) methodAnnots[0]).name()); } final com.msopentech.odatajclient.engine.data.metadata.edm.EntityContainer container = containerHandler.getFactory().getMetadata().getSchema(ClassUtils.getNamespace(typeRef)). getEntityContainer(entityContainerName); final com.msopentech.odatajclient.engine.data.metadata.edm.FunctionImport funcImp = container.getFunctionImport(((FunctionImport) methodAnnots[0]).name()); return functionImport((FunctionImport) methodAnnots[0], method, args, operation.getTarget(), funcImp); } // Assumption: for each getter will always exist a setter and viceversa. else if (method.getName().startsWith("get")) { // get method annotation and check if it exists as expected final Object res; final Method getter = typeRef.getMethod(method.getName()); final Property property = ClassUtils.getAnnotation(Property.class, getter); if (property == null) { final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter); if (navProp == null) { throw new UnsupportedOperationException("Unsupported method " + method.getName()); } else { // if the getter refers to a navigation property ... navigate and follow link if necessary res = getNavigationPropertyValue(navProp, getter); } } else { // if the getter refers to a property .... get property from wrapped entity res = getPropertyValue(property, getter.getGenericReturnType()); } // attach the current handler attach(); return res; } else if (method.getName().startsWith("set")) { // get the corresponding getter method (see assumption above) final String getterName = method.getName().replaceFirst("set", "get"); final Method getter = typeRef.getMethod(getterName); final Property property = ClassUtils.getAnnotation(Property.class, getter); if (property == null) { final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter); if (navProp == null) { throw new UnsupportedOperationException("Unsupported method " + method.getName()); } else { // if the getter refers to a navigation property ... if (ArrayUtils.isEmpty(args) || args.length != 1) { throw new IllegalArgumentException("Invalid argument"); } setNavigationPropertyValue(navProp, args[0]); } } else { setPropertyValue(property, args[0]); } return ClassUtils.returnVoid(); } else { throw new UnsupportedOperationException("Method not found: " + method); } } private Object getNavigationPropertyValue(final NavigationProperty property, final Method getter) { final Class<?> type = getter.getReturnType(); final Class<?> collItemType; if (AbstractEntityCollection.class.isAssignableFrom(type)) { final Type[] entityCollectionParams = ((ParameterizedType) type.getGenericInterfaces()[0]).getActualTypeArguments(); collItemType = (Class<?>) entityCollectionParams[0]; } else { collItemType = type; } final EdmMetadata metadata = containerHandler.getFactory().getMetadata(); final Schema schema = metadata.getSchema(ClassUtils.getNamespace(typeRef)); // 1) get association final Association association = EngineUtils.getAssociation(schema, property.relationship()); // 2) get entity container and association set final Map.Entry<EntityContainer, AssociationSet> associationSet = EngineUtils.getAssociationSet(association, schema.getNamespace(), metadata); // 3) get entitySet final String targetEntitySetName = EngineUtils.getEntitySetName(associationSet.getValue(), property.toRole()); final Object navPropValue; if (linkChanges.containsKey(property)) { navPropValue = linkChanges.get(property); } else { final ODataLink link = EngineUtils.getNavigationLink(property.name(), entity); if (link instanceof ODataInlineEntity) { // return entity navPropValue = getEntityProxy( ((ODataInlineEntity) link).getEntity(), associationSet.getKey().getName(), targetEntitySetName, type, false); } else if (link instanceof ODataInlineEntitySet) { // return entity set navPropValue = getEntityCollection( collItemType, type, associationSet.getKey().getName(), ((ODataInlineEntitySet) link).getEntitySet(), link.getLink(), false); } else { // navigate final URI uri = URIUtils.getURI( containerHandler.getFactory().getServiceRoot(), link.getLink().toASCIIString()); if (AbstractEntityCollection.class.isAssignableFrom(type)) { navPropValue = getEntityCollection( collItemType, type, associationSet.getKey().getName(), ODataRetrieveRequestFactory.getEntitySetRequest(uri).execute().getBody(), uri, true); } else { final ODataRetrieveResponse<ODataEntity> res = ODataRetrieveRequestFactory.getEntityRequest(uri).execute(); navPropValue = getEntityProxy( res.getBody(), associationSet.getKey().getName(), targetEntitySetName, type, res.getEtag(), true); } } if (navPropValue != null) { int checkpoint = linkChanges.hashCode(); linkChanges.put(property, navPropValue); updateLinksTag(checkpoint); } } return navPropValue; } private Object getPropertyValue(final String name, final Type type) { try { final Object res; if (propertyChanges.containsKey(name)) { res = propertyChanges.get(name); } else { res = type == null ? EngineUtils.getValueFromProperty( containerHandler.getFactory().getMetadata(), entity.getProperty(name)) : EngineUtils.getValueFromProperty( containerHandler.getFactory().getMetadata(), entity.getProperty(name), type); if (res != null) { int checkpoint = propertyChanges.hashCode(); propertyChanges.put(name, res); updatePropertiesTag(checkpoint); } } return res; } catch (Exception e) { throw new IllegalArgumentException("Error getting value for property '" + name + "'", e); } } private Object getPropertyValue(final Property property, final Type type) { if (!(type instanceof ParameterizedType) && (Class<?>) type == InputStream.class) { return getStreamedProperty(property); } else { return getPropertyValue(property.name(), type); } } public Object getAdditionalProperty(final String name) { return getPropertyValue(name, null); } public Collection<String> getAdditionalPropertyNames() { final Set<String> res = new HashSet<String>(propertyChanges.keySet()); final Set<String> propertyNames = new HashSet<String>(); for (Method method : typeRef.getMethods()) { final Annotation ann = method.getAnnotation(Property.class); if (ann != null) { final String property = ((Property) ann).name(); propertyNames.add(property); // maybe someone could add a normal attribute to the additional set res.remove(property); } } for (ODataProperty property : entity.getProperties()) { if (!propertyNames.contains(property.getName())) { res.add(property.getName()); } } return res; } private void setNavigationPropertyValue(final NavigationProperty property, final Object value) { // 1) attach source entity attach(AttachedEntityStatus.CHANGED, false); // 2) attach the target entity handlers for (Object link : AbstractEntityCollection.class.isAssignableFrom(value.getClass()) ? (AbstractEntityCollection) value : Collections.singleton(value)) { final InvocationHandler etih = Proxy.getInvocationHandler(link); if (!(etih instanceof EntityTypeInvocationHandler)) { throw new IllegalArgumentException("Invalid argument type"); } final EntityTypeInvocationHandler handler = (EntityTypeInvocationHandler) etih; if (!handler.getTypeRef().isAnnotationPresent(EntityType.class)) { throw new IllegalArgumentException( "Invalid argument type " + handler.getTypeRef().getSimpleName()); } if (!entityContext.isAttached(handler)) { entityContext.attach(handler, AttachedEntityStatus.LINKED); } } // 3) add links linkChanges.put(property, value); } private void setPropertyValue(final Property property, final Object value) { if (property.type().equalsIgnoreCase("Edm.Stream")) { setStreamedProperty(property, (InputStream) value); } else { propertyChanges.put(property.name(), value); } attach(AttachedEntityStatus.CHANGED); } public void addAdditionalProperty(final String name, final Object value) { propertyChanges.put(name, value); attach(AttachedEntityStatus.CHANGED); } private void updatePropertiesTag(final int checkpoint) { if (checkpoint == propertiesTag) { propertiesTag = propertyChanges.hashCode(); } } private void updateLinksTag(final int checkpoint) { if (checkpoint == linksTag) { linksTag = linkChanges.hashCode(); } } public boolean isChanged() { return this.linkChanges.hashCode() != this.linksTag || this.propertyChanges.hashCode() != this.propertiesTag || this.stream != null || !this.streamedPropertyChanges.isEmpty(); } public void setStream(final InputStream stream) { if (typeRef.getAnnotation(EntityType.class).hasStream()) { IOUtils.closeQuietly(this.stream); this.stream = stream; attach(AttachedEntityStatus.CHANGED); } } public InputStream getStreamChanges() { return this.stream; } public Map<String, InputStream> getStreamedPropertyChanges() { return streamedPropertyChanges; } public InputStream getStream() { final String contentSource = entity.getMediaContentSource(); if (this.stream == null && typeRef.getAnnotation(EntityType.class).hasStream() && StringUtils.isNotBlank(contentSource)) { final String comntentType = StringUtils.isBlank(entity.getMediaContentType()) ? "*/*" : entity.getMediaContentType(); final URI contentSourceURI = URIUtils.getURI(containerHandler.getFactory().getServiceRoot(), contentSource); final ODataMediaRequest retrieveReq = ODataRetrieveRequestFactory.getMediaRequest(contentSourceURI); retrieveReq.setFormat(ODataMediaFormat.fromFormat(comntentType)); this.stream = retrieveReq.execute().getBody(); } return this.stream; } public Object getStreamedProperty(final Property property) { InputStream res = streamedPropertyChanges.get(property.name()); try { if (res == null) { final URI link = URIUtils.getURI( containerHandler.getFactory().getServiceRoot(), EngineUtils.getEditMediaLink(property.name(), this.entity).toASCIIString()); final ODataMediaRequest req = ODataRetrieveRequestFactory.getMediaRequest(link); res = req.execute().getBody(); } } catch (Exception e) { res = null; } return res; } private void setStreamedProperty(final Property property, final InputStream input) { final Object obj = propertyChanges.get(property.name()); if (obj != null && obj instanceof InputStream) { IOUtils.closeQuietly((InputStream) obj); } streamedPropertyChanges.put(property.name(), input); } private void attach() { if (!entityContext.isAttached(this)) { entityContext.attach(this, AttachedEntityStatus.ATTACHED); } } private void attach(final AttachedEntityStatus status) { attach(status, true); } private void attach(final AttachedEntityStatus status, final boolean override) { if (entityContext.isAttached(this)) { if (override) { entityContext.setStatus(this, status); } } else { entityContext.attach(this, status); } } @Override public String toString() { return uuid.toString(); } @Override public int hashCode() { return uuid.hashCode(); } @Override public boolean equals(final Object obj) { return obj instanceof EntityTypeInvocationHandler && ((EntityTypeInvocationHandler) obj).getUUID().equals(uuid); } }
38.065109
120
0.62835
525d96e17a7e1b119c5ce9cb64da25f843d99e05
5,383
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.conf.layers; import lombok.*; import org.deeplearning4j.nn.api.Layer; import org.deeplearning4j.nn.api.ParamInitializer; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.inputs.InputType; import org.deeplearning4j.nn.conf.memory.LayerMemoryReport; import org.deeplearning4j.nn.conf.memory.MemoryReport; import org.deeplearning4j.nn.params.PretrainParamInitializer; import org.deeplearning4j.optimize.api.TrainingListener; import org.nd4j.linalg.api.ndarray.INDArray; import java.util.Collection; import java.util.Map; /** * Autoencoder layer. * Adds noise to input and learn a reconstruction function. * */ @Data @NoArgsConstructor @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class AutoEncoder extends BasePretrainNetwork { protected double corruptionLevel; protected double sparsity; // Builder private AutoEncoder(Builder builder) { super(builder); this.corruptionLevel = builder.corruptionLevel; this.sparsity = builder.sparsity; initializeConstraints(builder); } @Override public Layer instantiate(NeuralNetConfiguration conf, Collection<TrainingListener> trainingListeners, int layerIndex, INDArray layerParamsView, boolean initializeParams) { org.deeplearning4j.nn.layers.feedforward.autoencoder.AutoEncoder ret = new org.deeplearning4j.nn.layers.feedforward.autoencoder.AutoEncoder(conf); ret.setListeners(trainingListeners); ret.setIndex(layerIndex); ret.setParamsViewArray(layerParamsView); Map<String, INDArray> paramTable = initializer().init(conf, layerParamsView, initializeParams); ret.setParamTable(paramTable); ret.setConf(conf); return ret; } @Override public ParamInitializer initializer() { return PretrainParamInitializer.getInstance(); } @Override public LayerMemoryReport getMemoryReport(InputType inputType) { //Because of supervised + unsupervised modes: we'll assume unsupervised, which has the larger memory requirements InputType outputType = getOutputType(-1, inputType); val actElementsPerEx = outputType.arrayElementsPerExample() + inputType.arrayElementsPerExample(); val numParams = initializer().numParams(this); val updaterStateSize = (int) getIUpdater().stateSize(numParams); int trainSizePerEx = 0; if (getIDropout() != null) { if (false) { //TODO drop connect //Dup the weights... note that this does NOT depend on the minibatch size... } else { //Assume we dup the input trainSizePerEx += inputType.arrayElementsPerExample(); } } //Also, during backprop: we do a preOut call -> gives us activations size equal to the output size // which is modified in-place by loss function trainSizePerEx += actElementsPerEx; return new LayerMemoryReport.Builder(layerName, AutoEncoder.class, inputType, outputType) .standardMemory(numParams, updaterStateSize).workingMemory(0, 0, 0, trainSizePerEx) .cacheMemory(MemoryReport.CACHE_MODE_ALL_ZEROS, MemoryReport.CACHE_MODE_ALL_ZEROS) //No caching .build(); } @AllArgsConstructor public static class Builder extends BasePretrainNetwork.Builder<Builder> { private double corruptionLevel = 3e-1f; private double sparsity = 0f; public Builder() {} /** * Builder - sets the level of corruption - 0.0 (none) to 1.0 (all values corrupted) * @param corruptionLevel Corruption level (0 to 1) */ public Builder(double corruptionLevel) { this.corruptionLevel = corruptionLevel; } /** * Level of corruption - 0.0 (none) to 1.0 (all values corrupted) * @param corruptionLevel Corruption level (0 to 1) */ public Builder corruptionLevel(double corruptionLevel) { this.corruptionLevel = corruptionLevel; return this; } /** * Autoencoder sparity parameter * @param sparsity Sparsity */ public Builder sparsity(double sparsity) { this.sparsity = sparsity; return this; } @Override @SuppressWarnings("unchecked") public AutoEncoder build() { return new AutoEncoder(this); } } }
37.643357
121
0.656511
83c4b059e2757abb6727ada97de8c1448f96cbfc
19,329
/* * 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.dubbo.common.threadpool.manager; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionAccessorAware; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_EXPORT_THREAD_NUM; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_REFER_THREAD_NUM; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; /** * Consider implementing {@code Licycle} to enable executors shutdown when the process stops. */ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionAccessorAware, ScopeModelAware { private static final Logger logger = LoggerFactory.getLogger(DefaultExecutorRepository.class); private int DEFAULT_SCHEDULER_SIZE = Runtime.getRuntime().availableProcessors(); private final ExecutorService sharedExecutor; private final ScheduledExecutorService sharedScheduledExecutor; // 此处的ring是一个取用环,用循环的概念不停的取用list里面的数据,重复循环的取用 // 不是一个数据环,对一个大小有限的数据结构,重复不停的循环写入,写到尾部了,再从头部开始写入 private Ring<ScheduledExecutorService> scheduledExecutors = new Ring<>(); private volatile ScheduledExecutorService serviceExportExecutor; private volatile ExecutorService serviceReferExecutor; private ScheduledExecutorService connectivityScheduledExecutor; public Ring<ScheduledExecutorService> registryNotificationExecutorRing = new Ring<>(); private Ring<ScheduledExecutorService> serviceDiscoveryAddressNotificationExecutorRing = new Ring<>(); private ScheduledExecutorService metadataRetryExecutor; private ConcurrentMap<String, ConcurrentMap<Integer, ExecutorService>> data = new ConcurrentHashMap<>(); private ExecutorService poolRouterExecutor; private Ring<ExecutorService> executorServiceRing = new Ring<ExecutorService>(); private final Object LOCK = new Object(); private ExtensionAccessor extensionAccessor; private ApplicationModel applicationModel; public DefaultExecutorRepository() { // 在构建他的时候,会有一个用于共享使用的线程池,NamedThreadFactory是干什么的,用来设定你的这个线程池里的线程的名称的前缀就可以了 sharedExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-shared-handler", true)); // 共享的定时调度的线程池 sharedScheduledExecutor = Executors.newScheduledThreadPool(8, new NamedThreadFactory("Dubbo-shared-scheduler", true)); // 有多少个cpu核,此时就可以做一个cpu核数量的遍历 for (int i = 0; i < DEFAULT_SCHEDULER_SIZE; i++) { // 通过遍历,会创建一个一个的scheduled executor service ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("Dubbo-framework-scheduler-" + i, true)); scheduledExecutors.addItem(scheduler); // router chain里面搞到的线程池,是一个线程数量固定位1的,有队列排队的一个线程池 executorServiceRing.addItem(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), new NamedInternalThreadFactory("Dubbo-state-router-loop-" + i, true) , new ThreadPoolExecutor.AbortPolicy())); } connectivityScheduledExecutor = Executors.newScheduledThreadPool(DEFAULT_SCHEDULER_SIZE, new NamedThreadFactory("Dubbo-connectivity-scheduler", true)); poolRouterExecutor = new ThreadPoolExecutor(1, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), new NamedInternalThreadFactory("Dubbo-state-router-pool-router", true), new ThreadPoolExecutor.AbortPolicy()); for (int i = 0; i < DEFAULT_SCHEDULER_SIZE; i++) { ScheduledExecutorService serviceDiscoveryAddressNotificationExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-SD-address-refresh-" + i)); ScheduledExecutorService registryNotificationExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-registry-notification-" + i)); serviceDiscoveryAddressNotificationExecutorRing.addItem(serviceDiscoveryAddressNotificationExecutor); registryNotificationExecutorRing.addItem(registryNotificationExecutor); } metadataRetryExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-metadata-retry")); } /** * Get called when the server or client instance initiating. * * @param url * @return */ public synchronized ExecutorService createExecutorIfAbsent(URL url) { // data缓存,在某个地方肯定会有一个代码触发,肯定会触发这个方法的执行 Map<Integer, ExecutorService> executors = data.computeIfAbsent(EXECUTOR_SERVICE_COMPONENT_KEY, k -> new ConcurrentHashMap<>()); // Consumer's executor is sharing globally, key=Integer.MAX_VALUE. Provider's executor is sharing by protocol. // 一旦第一次被触发,这里必然会提取出来provider端的端口号,20880 Integer portKey = CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY)) ? Integer.MAX_VALUE : url.getPort(); if (url.getParameter(THREAD_NAME_KEY) == null) { url = url.putAttribute(THREAD_NAME_KEY, "Dubbo-protocol-"+portKey); } URL finalUrl = url; // 把你的20880作为一个key,同时创建出一个线程池出来 ExecutorService executor = executors.computeIfAbsent(portKey, k -> createExecutor(finalUrl)); // If executor has been shut down, create a new one if (executor.isShutdown() || executor.isTerminated()) { executors.remove(portKey); executor = createExecutor(url); executors.put(portKey, executor); } return executor; } public ExecutorService getExecutor(URL url) { // 先拿到一个固定的port->executor线程池之间的缓存 Map<Integer, ExecutorService> executors = data.get(EXECUTOR_SERVICE_COMPONENT_KEY); /** * It's guaranteed that this method is called after {@link #createExecutorIfAbsent(URL)}, so data should already * have Executor instances generated and stored. */ if (executors == null) { logger.warn("No available executors, this is not expected, framework should call createExecutorIfAbsent first " + "before coming to here."); return null; } // Consumer's executor is sharing globally, key=Integer.MAX_VALUE. Provider's executor is sharing by protocol. // 计算一个所谓的port key Integer portKey = CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY)) ? Integer.MAX_VALUE : url.getPort(); ExecutorService executor = executors.get(portKey); if (executor != null && (executor.isShutdown() || executor.isTerminated())) { executors.remove(portKey); // Does not re-create a shutdown executor, use SHARED_EXECUTOR for downgrade. executor = null; logger.info("Executor for " + url + " is shutdown."); } if (executor == null) { return sharedExecutor; } else { return executor; } } @Override public void updateThreadpool(URL url, ExecutorService executor) { try { if (url.hasParameter(THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; int threads = url.getParameter(THREADS_KEY, 0); int max = threadPoolExecutor.getMaximumPoolSize(); int core = threadPoolExecutor.getCorePoolSize(); if (threads > 0 && (threads != max || threads != core)) { if (threads < core) { threadPoolExecutor.setCorePoolSize(threads); if (core == max) { threadPoolExecutor.setMaximumPoolSize(threads); } } else { threadPoolExecutor.setMaximumPoolSize(threads); if (core == max) { threadPoolExecutor.setCorePoolSize(threads); } } } } } catch (Throwable t) { logger.error(t.getMessage(), t); } } @Override // 为什么线程池需要放在类似于ring的取用环,数据环,搞错了,看花眼了 // 你不停的取用,取用,取用,取用的过程中,是在循环不断的取用不同的线程池 public ScheduledExecutorService nextScheduledExecutor() { return scheduledExecutors.pollItem(); } @Override public ExecutorService nextExecutorExecutor() { return executorServiceRing.pollItem(); } @Override public ScheduledExecutorService getServiceExportExecutor() { synchronized (LOCK) { if (serviceExportExecutor == null) { int coreSize = getExportThreadNum(); serviceExportExecutor = Executors.newScheduledThreadPool(coreSize, new NamedThreadFactory("Dubbo-service-export", true)); } } return serviceExportExecutor; } @Override public void shutdownServiceExportExecutor() { synchronized (LOCK) { if (serviceExportExecutor != null && !serviceExportExecutor.isShutdown()) { try { serviceExportExecutor.shutdown(); } catch (Throwable ignored) { // ignored logger.warn(ignored.getMessage(), ignored); } } serviceExportExecutor = null; } } @Override public ExecutorService getServiceReferExecutor() { synchronized (LOCK) { if (serviceReferExecutor == null) { int coreSize = getReferThreadNum(); serviceReferExecutor = Executors.newFixedThreadPool(coreSize, new NamedThreadFactory("Dubbo-service-refer", true)); } } return serviceReferExecutor; } @Override public void shutdownServiceReferExecutor() { synchronized (LOCK) { if (serviceReferExecutor != null && !serviceReferExecutor.isShutdown()) { try { serviceReferExecutor.shutdown(); } catch (Throwable ignored) { logger.warn(ignored.getMessage(), ignored); } } serviceReferExecutor = null; } } private Integer getExportThreadNum() { Integer threadNum = null; ApplicationModel applicationModel = ApplicationModel.ofNullable(this.applicationModel); for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) { threadNum = getExportThreadNum(moduleModel); if (threadNum != null) { break; } } if (threadNum == null) { logger.info("Cannot get config `export-thread-num` from module config, using default: " + DEFAULT_EXPORT_THREAD_NUM); return DEFAULT_EXPORT_THREAD_NUM; } return threadNum; } private Integer getExportThreadNum(ModuleModel moduleModel) { ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElse(null); if (moduleConfig == null) { return null; } Integer threadNum = moduleConfig.getExportThreadNum(); if (threadNum == null) { threadNum = moduleModel.getConfigManager().getProviders() .stream() .map(ProviderConfig::getExportThreadNum) .filter(k -> k != null && k > 0) .findAny().orElse(null); } return threadNum; } private Integer getReferThreadNum() { Integer threadNum = null; ApplicationModel applicationModel = ApplicationModel.ofNullable(this.applicationModel); for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) { threadNum = getReferThreadNum(moduleModel); if (threadNum != null) { break; } } if (threadNum == null) { logger.info("Cannot get config `refer-thread-num` from module config, using default: " + DEFAULT_REFER_THREAD_NUM); return DEFAULT_REFER_THREAD_NUM; } return threadNum; } private Integer getReferThreadNum(ModuleModel moduleModel) { ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElse(null); if (moduleConfig == null) { return null; } Integer threadNum = moduleConfig.getReferThreadNum(); if (threadNum == null) { threadNum = moduleModel.getConfigManager().getConsumers() .stream() .map(ConsumerConfig::getReferThreadNum) .filter(k -> k != null && k > 0) .findAny().orElse(null); } return threadNum; } @Override public ScheduledExecutorService getRegistryNotificationExecutor() { return registryNotificationExecutorRing.pollItem(); } public ScheduledExecutorService getServiceDiscoveryAddressNotificationExecutor() { return serviceDiscoveryAddressNotificationExecutorRing.pollItem(); } @Override public ScheduledExecutorService getMetadataRetryExecutor() { return metadataRetryExecutor; } @Override public ExecutorService getSharedExecutor() { return sharedExecutor; } @Override public ScheduledExecutorService getSharedScheduledExecutor() { return sharedScheduledExecutor; } private ExecutorService createExecutor(URL url) { // 也是用的SPI的机制 // 讲过dubbo的业务线程池,有很多种类型,默认的就是fixed threadpool // 默认是fixed threadpool,adaptive自适应,他其实在真正获取线程池的时候,是会去根据url里的具体的参数来找到对应的实现类 // adaptive,但是可以 看出来默认还是走fixed threadpool,默认的线程数量就是200个 // SPI的adaptive自适应机制 // 还是去生成代理类,代理类的getExecutor方法被调用,在里面必须通过url的参数,提取出来对应的线程池的短名称 // 去找到对应的实现类的,再执行真正的getExecutor方法 return (ExecutorService) extensionAccessor.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url); } @Override public ExecutorService getPoolRouterExecutor() { return poolRouterExecutor; } @Override public ScheduledExecutorService getConnectivityScheduledExecutor() { return connectivityScheduledExecutor; } @Override public void destroyAll() { logger.info("destroying executor repository .."); shutdownExecutorService(poolRouterExecutor, "poolRouterExecutor"); shutdownExecutorService(metadataRetryExecutor, "metadataRetryExecutor"); shutdownServiceExportExecutor(); shutdownServiceReferExecutor(); data.values().forEach(executors -> { if (executors != null) { executors.values().forEach(executor -> { if (executor != null && !executor.isShutdown()) { try { ExecutorUtil.shutdownNow(executor, 100); } catch (Throwable ignored) { // ignored logger.warn(ignored.getMessage(), ignored); } } }); } }); data.clear(); // scheduledExecutors shutdownExecutorServices(scheduledExecutors.listItems(), "scheduledExecutors"); // executorServiceRing shutdownExecutorServices(executorServiceRing.listItems(), "executorServiceRing"); // connectivityScheduledExecutor shutdownExecutorService(connectivityScheduledExecutor, "connectivityScheduledExecutor"); // shutdown share executor shutdownExecutorService(sharedExecutor, "sharedExecutor"); shutdownExecutorService(sharedScheduledExecutor, "sharedScheduledExecutor"); // serviceDiscoveryAddressNotificationExecutorRing shutdownExecutorServices(serviceDiscoveryAddressNotificationExecutorRing.listItems(), "serviceDiscoveryAddressNotificationExecutorRing"); // registryNotificationExecutorRing shutdownExecutorServices(registryNotificationExecutorRing.listItems(), "registryNotificationExecutorRing"); } private void shutdownExecutorServices(List<? extends ExecutorService> executorServices, String msg) { for (ExecutorService executorService : executorServices) { shutdownExecutorService(executorService, msg); } } private void shutdownExecutorService(ExecutorService executorService, String name) { try { executorService.shutdownNow(); } catch (Exception e) { String msg = "shutdown executor service [" + name + "] failed: "; logger.warn(msg + e.getMessage(), e); } } @Override public void setExtensionAccessor(ExtensionAccessor extensionAccessor) { this.extensionAccessor = extensionAccessor; } @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } }
41.657328
159
0.672823
6d4c6ca2c0c6c09abbf182f22b013d89036c994f
326
package io.github.kavahub.learnjava.common.eventbus; /** * * 子事件 * * @author PinWei Wan * @since 1.0.0 */ public class ChildEvent extends FatherEvent { public ChildEvent(String name) { super(name); } @Override public String toString() { return "ChildEvent[name=" + name + "]"; } }
16.3
52
0.604294
ebccce97e8ac33f1c11c26d7f45129eb9ce0aeca
18,932
/** * Copyright 2015 Tampere University of Technology, Pori Department * * 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 service.tut.pori.contentanalysis.video.reference; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.log4j.Logger; import service.tut.pori.contentanalysis.AnalysisBackend; import service.tut.pori.contentanalysis.PhotoParameters.AnalysisType; import service.tut.pori.contentanalysis.AsyncTask.TaskStatus; import service.tut.pori.contentanalysis.AsyncTask.TaskType; import service.tut.pori.contentanalysis.BackendStatus; import service.tut.pori.contentanalysis.CAContentCore.ServiceType; import service.tut.pori.contentanalysis.CAContentCore.Visibility; import service.tut.pori.contentanalysis.Definitions; import service.tut.pori.contentanalysis.MediaObjectList; import service.tut.pori.contentanalysis.reference.CAReferenceCore; import service.tut.pori.contentanalysis.reference.CAXMLObjectCreator; import service.tut.pori.contentanalysis.video.DeletedVideoList; import service.tut.pori.contentanalysis.video.Timecode; import service.tut.pori.contentanalysis.video.TimecodeList; import service.tut.pori.contentanalysis.video.Video; import service.tut.pori.contentanalysis.video.VideoList; import service.tut.pori.contentanalysis.video.VideoParameters; import service.tut.pori.contentanalysis.video.VideoTaskDetails; import service.tut.pori.contentanalysis.video.VideoTaskResponse; import core.tut.pori.http.RedirectResponse; import core.tut.pori.http.Response; import core.tut.pori.http.parameters.DataGroups; import core.tut.pori.http.parameters.Limits; import core.tut.pori.users.UserIdentity; import core.tut.pori.utils.XMLFormatter; /** * The reference implementations for Video Content Analysis Service. * */ public final class VideoReferenceCore { private static final VideoXMLObjectCreator CREATOR = new VideoXMLObjectCreator(null); private static final DataGroups DATAGROUPS_BACKEND_RESPONSE = new DataGroups(CAXMLObjectCreator.DATA_GROUP_BACKEND_RESPONSE); // data groups for add task callback private static final Limits DEFAULT_LIMITS = new Limits(0, 0); // default number of limits for references private static final DataGroups DATAGROUPS_ALL = new DataGroups(DataGroups.DATA_GROUP_ALL); private static final String EXAMPLE_URI = "http://users.ics.aalto.fi/jorma/d2i/hs-00.mp4"; private static final Logger LOGGER = Logger.getLogger(VideoReferenceCore.class); /** * */ private VideoReferenceCore(){ // nothing needed } /** * * @param authenticatedUser * @param serviceId * @param guid * @return an example response for the given values */ public static RedirectResponse generateTargetUrl(UserIdentity authenticatedUser, ServiceType serviceId, String guid) { LOGGER.info((authenticatedUser == null ? "No logged in user." : "Ignoring the logged in user, id: "+authenticatedUser.getUserId())); // only notify of the logged in status return new RedirectResponse(EXAMPLE_URI); } /** * * @param dataGroups * @return a randomly generated video */ public static Video generateVideo(DataGroups dataGroups) { return CREATOR.createVideo(null, (DataGroups.isEmpty(dataGroups) ? DATAGROUPS_ALL : dataGroups), DEFAULT_LIMITS, null, null); } /** * * @param dataGroups * @param limits * @param cls * @return a randomly generated video list */ public static VideoList generateVideoList(DataGroups dataGroups, Limits limits, Class<? extends VideoList> cls) { if(VideoList.class == cls){ return CREATOR.createVideoList(null, (DataGroups.isEmpty(dataGroups) ? DATAGROUPS_ALL : dataGroups), limits, null, null); }else if(DeletedVideoList.class == cls){ return CREATOR.createDeletedVideoList(limits); }else{ throw new IllegalArgumentException("Unsupported class : "+cls); } } /** * * @param dataGroups * @param limits * @param taskType * @return randomly generated task details */ public static VideoTaskDetails generateVideoTaskDetails(DataGroups dataGroups, Limits limits, TaskType taskType) { switch(taskType){ case ANALYSIS: case FEEDBACK: break; default: throw new IllegalArgumentException("Unsupported task type: "+taskType.name()); } limits.setTypeLimits(-1, -1, service.tut.pori.contentanalysis.Definitions.ELEMENT_BACKEND_STATUS_LIST); // do not add back-end status list return CREATOR.createVideoTaskDetails(null, (DataGroups.isEmpty(dataGroups) ? DATAGROUPS_ALL : dataGroups), limits, null, taskType); } /** * * @return randomly generated timecode */ public static Timecode generateTimecode() { return CREATOR.createTimecode(null); } /** * * @param limits * @return a randomly generated timecode list */ public static TimecodeList generateTimecodeList(Limits limits) { return CREATOR.createTimecodeList(limits, false); } /** * * @return randomly generated video options */ public static VideoParameters generateVideoOptions() { return CREATOR.createVideoOptions(); } /** * * @param limits * @return a randomly generated task response */ public static VideoTaskResponse generateTaskResponse(Limits limits) { return CREATOR.createTaskResponse(null, DATAGROUPS_BACKEND_RESPONSE, limits, null, TaskType.ANALYSIS); } /** * This performs a trivial check for the task contents, checking for the presence of a few key values. * The validity of the actual task contents will not checked. * * @param response */ public static void taskFinished(VideoTaskResponse response) { Integer tBackendId = response.getBackendId(); if(tBackendId == null){ throw new IllegalArgumentException("Invalid backendId: "+tBackendId); } Long tTaskId = response.getTaskId(); if(tTaskId == null){ throw new IllegalArgumentException("Invalid taskId: "+tTaskId); } TaskStatus status = response.getStatus(); if(status == null){ throw new IllegalArgumentException("TaskStatus is invalid or missing."); } TaskType type = response.getTaskType(); if(type == null){ throw new IllegalArgumentException("TaskType is invalid or missing."); } try{ switch(type){ case ANALYSIS: VideoList vl = response.getVideoList(); if(!VideoList.isEmpty(vl)){ if(!VideoList.isValid(vl)){ LOGGER.warn("Invalid "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST); } for(Video v : response.getVideoList().getVideos()){ MediaObjectList vObjects = v.getMediaObjects(); if(MediaObjectList.isEmpty(vObjects)){ LOGGER.info("No media objects for photo, GUID: "+v.getGUID()); }else if(!MediaObjectList.isValid(vObjects)){ throw new IllegalArgumentException("Invalid "+service.tut.pori.contentanalysis.Definitions.ELEMENT_MEDIA_OBJECTLIST); } } } break; case FEEDBACK: if(!VideoList.isValid(response.getVideoList())){ throw new IllegalArgumentException("Invalid "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST); } break; default: throw new IllegalArgumentException("Tasks of type: "+type.name()+" are not supported by this validator."); } }catch(ClassCastException ex){ LOGGER.debug(ex, ex); throw new IllegalArgumentException("Task content data was not of the expected type."); } } /** * * @param backendId * @param taskId * @param dataGroups * @param limits * @return an example response for the given values */ public static Response queryTaskDetails(Integer backendId, Long taskId, DataGroups dataGroups, Limits limits) { if(limits.getMaxItems(service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST) >= Limits.DEFAULT_MAX_ITEMS){ LOGGER.debug("Reseting limits for "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST+": max items was "+Limits.DEFAULT_MAX_ITEMS); limits.setTypeLimits(DEFAULT_LIMITS.getStartItem(service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST), DEFAULT_LIMITS.getEndItem(service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST), service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST); // startItem makes no difference for random } if(limits.getMaxItems(service.tut.pori.contentanalysis.Definitions.ELEMENT_MEDIA_OBJECTLIST) >= Limits.DEFAULT_MAX_ITEMS){ LOGGER.debug("Reseting limits for "+service.tut.pori.contentanalysis.Definitions.ELEMENT_MEDIA_OBJECTLIST+": max items was "+Limits.DEFAULT_MAX_ITEMS); limits.setTypeLimits(DEFAULT_LIMITS.getStartItem(service.tut.pori.contentanalysis.Definitions.ELEMENT_MEDIA_OBJECTLIST), DEFAULT_LIMITS.getEndItem(service.tut.pori.contentanalysis.Definitions.ELEMENT_MEDIA_OBJECTLIST), service.tut.pori.contentanalysis.Definitions.ELEMENT_MEDIA_OBJECTLIST); // startItem makes no difference for random } limits.setTypeLimits(-1, -1, null); // disable all other photo lists return new Response(CREATOR.createVideoTaskDetails(backendId, dataGroups, limits, taskId, TaskType.ANALYSIS)); } /** * * @param authenticatedUser * @param objects * @param dataGroups * @param limits * @param serviceTypes * @param userIdFilters * @return an example response for the given values */ public static Response similarVideosByObject(UserIdentity authenticatedUser, MediaObjectList objects, DataGroups dataGroups, Limits limits, EnumSet<ServiceType> serviceTypes, long[] userIdFilters) { LOGGER.info((authenticatedUser == null ? "No logged in user." : "Ignoring the logged in user, id: "+authenticatedUser.getUserId())); // only notify of the logged in status if(limits.getMaxItems(service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST) >= Limits.DEFAULT_MAX_ITEMS){ LOGGER.debug("Reseting limits: Default max items was "+Limits.DEFAULT_MAX_ITEMS); limits = DEFAULT_LIMITS; // startItem makes no difference for random } return new Response(CREATOR.createSearchResults(null, dataGroups, limits, serviceTypes, userIdFilters, objects)); } /** * * @param authenticatedUser * @param guids * @param dataGroups * @param limits * @param serviceTypes * @param userIdFilter * @return an example response for the given values */ public static Response getVideos(UserIdentity authenticatedUser, List<String> guids, DataGroups dataGroups, Limits limits, EnumSet<ServiceType> serviceTypes, long[] userIdFilter) { LOGGER.info((authenticatedUser == null ? "No logged in user." : "Ignoring the logged in user, id: "+authenticatedUser.getUserId())); // only notify of the logged in status if(limits.getMaxItems(service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST) >= Limits.DEFAULT_MAX_ITEMS){ LOGGER.debug("Reseting limits: Default max items was "+Limits.DEFAULT_MAX_ITEMS); limits = DEFAULT_LIMITS; // startItem makes no difference for random } int userIdCount = (ArrayUtils.isEmpty(userIdFilter) ? 0 : userIdFilter.length); VideoList list = CREATOR.createVideoList(null, dataGroups, limits, serviceTypes, null); if(list != null && guids != null && !guids.isEmpty()){ for(Iterator<Video> iter = list.getVideos().iterator();iter.hasNext();){ // remove all extra guids, we could also modify the limit parameter, but for this testing method, the implementation does not matter Video video = iter.next(); if(guids.isEmpty()){ // we have used up all given guids iter.remove(); }else{ video.setGUID(guids.remove(0)); video.setVisibility(Visibility.PUBLIC); // there could also be private photos for the authenticated user, but to make sure the results are valid, return only PUBLIC photos } if(userIdCount > 1){ video.setOwnerUserId(new UserIdentity(userIdFilter[CREATOR.getRandom().nextInt(userIdCount)])); } } // for } return new Response(list); } /** * This performs a trivial check for the task contents, checking for the presence of a few key values. * The validity of the actual task contents will not be checked. * * @param taskDetails */ public static void addTask(VideoTaskDetails taskDetails) { Integer tBackendId = taskDetails.getBackendId(); if(tBackendId == null){ throw new IllegalArgumentException("Invalid backendId: "+tBackendId); } Long tTaskId = taskDetails.getTaskId(); if(tTaskId == null){ throw new IllegalArgumentException("Invalid taskId: "+tTaskId); } String uri = taskDetails.getCallbackUri(); if(StringUtils.isBlank(uri)){ throw new IllegalArgumentException("Invalid callbackUri: "+uri); } TaskType type = taskDetails.getTaskType(); if(type == null){ throw new IllegalArgumentException("TaskType is invalid or missing."); } switch(type){ case BACKEND_FEEDBACK: if(!VideoList.isValid(taskDetails.getVideoList())){ throw new IllegalArgumentException("Invalid "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST); } addTaskAsyncCallback(taskDetails, null); break; case ANALYSIS: VideoList videoList = taskDetails.getVideoList(); if(!VideoList.isValid(videoList)){ throw new IllegalArgumentException("Invalid "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST); } if(taskDetails.getDeletedVideoList() != null){ throw new IllegalArgumentException(service.tut.pori.contentanalysis.video.Definitions.ELEMENT_DELETED_VIDEOLIST+" cannot appear in a task of type: "+TaskType.ANALYSIS.name()); } VideoParameters vp = taskDetails.getTaskParameters(); for(Video video : videoList.getVideos()){ MediaObjectList mediaObjects = CREATOR.createMediaObjectList((vp == null ? null : vp.getAnalysisTypes()), DATAGROUPS_BACKEND_RESPONSE, DEFAULT_LIMITS, null); for(service.tut.pori.contentanalysis.MediaObject o : mediaObjects.getMediaObjects()){ o.setOwnerUserId(null); o.setBackendId(tBackendId); o.setMediaObjectId(null); o.setServiceType(null); } video.addackendStatus(new BackendStatus(new AnalysisBackend(tBackendId), TaskStatus.COMPLETED)); video.addMediaObjects(mediaObjects); } addTaskAsyncCallback(taskDetails, videoList); break; case FEEDBACK: if(taskDetails.getVideoList() != null && !VideoList.isValid(taskDetails.getVideoList())){ throw new IllegalArgumentException("Invalid "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST); }else if(taskDetails.getDeletedVideoList() == null){ throw new IllegalArgumentException(Definitions.ELEMENT_TASK_DETAILS+" requires at least one of "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_VIDEOLIST+" or "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_DELETED_VIDEOLIST); }else if(!DeletedVideoList.isValid(taskDetails.getDeletedVideoList())){ throw new IllegalArgumentException("Invalid "+service.tut.pori.contentanalysis.video.Definitions.ELEMENT_DELETED_VIDEOLIST); } addTaskAsyncCallback(taskDetails, null); break; default: throw new IllegalArgumentException("Tasks of type: "+type.name()+" are not supported by this validator."); } } /** * * @param taskId * @param dataGroups * @param limits * @return an example response for the given values */ public static Response queryTaskStatus(Long taskId, DataGroups dataGroups, Limits limits) { if(limits.getMaxItems() >= Limits.DEFAULT_MAX_ITEMS){ LOGGER.debug("Reseting limits: Default max items was "+Limits.DEFAULT_MAX_ITEMS); limits = DEFAULT_LIMITS; // startItem makes no difference for random } return new Response(CREATOR.createTaskResponse(null, dataGroups, limits, taskId, TaskType.ANALYSIS)); } /** * Call asynchronously the callback given in the details, returning an example task response * * @param details * @param videoList * @throws UnsupportedOperationException on unsupported task details * @see service.tut.pori.contentanalysis.video.VideoTaskResponse */ public static void addTaskAsyncCallback(VideoTaskDetails details, VideoList videoList) throws UnsupportedOperationException{ TaskType type = details.getTaskType(); if(!TaskType.ANALYSIS.equals(type)){ throw new UnsupportedOperationException("Unsupported task type: "+type); } HttpPost post = new HttpPost(details.getCallbackUri()); VideoTaskResponse r = new VideoTaskResponse(); r.setBackendId(details.getBackendId()); r.setTaskId(details.getTaskId()); r.setStatus(TaskStatus.COMPLETED); r.setTaskType(details.getTaskType()); r.setVideoList(videoList); post.setEntity(new StringEntity((new XMLFormatter()).toString(r), core.tut.pori.http.Definitions.ENCODING_UTF8)); CAReferenceCore.executeAsyncCallback(post); } /** * Client API variation of search by GUID * * @param authenticatedUser * @param analysisTypes * @param guid * @param dataGroups * @param limits * @param serviceTypes * @param userIdFilters * @return an example response for the given values */ public static Response searchSimilarById(UserIdentity authenticatedUser, EnumSet<AnalysisType> analysisTypes, String guid, DataGroups dataGroups, Limits limits, EnumSet<ServiceType> serviceTypes, long[] userIdFilters) { LOGGER.info((authenticatedUser == null ? "No logged in user." : "Ignoring the logged in user, id: "+authenticatedUser.getUserId())); // only notify of the logged in status return searchSimilarById(analysisTypes, guid, dataGroups, limits, serviceTypes, userIdFilters); // we can directly call the back-end API reference implementation } /** * Back-end API variation of search by GUID * * @param analysisTypes * @param serviceTypes * @param guid * @param userIds * @param dataGroups * @param limits * @return an example response for the given values */ public static Response searchSimilarById(EnumSet<AnalysisType> analysisTypes, String guid, DataGroups dataGroups, Limits limits, EnumSet<ServiceType> serviceTypes, long[] userIds) { if(limits.getMaxItems() >= Limits.DEFAULT_MAX_ITEMS){ LOGGER.debug("Reseting limits: Default max items was "+Limits.DEFAULT_MAX_ITEMS); limits = DEFAULT_LIMITS; // startItem makes no difference for random } return new Response(CREATOR.createSearchResults(guid, dataGroups, limits, serviceTypes, userIds, null)); } }
42.63964
337
0.756761