hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e18105b684db36604e0096d0416010b29cd1dee | 1,249 | java | Java | aws-java-sdk-comprehendmedical/src/main/java/com/amazonaws/services/comprehendmedical/model/InternalServerException.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | 1 | 2022-01-04T04:11:16.000Z | 2022-01-04T04:11:16.000Z | aws-java-sdk-comprehendmedical/src/main/java/com/amazonaws/services/comprehendmedical/model/InternalServerException.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-comprehendmedical/src/main/java/com/amazonaws/services/comprehendmedical/model/InternalServerException.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | 33.756757 | 123 | 0.728583 | 10,239 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.comprehendmedical.model;
import javax.annotation.Generated;
/**
* <p>
* An internal server error occurred. Retry your request.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InternalServerException extends com.amazonaws.services.comprehendmedical.model.AWSComprehendMedicalException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new InternalServerException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public InternalServerException(String message) {
super(message);
}
}
|
3e1810f225c36093b2c3b1b401c32f4053b13463 | 406 | java | Java | spring-learn/src/main/java/com/learn/config/AppConfig.java | ren1151576/spring-framework | 3ba41b90371919e6827cb228c9173da2d4d6e538 | [
"Apache-2.0"
] | null | null | null | spring-learn/src/main/java/com/learn/config/AppConfig.java | ren1151576/spring-framework | 3ba41b90371919e6827cb228c9173da2d4d6e538 | [
"Apache-2.0"
] | null | null | null | spring-learn/src/main/java/com/learn/config/AppConfig.java | ren1151576/spring-framework | 3ba41b90371919e6827cb228c9173da2d4d6e538 | [
"Apache-2.0"
] | null | null | null | 20.3 | 60 | 0.785714 | 10,240 | package com.learn.config;
import com.learn.bean.ExampleBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public ExampleBean exampleBean() {
ExampleBean exampleBean = new ExampleBean();
exampleBean.setParam1("param2");
exampleBean.setParam2("param1");
return exampleBean;
}
}
|
3e1812c11ebc2c44fe4e6adc64d8fccf80ffc9da | 377 | java | Java | src/com/github/metalloid/name/Name.java | Rafal-Laskowski/Metalloid-WebElement-Name | 841b9ad305ce9bdfe8198dd300dd2495ac22d559 | [
"Apache-2.0"
] | null | null | null | src/com/github/metalloid/name/Name.java | Rafal-Laskowski/Metalloid-WebElement-Name | 841b9ad305ce9bdfe8198dd300dd2495ac22d559 | [
"Apache-2.0"
] | null | null | null | src/com/github/metalloid/name/Name.java | Rafal-Laskowski/Metalloid-WebElement-Name | 841b9ad305ce9bdfe8198dd300dd2495ac22d559 | [
"Apache-2.0"
] | null | null | null | 31.416667 | 71 | 0.806366 | 10,241 | package com.github.metalloid.name;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.CONSTRUCTOR})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Name {
String description() default "";
} |
3e18134042eb9c23ba3bad4aa3d8f1b6d16cee64 | 1,900 | java | Java | src/main/java/net/farlands/sanctuary/command/player/CommandAFK.java | jpintoduarte76/FarLands | 3071772f07fef0b6bd29e2b249d37326faccac66 | [
"Apache-2.0"
] | 3 | 2021-11-29T00:04:16.000Z | 2021-12-26T21:31:09.000Z | src/main/java/net/farlands/sanctuary/command/player/CommandAFK.java | jpintoduarte76/FarLands | 3071772f07fef0b6bd29e2b249d37326faccac66 | [
"Apache-2.0"
] | 1 | 2021-12-26T21:37:03.000Z | 2021-12-26T21:37:03.000Z | src/main/java/net/farlands/sanctuary/command/player/CommandAFK.java | jpintoduarte76/FarLands | 3071772f07fef0b6bd29e2b249d37326faccac66 | [
"Apache-2.0"
] | null | null | null | 38.77551 | 139 | 0.691053 | 10,242 | package net.farlands.sanctuary.command.player;
import net.farlands.sanctuary.FarLands;
import net.farlands.sanctuary.command.Category;
import net.farlands.sanctuary.command.PlayerCommand;
import net.farlands.sanctuary.data.FLPlayerSession;
import net.farlands.sanctuary.data.Rank;
import net.farlands.sanctuary.util.ComponentColor;
import net.farlands.sanctuary.util.Logging;
import net.farlands.sanctuary.util.TimeInterval;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class CommandAFK extends PlayerCommand {
public CommandAFK() {
super(Rank.INITIATE, Category.MISCELLANEOUS, "Notify players that you are AFK.", "/afk", "afk");
}
@Override
public boolean execute(Player sender, String[] args) {
FLPlayerSession session = FarLands.getDataHandler().getSession(sender);
// Check the command cooldown
if (!session.isCommandCooldownComplete(this)) {
sender.sendMessage(ComponentColor.red(
"You can use this command again in " +
TimeInterval.formatTime(session.commandCooldownTimeRemaining(this) * 50L, false))
);
return true;
}
// Don't allow them to run this command while they're actively being AFK checked
if (!session.afkCheckCooldown.isComplete())
return true;
// Set them to be AFK
Bukkit.getScheduler().runTaskLater(FarLands.getInstance(), () -> session.afk = true, 50L);
session.setCommandCooldown(this, 3L * 60L * 20L);
// Reset their AFK check cooldown
if (session.afkCheckInitializerCooldown != null)
session.afkCheckInitializerCooldown.resetCurrentTask();
// Notify the server
Logging.broadcast(flp -> !flp.handle.getIgnoreStatus(session.handle).includesChat(), " * %0 is now AFK.", session.handle.username);
return true;
}
}
|
3e18134769a817a3879719bf77bf1ac4c8d4da28 | 3,083 | java | Java | badge-library/src/main/java/net/badgeindicator/Configuration.java | platoblm/badge-indicator | 0d9e6884c6c5cb64bd7c342021453a11b4ec3d78 | [
"Apache-2.0"
] | null | null | null | badge-library/src/main/java/net/badgeindicator/Configuration.java | platoblm/badge-indicator | 0d9e6884c6c5cb64bd7c342021453a11b4ec3d78 | [
"Apache-2.0"
] | null | null | null | badge-library/src/main/java/net/badgeindicator/Configuration.java | platoblm/badge-indicator | 0d9e6884c6c5cb64bd7c342021453a11b4ec3d78 | [
"Apache-2.0"
] | null | null | null | 33.150538 | 118 | 0.725268 | 10,243 | package net.badgeindicator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import static android.graphics.Color.RED;
import static android.graphics.Color.WHITE;
class Configuration {
private int value;
private ColorStateList backgroundColors;
private ColorStateList textColors;
private int textSize;
private int padding;
private int currentBackgroundColor;
private int currentTextColor;
public int getValue() {
return value;
}
void setValue(int value) {
this.value = value;
}
String getValueToDraw() {
return String.valueOf(value);
}
public int getCurrentBackgroundColor() {
return currentBackgroundColor;
}
public int getCurrentTextColor() {
return currentTextColor;
}
public int getTextSize() {
return textSize;
}
public int getPadding() {
return padding;
}
void loadDefaults(Context context) {
Resources resources = context.getResources();
backgroundColors = ColorStateList.valueOf(RED);
textColors = ColorStateList.valueOf(WHITE);
textSize= resources.getDimensionPixelSize(R.dimen.badge_indicator_default_text_size);
padding = resources.getDimensionPixelSize(R.dimen.badge_indicator_default_padding);
}
void loadAttributes(Context context, AttributeSet attrs) {
TypedArray appearance = context.obtainStyledAttributes(attrs, R.styleable.BadgeIndicator);
loadFromAttributeArray(appearance);
appearance.recycle();
}
/**
* @param stateSet the current drawable state
* @return true if colors have changed, false if not
*/
boolean updateCurrentColors(int[] stateSet) {
final int backgroundColor = currentBackgroundColor;
final int textColor = currentTextColor;
currentBackgroundColor = backgroundColors.getColorForState(stateSet, 0);
currentTextColor = textColors.getColorForState(stateSet, 0);
return backgroundColor != currentBackgroundColor ||
textColor != currentTextColor;
}
private void loadFromAttributeArray(TypedArray appearance) {
value = appearance.getInt(R.styleable.BadgeIndicator_badge_value, value);
backgroundColors = getColorStateList(appearance,R.styleable.BadgeIndicator_badge_color, backgroundColors);
textColors = getColorStateList(appearance, R.styleable.BadgeIndicator_badge_textColor, textColors);
textSize = appearance.getDimensionPixelSize(R.styleable.BadgeIndicator_badge_textSize, textSize);
padding = appearance.getDimensionPixelSize(R.styleable.BadgeIndicator_badge_padding, padding);
}
private ColorStateList getColorStateList(TypedArray appearance, int resourceIndex, ColorStateList defaultColors) {
ColorStateList colors = appearance.getColorStateList(resourceIndex);
return colors != null ? colors : defaultColors;
}
}
|
3e1816829ebc1495628dc5a9bed458ac4b6b7309 | 836 | java | Java | apt/src/test/java/com/scindapsus/apt/APTTests.java | PhaerisWakfu/scindapsus-lock-spring-boot-starter | 4b97d94856c185538a13e4804e36ae9af24b863b | [
"Apache-2.0"
] | 1 | 2021-12-16T06:23:53.000Z | 2021-12-16T06:23:53.000Z | apt/src/test/java/com/scindapsus/apt/APTTests.java | PhaerisWakfu/scindapsus-lock-spring-boot-starter | 4b97d94856c185538a13e4804e36ae9af24b863b | [
"Apache-2.0"
] | null | null | null | apt/src/test/java/com/scindapsus/apt/APTTests.java | PhaerisWakfu/scindapsus-lock-spring-boot-starter | 4b97d94856c185538a13e4804e36ae9af24b863b | [
"Apache-2.0"
] | null | null | null | 25.333333 | 84 | 0.784689 | 10,244 | package com.scindapsus.apt;
import com.scindapsus.apt.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
/**
* @author wyh
* @since 1.0
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = APTApplication.class)
@AutoConfigureMockMvc
class APTTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private UserRepository userRepository;
@Test
void test(){
userRepository.findAll();
}
}
|
3e1817186dbd30ae15ee89c94803b2c0ecc900e2 | 123 | java | Java | craof-android/app/src/main/java/br/com/org/entidade/craof/ItemCompra.java | agrocomp/Craof-Android | d2d6f78f78d2259ea77b35e2fed80b1d323881e9 | [
"MIT"
] | 1 | 2016-10-30T14:09:07.000Z | 2016-10-30T14:09:07.000Z | craof-android/app/src/main/java/br/com/org/entidade/craof/ItemCompra.java | agrocomp/Craof-Android | d2d6f78f78d2259ea77b35e2fed80b1d323881e9 | [
"MIT"
] | null | null | null | craof-android/app/src/main/java/br/com/org/entidade/craof/ItemCompra.java | agrocomp/Craof-Android | d2d6f78f78d2259ea77b35e2fed80b1d323881e9 | [
"MIT"
] | null | null | null | 12.3 | 34 | 0.772358 | 10,245 | package br.com.org.entidade.craof;
public class ItemCompra {
private float quantidade;
private char finalidadeUso;
}
|
3e181886b87ef07b8d0a3bacb0722ba17d11212b | 10,134 | java | Java | src/main/java/com/eclipsekingdom/fractalforest/trees/Species.java | ParallelMC/FractalForest | 120f9ad8d87a61ef31d97073d348ac18b6278919 | [
"MIT"
] | null | null | null | src/main/java/com/eclipsekingdom/fractalforest/trees/Species.java | ParallelMC/FractalForest | 120f9ad8d87a61ef31d97073d348ac18b6278919 | [
"MIT"
] | null | null | null | src/main/java/com/eclipsekingdom/fractalforest/trees/Species.java | ParallelMC/FractalForest | 120f9ad8d87a61ef31d97073d348ac18b6278919 | [
"MIT"
] | null | null | null | 47.801887 | 236 | 0.714624 | 10,246 | package com.eclipsekingdom.fractalforest.trees;
import com.eclipsekingdom.fractalforest.trees.effect.EffectType;
import com.eclipsekingdom.fractalforest.trees.effect.IEffects;
import com.eclipsekingdom.fractalforest.trees.gen.fractal.FractalGrowthPattern;
import com.eclipsekingdom.fractalforest.trees.gen.fractal.FractalTreeBuilder;
import com.eclipsekingdom.fractalforest.trees.gen.fractal.genome.GenomeType;
import com.eclipsekingdom.fractalforest.trees.gen.fractal.genome.IGenome;
import com.eclipsekingdom.fractalforest.trees.habitat.HabitatType;
import com.eclipsekingdom.fractalforest.trees.habitat.IHabitat;
import com.eclipsekingdom.fractalforest.util.ChatUtil;
import com.eclipsekingdom.fractalforest.util.Scale;
import com.eclipsekingdom.fractalforest.util.X.FSapling;
import com.eclipsekingdom.fractalforest.util.theme.ITheme;
import com.eclipsekingdom.fractalforest.util.theme.ThemeType;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import org.checkerframework.checker.units.qual.A;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.eclipsekingdom.fractalforest.sys.language.Message.LABEL_SAPLING;
import static com.eclipsekingdom.fractalforest.sys.language.Message.LABEL_SPECIES;
/**
* This class represents a specific Species of sapling.
* This used to be an enum, but was converted into a class to allow other plugins to add custom species
*/
public class Species {
public static final Species MAGNOLIA = new Species("MAGNOLIA", Scale.SMALL, GenomeType.MAGNOLIA.value(), FSapling.OAK_SAPLING, ThemeType.OAK.getTheme());
public static final Species BUCK_EYE = new Species("BUCK_EYE", Scale.MEDIUM, GenomeType.BUCK_EYE.value(), FSapling.OAK_SAPLING, ThemeType.OAK.getTheme());
public static final Species FLOWERING_HAWTHORN = new Species("FLOWERING_HAWTHORN", Scale.MEDIUM, GenomeType.BUCK_EYE.value(), FSapling.OAK_SAPLING, ThemeType.FLOWERING_HAWTHORN.getTheme());
public static final Species OAK = new Species("OAK", Scale.MASSIVE, GenomeType.OAK.value(), FSapling.OAK_SAPLING, ThemeType.OAK.getTheme());
public static final Species ELM = new Species("ELM", Scale.MASSIVE, GenomeType.ELM.value(), FSapling.OAK_SAPLING, ThemeType.OAK.getTheme());
public static final Species BIRCH = new Species("BIRCH", Scale.BIG, GenomeType.BIRCH.value(), FSapling.BIRCH_SAPLING, ThemeType.BIRCH.getTheme());
public static final Species FALL_BIRCH = new Species("FALL_BIRCH", Scale.BIG, GenomeType.BIRCH.value(), FSapling.BIRCH_SAPLING, ThemeType.FALL_BIRCH.getTheme());
public static final Species FALL_OAK = new Species("FALL_OAK", Scale.MASSIVE, GenomeType.OAK.value(), FSapling.OAK_SAPLING, ThemeType.FALL_OAK.getTheme());
public static final Species FALL_ELM = new Species("FALL_ELM", Scale.MASSIVE, GenomeType.ELM.value(), FSapling.OAK_SAPLING, ThemeType.FALL_ELM.getTheme());
public static final Species FALL_MAPLE = new Species("FALL_MAPLE", Scale.MASSIVE, GenomeType.OAK.value(), FSapling.OAK_SAPLING, ThemeType.FALL_MAPLE.getTheme());
public static final Species WEIRWOOD = new Species("WEIRWOOD", Scale.MASSIVE, GenomeType.WEIRWOOD.value(), FSapling.BIRCH_SAPLING, ThemeType.WEIRWOOD.getTheme());
public static final Species WHITE_ASH = new Species("WHITE_ASH", Scale.BIG, GenomeType.WHITE_ASH.value(), FSapling.ACACIA_SAPLING, ThemeType.WHITE_ASH.getTheme());
public static final Species NARROW_LEAF_ASH = new Species("NARROW_LEAF_ASH", Scale.BIG, GenomeType.NARROW_LEAF_ASH.value(), FSapling.ACACIA_SAPLING, ThemeType.WHITE_ASH.getTheme());
public static final Species SHANTUNG_MAPLE = new Species("SHANTUNG_MAPLE", Scale.MASSIVE, GenomeType.SHANTUNG_MAPLE.value(), FSapling.OAK_SAPLING, ThemeType.OAK.getTheme());
public static final Species HICKORY = new Species("HICKORY", Scale.BIG, GenomeType.HICKORY.value(), FSapling.OAK_SAPLING, ThemeType.OAK.getTheme());
public static final Species BLOOD_BUSH = new Species("BLOOD_BUSH", Scale.SMALL, GenomeType.BLOOD_BUSH.value(), FSapling.NETHER_WART, ThemeType.BLOOD_BUSH.getTheme(), HabitatType.NETHER.getHabitat(), EffectType.NETHER.getEffects());
public static final Species FLAME_TREE = new Species("FLAME_TREE", Scale.MEDIUM, GenomeType.FLAME_TREE.value(), FSapling.NETHER_WART, ThemeType.FLAME_TREE.getTheme(), HabitatType.NETHER.getHabitat(), EffectType.NETHER.getEffects());
public static final Species CYGNI = new Species("CYGNI", Scale.MEDIUM, GenomeType.CYGNI.value(), FSapling.CHORUS, ThemeType.CYGNI.getTheme(), HabitatType.END.getHabitat(), EffectType.END.getEffects());
public static final Species SECCHI = new Species("SECCHI", Scale.SMALL, GenomeType.SECCHI.value(), FSapling.CHORUS, ThemeType.SECCHI.getTheme(), HabitatType.END.getHabitat(), EffectType.END.getEffects());
private Scale scale;
private FractalGrowthPattern growthPattern;
private FSapling fSapling;
private IHabitat habitat;
private IEffects effects;
private ITheme theme;
private String plantingPermString;
private String formattedName;
private String name;
public Species(String name, Scale scale, IGenome genome, FSapling fSapling, ITheme theme, IHabitat habitat, IEffects effects) {
init(name, scale, genome, fSapling, theme, habitat, effects);
}
public Species(Scale scale, IGenome genome, FSapling fSapling, ITheme theme, IHabitat habitat, IEffects effects) {
init("", scale, genome, fSapling, theme, habitat, effects);
}
public Species(String name, Scale scale, IGenome genome, FSapling fSapling, ITheme theme) {
init(name, scale, genome, fSapling, theme, HabitatType.FOREST.getHabitat(), EffectType.FOREST.getEffects());
}
public Species(Scale scale, IGenome genome, FSapling fSapling, ITheme theme) {
init("", scale, genome, fSapling, theme, HabitatType.FOREST.getHabitat(), EffectType.FOREST.getEffects());
}
private Species() {
}
private void init(String name, Scale scale, IGenome genome, FSapling fSapling, ITheme theme, IHabitat habitat, IEffects effects) {
this.name = name;
this.scale = scale;
this.growthPattern = new FractalGrowthPattern(genome);
this.fSapling = fSapling;
this.habitat = habitat;
this.effects = effects;
this.theme = theme;
this.plantingPermString = "forest.plant." + toString().replace("_", "").toLowerCase();
this.formattedName = ChatUtil.format(toString());
}
public ITree getIndividual(Player planter, Location seed) {
return new FractalTreeBuilder(this, planter, seed, growthPattern.generateBlueprint());
}
public ItemStack getSapling() {
String species = toString();
ItemStack itemStack = fSapling.getItemStack();
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(ChatColor.GREEN + formattedName + " " + LABEL_SAPLING);
meta.addEnchant(Enchantment.DURABILITY, 1, true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
ArrayList<String> lore = new ArrayList<>();
lore.add(ChatColor.DARK_GREEN + LABEL_SPECIES.toString() + ": " + ChatColor.GRAY + species);
lore.add(ChatColor.DARK_GREEN + "Size: " + ChatColor.GRAY + scale.getFormatted());
meta.setLore(lore);
itemStack.setItemMeta(meta);
return itemStack;
}
public IHabitat getHabitat() {
return habitat;
}
public IEffects getEffects() {
return effects;
}
public ITheme getTheme() {
return theme;
}
public String format() {
return formattedName;
}
public String getPlanterPerm() {
return plantingPermString;
}
public static Species from(String string) {
for (Species species : values()) {
if (species.toString().equalsIgnoreCase(string)) {
return species;
}
}
return null;
}
public static void registerPermissions() {
PluginManager pm = Bukkit.getServer().getPluginManager();
for (Species species : values()) {
pm.addPermission(new Permission(species.getPlanterPerm(), "allows player to plant " + species.format() + " sapling."));
}
}
private static final HashMap<String, Species> species = new HashMap<>();
private static boolean initializedStaticVals = false;
/**
* Returns an array of all registered species
* @return An array of all registered species
*/
public static Species[] values() {
// This block automatically takes all of the static values and adds them to the species hashmap.
if (!initializedStaticVals) {
Species blankSpecies = new Species();
Field[] fields = Species.class.getDeclaredFields();
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers()) && f.getType().equals(Species.class)) {
try {
Species sp = (Species) f.get(blankSpecies);
species.put(sp.name(), sp);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
initializedStaticVals = true;
}
return species.values().toArray(new Species[0]);
}
/**
* Adds a new species to the map
* @param newSpecies The new species to add
*/
public static void addSpecies(Species newSpecies) {
species.put(newSpecies.name(), newSpecies);
}
public String name() {
return name;
}
public static Species valueOf(String name) {
return species.get(name);
}
public String toString() {
return name;
}
}
|
3e181976992ea4169bc21d329f41535cc1e974d0 | 7,541 | java | Java | pmml-evaluator/src/main/java/org/jpmml/evaluator/AssociationModelEvaluator.java | jpmml/jpmml | d63174f6e7e8a663200d9fc2caa6606cd51cbe74 | [
"BSD-3-Clause"
] | 60 | 2015-01-27T03:27:11.000Z | 2021-08-17T03:47:20.000Z | pmml-evaluator/src/main/java/org/jpmml/evaluator/AssociationModelEvaluator.java | jpmml/jpmml | d63174f6e7e8a663200d9fc2caa6606cd51cbe74 | [
"BSD-3-Clause"
] | 1 | 2015-06-16T19:39:37.000Z | 2015-06-16T19:39:37.000Z | pmml-evaluator/src/main/java/org/jpmml/evaluator/AssociationModelEvaluator.java | jpmml/jpmml | d63174f6e7e8a663200d9fc2caa6606cd51cbe74 | [
"BSD-3-Clause"
] | 36 | 2015-04-14T06:10:03.000Z | 2022-03-30T05:08:43.000Z | 27.521898 | 127 | 0.737833 | 10,247 | /*
* Copyright (c) 2013 Villu Ruusmann
*/
package org.jpmml.evaluator;
import java.util.*;
import org.jpmml.manager.*;
import org.dmg.pmml.*;
import com.google.common.cache.*;
import com.google.common.collect.*;
public class AssociationModelEvaluator extends ModelEvaluator<AssociationModel> implements HasEntityRegistry<AssociationRule> {
public AssociationModelEvaluator(PMML pmml){
this(pmml, find(pmml.getModels(), AssociationModel.class));
}
public AssociationModelEvaluator(PMML pmml, AssociationModel associationModel){
super(pmml, associationModel);
}
@Override
public String getSummary(){
return "Association rules";
}
public FieldName getActiveField(){
List<FieldName> activeFields = getActiveFields();
if(activeFields.size() < 1){
throw new InvalidFeatureException("No active fields", getMiningSchema());
} else
if(activeFields.size() > 1){
throw new InvalidFeatureException("Too many active fields", getMiningSchema());
}
return activeFields.get(0);
}
/**
* @return <code>null</code> Always.
*/
@Override
public Target getTarget(FieldName name){
return null;
}
@Override
public BiMap<String, AssociationRule> getEntityRegistry(){
return getValue(AssociationModelEvaluator.entityCache);
}
@Override
public Map<FieldName, ?> evaluate(ModelEvaluationContext context){
AssociationModel associationModel = getModel();
if(!associationModel.isScorable()){
throw new InvalidResultException(associationModel);
}
Map<FieldName, ?> predictions;
MiningFunctionType miningFunction = associationModel.getFunctionName();
switch(miningFunction){
case ASSOCIATION_RULES:
predictions = evaluateAssociationRules(context);
break;
default:
throw new UnsupportedFeatureException(associationModel, miningFunction);
}
return OutputUtil.evaluate(predictions, context);
}
private Map<FieldName, ?> evaluateAssociationRules(EvaluationContext context){
AssociationModel associationModel = getModel();
FieldName activeField = getActiveField();
FieldValue value = context.getField(activeField);
if(value == null){
throw new MissingFieldException(activeField, associationModel);
}
Collection<?> values;
try {
values = (Collection<?>)FieldValueUtil.getValue(value);
} catch(ClassCastException cce){
throw new TypeCheckException(Collection.class, value);
}
Set<String> input = createInput(values, context);
Map<String, Boolean> flags = Maps.newLinkedHashMap();
List<Itemset> itemsets = associationModel.getItemsets();
for(Itemset itemset : itemsets){
flags.put(itemset.getId(), isSubset(input, itemset));
}
List<AssociationRule> associationRules = associationModel.getAssociationRules();
BitSet antecedentFlags = new BitSet(associationRules.size());
BitSet consequentFlags = new BitSet(associationRules.size());
for(int i = 0; i < associationRules.size(); i++){
AssociationRule associationRule = associationRules.get(i);
Boolean antecedentFlag = flags.get(associationRule.getAntecedent());
if(antecedentFlag == null){
throw new InvalidFeatureException(associationRule);
}
antecedentFlags.set(i, antecedentFlag);
Boolean consequentFlag = flags.get(associationRule.getConsequent());
if(consequentFlag == null){
throw new InvalidFeatureException(associationRule);
}
consequentFlags.set(i, consequentFlag);
}
Association association = new Association(associationRules, antecedentFlags, consequentFlags){
@Override
public BiMap<String, Item> getItemRegistry(){
return AssociationModelEvaluator.this.getItemRegistry();
}
@Override
public BiMap<String, Itemset> getItemsetRegistry(){
return AssociationModelEvaluator.this.getItemsetRegistry();
}
@Override
public BiMap<String, AssociationRule> getAssociationRuleRegistry(){
return AssociationModelEvaluator.this.getEntityRegistry();
}
};
return Collections.singletonMap(getTargetField(), association);
}
/**
* @return A set of {@link Item#getId() Item identifiers}.
*/
private Set<String> createInput(Collection<?> values, EvaluationContext context){
Set<String> result = Sets.newLinkedHashSet();
Map<String, String> valueItems = (getItemValues().inverse());
values:
for(Object value : values){
String stringValue = TypeUtil.format(value);
String id = valueItems.get(stringValue);
if(id == null){
context.addWarning("Unknown item value \"" + stringValue + "\"");
continue values;
}
result.add(id);
}
return result;
}
static
private boolean isSubset(Set<String> input, Itemset itemset){
boolean result = true;
List<ItemRef> itemRefs = itemset.getItemRefs();
for(ItemRef itemRef : itemRefs){
result &= input.contains(itemRef.getItemRef());
if(!result){
return false;
}
}
return result;
}
/**
* @return A bidirectional map between {@link Item#getId Item identifiers} and {@link Item instances}.
*/
private BiMap<String, Item> getItemRegistry(){
return getValue(AssociationModelEvaluator.itemCache);
}
/**
* @return A bidirectional map between {@link Itemset#getId() Itemset identifiers} and {@link Itemset instances}.
*/
private BiMap<String, Itemset> getItemsetRegistry(){
return getValue(AssociationModelEvaluator.itemsetCache);
}
/**
* @return A bidirectional map between {@link Item#getId() Item identifiers} and {@link Item#getValue() Item values}.
*/
private BiMap<String, String> getItemValues(){
return getValue(AssociationModelEvaluator.itemValueCache);
}
static
private BiMap<String, String> parseItemValues(AssociationModel associationModel){
BiMap<String, String> result = HashBiMap.create();
List<Item> items = associationModel.getItems();
for(Item item : items){
result.put(item.getId(), item.getValue());
}
return result;
}
private static final LoadingCache<AssociationModel, BiMap<String, AssociationRule>> entityCache = CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<AssociationModel, BiMap<String, AssociationRule>>(){
@Override
public BiMap<String, AssociationRule> load(AssociationModel associationModel){
BiMap<String, AssociationRule> result = HashBiMap.create();
EntityUtil.putAll(associationModel.getAssociationRules(), result);
return result;
}
});
private static final LoadingCache<AssociationModel, BiMap<String, Item>> itemCache = CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<AssociationModel, BiMap<String, Item>>(){
@Override
public BiMap<String, Item> load(AssociationModel associationModel){
BiMap<String, Item> result = HashBiMap.create();
EntityUtil.putAll(associationModel.getItems(), result);
return result;
}
});
private static final LoadingCache<AssociationModel, BiMap<String, Itemset>> itemsetCache = CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<AssociationModel, BiMap<String, Itemset>>(){
@Override
public BiMap<String, Itemset> load(AssociationModel associationModel){
BiMap<String, Itemset> result = HashBiMap.create();
EntityUtil.putAll(associationModel.getItemsets(), result);
return result;
}
});
private static final LoadingCache<AssociationModel, BiMap<String, String>> itemValueCache = CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<AssociationModel, BiMap<String, String>>(){
@Override
public BiMap<String, String> load(AssociationModel associationModel){
return parseItemValues(associationModel);
}
});
} |
3e1819b47af8b889926c6a29ff2df478b9ec934f | 3,216 | java | Java | SS16_Aufgaben/Blatt08/vorgabe/tests/GraphTest.java | wustudent/AlgoDat | ff6067412f2f23a85f847d83820aeb4914c0e2ad | [
"MIT"
] | null | null | null | SS16_Aufgaben/Blatt08/vorgabe/tests/GraphTest.java | wustudent/AlgoDat | ff6067412f2f23a85f847d83820aeb4914c0e2ad | [
"MIT"
] | null | null | null | SS16_Aufgaben/Blatt08/vorgabe/tests/GraphTest.java | wustudent/AlgoDat | ff6067412f2f23a85f847d83820aeb4914c0e2ad | [
"MIT"
] | 2 | 2016-05-12T22:11:22.000Z | 2020-03-27T08:56:09.000Z | 24 | 104 | 0.666978 | 10,248 | import java.io.IOException;
import java.util.LinkedList;
import org.junit.Test;
import org.junit.Assert;
public class GraphTest {
// Test correct total edge weight of MST
@Test
public void testWeight() {
Graph g1;
try {
g1 = GraphIO.loadGraph("tests/testgraphen/test_kruskal01.txt");
// get mst
Graph mst = g1.toMinSpanTree();
// get actual weight
int actual = 0;
for (Node n : mst.getNodes()) {
for (Edge e : n.getIncidentEdges()) {
actual += e.getWeight();
}
}
// get correct weight
int expected = 12;
Assert.assertEquals("This is not the minimum spanning tree",
expected, actual);
} catch (IOException e1) {
e1.printStackTrace();
}
}
//You can implement the following tests yourself.
//We recommend to add more test than just these examples.
// test if the MinSpanTree has the correct number of edges
@Test
public void testEdgeCount() {
DiGraph g1;
try {
g1 = GraphIO.loadGraph("tests/testgraphen/test_kruskal01.txt");
// get mst
DiGraph mst =(DiGraph) g1.toMinSpanTree();
// get actual count
int actual = mst.getEdges().size();
// get correct count
int expected = 6;
Assert.assertEquals("Count to Edges is not correct:",
expected, actual);
} catch (IOException e1) {
e1.printStackTrace();
}
}
// Test if every node has at least one edge (in an MST with more than 1 node)
@Test
public void testEveryNodeHasEdges() {
DiGraph g1;
try {
g1 = GraphIO.loadGraph("tests/testgraphen/test_kruskal01.txt");
// get mst
DiGraph mst =(DiGraph) g1.toMinSpanTree();
LinkedList<Edge> edges= new LinkedList<Edge>(mst.getEdges());
// get actual nodes
g1.clearMarks();
for(Edge e:edges){
e.getStartnode().status=Node.BLACK;
e.getEndnode().status=Node.BLACK;
}
LinkedList<Node> nodes= new LinkedList<Node>(mst.nodes.values());
for(Node n:nodes)
Assert.assertTrue("Count to Edges is not correct:",
n.status==Node.BLACK);
} catch (IOException e1) {
e1.printStackTrace();
}
}
// Test if the MinSpanTree actually connects all nodes
@Test
public void testConnectivity() {
DiGraph g1;
try {
g1 = GraphIO.loadGraph("tests/testgraphen/test_kruskal01.txt");
// get mst
DiGraph mst =(DiGraph) g1.toMinSpanTree();
LinkedList<Edge> edges= new LinkedList<Edge>(mst.getEdges());
LinkedList<Node> nodes= new LinkedList<Node>(mst.nodes.values());
UnionFindSet<Node> ufs=new UnionFindSet<Node>();
ufs.add(nodes);
for(Edge e:edges)
ufs.union(e.getStartnode(),e.getEndnode());
Node expected=ufs.getRepresentative(nodes.get(0));
for(Node n:nodes){
Assert.assertTrue("MinSpanTree actually not connects all nodes",ufs.getRepresentative(n)==expected);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Test
public void testWrongGraph() {
boolean isSuccess=false;
DiGraph g1;
try {
g1 = GraphIO.loadGraph("tests/testgraphen/test_kruskal03.txt");
try{
g1.toMinSpanTree();
}
catch(RuntimeException e){
isSuccess=true;
}
} catch (IOException e1) {
e1.printStackTrace();
}
Assert.assertTrue("Graph error not caught!",isSuccess);
}
}
|
3e1819e89848358237f93f90518e3956ff7415ee | 2,480 | java | Java | src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java | phaser4/spring-data-dynamodb | 7ebb97aee17cf71189d04566cae1f0f5233aac4c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java | phaser4/spring-data-dynamodb | 7ebb97aee17cf71189d04566cae1f0f5233aac4c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/socialsignin/spring/data/dynamodb/repository/Query.java | phaser4/spring-data-dynamodb | 7ebb97aee17cf71189d04566cae1f0f5233aac4c | [
"Apache-2.0"
] | null | null | null | 38.75 | 143 | 0.758468 | 10,249 | /**
* Copyright © 2018 spring-data-dynamodb (https://github.com/boostchicken/spring-data-dynamodb)
*
* 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.socialsignin.spring.data.dynamodb.repository;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.socialsignin.spring.data.dynamodb.repository.QueryConstants.ConsistentReadMode;
import static org.socialsignin.spring.data.dynamodb.repository.QueryConstants.QUERY_LIMIT_UNLIMITED;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Query {
/**
* A string that identifies the attributes you want. To retrieve a single
* attribute, specify its name. For multiple attributes, the names must be
* comma-separated.
*
* @see <a href=
* "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ProjectionExpressions.html">Projection
* Expressions</a>
* @return comma-separated list of fields
*/
String fields() default "";
/**
* An integer to limit the number of elements returned.
*
* @see <a href=
* "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ProjectionExpressions.html">Projection
* Expressions</a>
* @return number of results to return
*/
int limit() default QUERY_LIMIT_UNLIMITED;
/**
* Override consistent read mode set in the DynamoDBMapper
*
* @see <a href=
* "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html">Read Consistency</a>
* @see <a href=
* "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptionalConfig.html">DynamoDBMapper Configuration</a>
* @return ConistentReadMode to enforce on query
*/
ConsistentReadMode consistentReads() default ConsistentReadMode.DEFAULT;
}
|
3e181a3d587f0476c0d0525beceddaf47a27dc34 | 301 | java | Java | src/main/java/edu/upenn/diffstream/matcher/RemoteMatcher.java | fniksic/diffstream | 82a7a6cf85e13f381cc9d87ac95a6de191c82148 | [
"MIT"
] | 6 | 2020-06-04T00:04:50.000Z | 2022-02-12T08:21:44.000Z | src/main/java/edu/upenn/diffstream/matcher/RemoteMatcher.java | fniksic/diffstream | 82a7a6cf85e13f381cc9d87ac95a6de191c82148 | [
"MIT"
] | 1 | 2020-11-26T00:11:22.000Z | 2020-12-02T03:44:24.000Z | src/main/java/edu/upenn/diffstream/matcher/RemoteMatcher.java | fniksic/diffstream | 82a7a6cf85e13f381cc9d87ac95a6de191c82148 | [
"MIT"
] | null | null | null | 27.363636 | 98 | 0.820598 | 10,250 | package edu.upenn.diffstream.matcher;
import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteMatcher<IN extends Serializable> extends Remote {
void processItem(IN item, boolean left) throws RemoteException, StreamsNotEquivalentException;
} |
3e181a74be11cdfb7543160fbaf92f3a49d54fb7 | 1,097 | java | Java | Hito 2/Tareas/Procesual/Ciudadano.java | Sejas24/prograIII | 99b385fbb6adeb32bd4c8d3ce6f0339e34bc2e30 | [
"MIT"
] | null | null | null | Hito 2/Tareas/Procesual/Ciudadano.java | Sejas24/prograIII | 99b385fbb6adeb32bd4c8d3ce6f0339e34bc2e30 | [
"MIT"
] | null | null | null | Hito 2/Tareas/Procesual/Ciudadano.java | Sejas24/prograIII | 99b385fbb6adeb32bd4c8d3ce6f0339e34bc2e30 | [
"MIT"
] | null | null | null | 32.264706 | 100 | 0.601641 | 10,251 | package Examen2;
public class Ciudadano implements LeerInterface{
private String primerNombre;
private String primerApellido;
private int ciNumber;
private String ciExt;
private int edad;
public Ciudadano() {
this.primerNombre = "";
this.primerApellido = "";
this.ciNumber = 0;
this.ciExt = "";
this.edad = 0;
}
public void Leer(){
System.out.printf("Ingrese Primer nombre: ");
this.primerNombre = LEER.next();
System.out.printf("Ingrese Primer apellido: ");
this.primerApellido = LEER.next();
System.out.printf("Ingrese Numero CI: ");
this.ciNumber = LEER.nextInt();
System.out.printf("Ingrese Extension CI: ");
this.ciExt = LEER.next();
System.out.printf("Ingrese Edad: ");
this.edad = LEER.nextInt();
}
public void Mostrar(){
System.out.printf("Nombre : %s, Apellido : %s, Numero CI: %d, Extension CI: %s,Edad: %d %s",
this.primerNombre,this.primerApellido,this.ciNumber,this.ciExt,this.edad, "\n");
}
}
|
3e181ac705b02ac1dc7ab203d99995a5e1d80756 | 2,508 | java | Java | BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/BaseClass.java | fossabot/sailfish-core | 2f8e94ff96cfe4aff3801d0896a90d73c9c6daa8 | [
"Apache-2.0"
] | 48 | 2018-12-27T10:17:27.000Z | 2019-10-23T04:35:17.000Z | BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/BaseClass.java | fossabot/sailfish-core | 2f8e94ff96cfe4aff3801d0896a90d73c9c6daa8 | [
"Apache-2.0"
] | 13 | 2019-12-17T10:41:03.000Z | 2022-02-26T17:09:18.000Z | BackEnd/Core/sailfish-core/src/main/java/com/exactpro/sf/scriptrunner/BaseClass.java | fossabot/sailfish-core | 2f8e94ff96cfe4aff3801d0896a90d73c9c6daa8 | [
"Apache-2.0"
] | 8 | 2019-12-18T05:32:30.000Z | 2022-03-13T13:03:49.000Z | 33.44 | 94 | 0.669458 | 10,252 | /******************************************************************************
* Copyright 2009-2018 Exactpro (Exactpro Systems Limited)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.exactpro.sf.scriptrunner;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.exactpro.sf.center.IVersion;
public abstract class BaseClass {
protected final String className;
protected final List<String> classAliases = new ArrayList<>();
protected final String classDescription;
protected final IVersion version;
protected final List<Method> classMethods = new ArrayList<>();
protected BaseClass(String className, String classDescription, IVersion version) {
this.className = className;
this.classDescription = classDescription;
this.version = version;
}
public String getClassName() {
return className;
}
public List<String> getClassAliases() {
return Collections.unmodifiableList(classAliases);
}
public String getClassDescription() {
return classDescription;
}
public List<Method> getClassMethods() {
// return new list to allow sorting in GUI
return new ArrayList<>(classMethods);
}
public IVersion getPlugin() {
return version;
}
@Override
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
builder.append("className", className);
builder.append("classAliases", classAliases);
builder.append("classDescription", classDescription);
builder.append("version", version);
builder.append("classMethods", classMethods);
return builder.toString();
}
}
|
3e181b8b5941afb53f7dd33bbdc47a684cd2a449 | 8,039 | java | Java | payments/src/main/java/com/rideaustin/service/farepayment/FarePaymentService.java | coopersystem-fsd/server | 24354717624c25b5d4faf0b7ea540e2742e8039f | [
"MIT"
] | 13 | 2020-08-20T23:51:13.000Z | 2021-08-23T17:47:14.000Z | payments/src/main/java/com/rideaustin/service/farepayment/FarePaymentService.java | coopersystem-fsd/server | 24354717624c25b5d4faf0b7ea540e2742e8039f | [
"MIT"
] | 3 | 2020-06-25T18:16:12.000Z | 2021-11-25T21:36:19.000Z | payments/src/main/java/com/rideaustin/service/farepayment/FarePaymentService.java | coopersystem-fsd/server | 24354717624c25b5d4faf0b7ea540e2742e8039f | [
"MIT"
] | 12 | 2020-06-16T20:42:18.000Z | 2022-03-10T21:45:39.000Z | 44.17033 | 202 | 0.783555 | 10,253 | package com.rideaustin.service.farepayment;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.joda.money.Money;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.rideaustin.Constants;
import com.rideaustin.model.Campaign;
import com.rideaustin.model.enums.PaymentStatus;
import com.rideaustin.model.enums.RideStatus;
import com.rideaustin.model.enums.SplitFareStatus;
import com.rideaustin.model.ride.FareDetails;
import com.rideaustin.model.ride.Ride;
import com.rideaustin.model.splitfare.FarePayment;
import com.rideaustin.repo.dsl.FarePaymentDslRepository;
import com.rideaustin.rest.exception.ConflictException;
import com.rideaustin.rest.model.FarePaymentDto;
import com.rideaustin.rest.model.PagingParams;
import com.rideaustin.service.FareService;
import com.rideaustin.service.FareService.CampaignCoverageResult;
import com.rideaustin.service.model.PendingPaymentDto;
import com.rideaustin.service.promocodes.PromocodeUseResult;
import com.rideaustin.utils.FareUtils;
import com.rideaustin.utils.SafeZeroUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Service
@Transactional
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class FarePaymentService {
private final FarePaymentDslRepository farePaymentDslRepository;
private final FareService fareService;
public FarePayment createFarePaymentForMainRider(Ride ride) throws ConflictException {
FarePayment alreadyCreatedFarePaymentForRider = farePaymentDslRepository.findFarePayment(ride.getId(), ride.getRider().getId());
if (null != alreadyCreatedFarePaymentForRider && alreadyCreatedFarePaymentForRider.isMainRider()) {
log.error("There was already main rider created for a ride (for proper rider). ");
return alreadyCreatedFarePaymentForRider;
} else if (null != alreadyCreatedFarePaymentForRider) {
throw new ConflictException("This ride has already created fare payment for ride main ride, but not as main rider");
}
Optional<FarePayment> existing = farePaymentDslRepository.findMainRiderFarePayment(ride.getId());
if (existing.isPresent()) {
throw new ConflictException("This ride has already created fare payment for other rider as main rider ");
}
FarePayment mainRiderFarePayment = FarePayment.builder()
.ride(ride)
.rider(ride.getRider())
.mainRider(true)
.splitStatus(SplitFareStatus.ACCEPTED)
.build();
mainRiderFarePayment = farePaymentDslRepository.save(mainRiderFarePayment);
return mainRiderFarePayment;
}
public List<PendingPaymentDto> listPendingPayments(long riderId) {
return farePaymentDslRepository.listPendingPaymentsForRider(riderId);
}
public void updateFarePayment(FarePayment farePayment) {
farePaymentDslRepository.save(farePayment);
}
public List<FarePayment> getAcceptedPaymentParticipants(Long rideId) {
return farePaymentDslRepository.findAcceptedFarePayments(rideId);
}
public List<FarePaymentDto> getAcceptedPaymentParticipantsInfo(Long rideId) {
return farePaymentDslRepository.findAcceptedFarePaymentInfo(rideId);
}
public Page<FarePayment> getRiderPaymentHistory(@Nonnull Long riderId, @Nullable RideStatus status, @Nonnull PagingParams paging) {
return farePaymentDslRepository.getRidePaymentHistoryFarePayment(riderId, status, paging);
}
public FarePaymentInfo createFarePaymentInfo(Ride ride, PromocodeUseResult promocodeUseResult, boolean useEstimate) throws ConflictException {
FarePaymentInfo info;
if (ride.isUserCancelled()) {
Optional<FareDetails> fareDetails = fareService.calculateFinalFare(ride, promocodeUseResult, ride.getPaymentStatus() == PaymentStatus.PREPAID_UPFRONT);
Money cancellationFee = fareDetails.map(FareDetails::getCancellationFee).orElse(Constants.ZERO_USD);
info = FarePaymentInfo.builder()
.primaryRiderFarePayment(getMainFarePayment(ride))
.secondaryRiderPayments(new ArrayList<>())
.farePerParticipants(cancellationFee)
.primaryRiderFare(cancellationFee)
.build();
} else {
List<FarePayment> paymentParticipants = getAcceptedPaymentParticipants(ride.getId());
ParticipantsFare participantsFare = calculateAmountToPayPerParticipant(ride, paymentParticipants, promocodeUseResult, useEstimate);
info = FarePaymentInfo.builder()
.primaryRiderFarePayment(getMainRiderFarePayment(paymentParticipants, ride))
.secondaryRiderPayments(getNoMainRiderFarePayments(paymentParticipants))
.farePerParticipants(participantsFare.getSecondaryRidersFare())
.primaryRiderFare(participantsFare.getPrimaryRiderFare())
.build();
}
return info;
}
private FarePayment getMainFarePayment(Ride ride) {
return farePaymentDslRepository.findFarePayment(ride.getId(), ride.getRider().getId());
}
private List<FarePayment> getNoMainRiderFarePayments(List<FarePayment> farePayments) {
return farePayments.stream().filter(fp -> !fp.isMainRider()).collect(Collectors.toList());
}
private FarePayment getMainRiderFarePayment(List<FarePayment> farePayments, Ride ride) throws ConflictException {
for (FarePayment fp : farePayments) {
if (fp.isMainRider()) {
if (!fp.getRider().equals(ride.getRider())) {
throw new ConflictException("Main rider on fare payment is different that main rider of ride");
}
return fp;
}
}
return null;
}
private ParticipantsFare calculateAmountToPayPerParticipant(Ride ride, List<FarePayment> allAcceptedFarePayments, PromocodeUseResult promocodeUseResult, boolean useEstimate) throws ConflictException {
if (allAcceptedFarePayments == null || allAcceptedFarePayments.isEmpty()) {
throw new ConflictException("No fare payment recorded");
}
final Optional<FareDetails> totalFareDetails = fareService.calculateTotalFare(ride, promocodeUseResult, false, useEstimate || ride.getPaymentStatus() == PaymentStatus.PREPAID_UPFRONT);
final CampaignCoverageResult campaignCoverageResult = fareService.checkCampaignCoverage(totalFareDetails.get(), ride);
Optional<FareDetails> fareDetails = fareService.calculateFinalFare(ride, promocodeUseResult, useEstimate || ride.getPaymentStatus() == PaymentStatus.PREPAID_UPFRONT);
Money noTipsCharge = fareDetails
.map(details -> details.getTotalCharge().minus(SafeZeroUtils.safeZero(details.getTip())))
.orElse(Constants.ZERO_USD);
Money secondary;
Money primary;
if (campaignCoverageResult.isCoveredByCampaign()) {
final Campaign campaign = campaignCoverageResult.getCampaignOptional().get();
secondary = FareUtils.adjustStripeChargeAmount(campaign.adjustTotalCharge(noTipsCharge));
primary = secondary;
} else {
secondary = FareUtils.adjustStripeChargeAmount(noTipsCharge.dividedBy(allAcceptedFarePayments.size(), Constants.ROUNDING_MODE));
primary = FareUtils.adjustStripeChargeAmount(secondary.plus(fareDetails.map(FareDetails::getTip).orElse(Constants.ZERO_USD)));
}
return new ParticipantsFare(primary, secondary);
}
public FarePayment getFarePaymentForRide(Ride ride) {
return farePaymentDslRepository.findFarePayment(ride.getId(), ride.getRider().getId());
}
@Getter
@Builder
public static class FarePaymentInfo {
private final FarePayment primaryRiderFarePayment;
private final List<FarePayment> secondaryRiderPayments;
private final Money farePerParticipants;
private final Money primaryRiderFare;
}
@Getter
@AllArgsConstructor
static class ParticipantsFare {
final Money primaryRiderFare;
final Money secondaryRidersFare;
}
}
|
3e181d65472b67dd46a65d72f951d0eabd864c3a | 5,440 | java | Java | xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java | fpapon/geronimo-xbean | e7ba34ac660ee89b234a10817a6c143ac01e7713 | [
"Apache-2.0"
] | 8 | 2015-05-03T01:21:07.000Z | 2021-11-07T21:04:20.000Z | xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java | fpapon/geronimo-xbean | e7ba34ac660ee89b234a10817a6c143ac01e7713 | [
"Apache-2.0"
] | 6 | 2015-03-18T15:25:37.000Z | 2021-07-21T09:47:51.000Z | xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java | fpapon/geronimo-xbean | e7ba34ac660ee89b234a10817a6c143ac01e7713 | [
"Apache-2.0"
] | 32 | 2015-02-23T19:44:14.000Z | 2021-12-23T02:33:30.000Z | 40.296296 | 128 | 0.62261 | 10,254 | /**
* 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.xbean.finder;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.xbean.finder.util.Files;
public final class ClassLoaders {
private static final boolean DONT_USE_GET_URLS = Boolean.getBoolean("xbean.finder.use.get-resources");
private static final ClassLoader SYSTEM = ClassLoader.getSystemClassLoader();
private static final boolean UNIX = !System.getProperty("os.name").toLowerCase().contains("win");
private static final Pattern MJAR_PATTERN = Pattern.compile(".*/META-INF/versions/[0-9]+/$");
public static Set<URL> findUrls(final ClassLoader classLoader) throws IOException {
if (classLoader == null || (SYSTEM.getParent() != null && classLoader == SYSTEM.getParent())) {
return Collections.emptySet();
}
final Set<URL> urls = new HashSet<URL>();
if (URLClassLoader.class.isInstance(classLoader) && !DONT_USE_GET_URLS) {
if (!isSurefire(classLoader)) {
for (final Collection<URL> item : Arrays.asList(
Arrays.asList(URLClassLoader.class.cast(classLoader).getURLs()), findUrls(classLoader.getParent()))) {
for (final URL url : item) {
addIfNotSo(urls, url);
}
}
} else { // http://jira.codehaus.org/browse/SUREFIRE-928 - we could reuse findUrlFromResources but this seems faster
urls.addAll(fromClassPath());
}
}
// DONT_USE_GET_URLS || java -jar xxx.jar and use MANIFEST.MF Class-Path?
// here perf is not an issue since we would either miss all the classpath or we have a single jar
if (urls.size() <= 1) {
final Set<URL> urlFromResources = findUrlFromResources(classLoader);
if (!urls.isEmpty()) {
final URL theUrl = urls.iterator().next();
if ("file".equals(theUrl.getProtocol())) { // theUrl can be file:xxxx but it is the same entry actually
urlFromResources.remove(new URL("jar:" + theUrl.toExternalForm() + "!/"));
}
}
urls.addAll(urlFromResources);
}
return urls;
}
private static void addIfNotSo(final Set<URL> urls, final URL url) {
if (UNIX && isNative(url)) {
return;
}
urls.add(url);
}
public static boolean isNative(final URL url) {
final File file = Files.toFile(url);
if (file != null) {
final String name = file.getName();
if (!name.endsWith(".jar") && !file.isDirectory()
&& name.contains(".so") && file.getAbsolutePath().startsWith("/usr/lib")) {
return true;
}
}
return false;
}
private static boolean isSurefire(ClassLoader classLoader) {
return System.getProperty("surefire.real.class.path") != null && classLoader == SYSTEM;
}
private static Collection<URL> fromClassPath() {
final String[] cp = System.getProperty("java.class.path").split(System.getProperty("path.separator", ":"));
final Set<URL> urls = new HashSet<URL>();
for (final String path : cp) {
try {
urls.add(new File(path).toURI().toURL()); // don't build the url in plain String since it is not portable
} catch (final MalformedURLException e) {
// ignore
}
}
return urls;
}
public static Set<URL> findUrlFromResources(final ClassLoader classLoader) throws IOException {
final Set<URL> set = new HashSet<URL>();
for (final URL url : Collections.list(classLoader.getResources("META-INF"))) {
final String externalForm = url.toExternalForm();
set.add(new URL(externalForm.substring(0, externalForm.lastIndexOf("META-INF"))));
}
for (final URL url : Collections.list(classLoader.getResources(""))) {
final String externalForm = url.toExternalForm();
if (MJAR_PATTERN.matcher(externalForm).matches()) {
set.add(new URL(externalForm.substring(0, externalForm.lastIndexOf("META-INF"))));
} else {
set.add(url);
}
}
return set;
}
private ClassLoaders() {
// no-op
}
}
|
3e181ed405a1f25699cb705cfd3e34d1c566472f | 11,900 | java | Java | sctp-mis/src/main/java/org/cga/sctp/mis/transfers/agencies/TransferAgenciesController.java | CGATechnologies/sctp2 | afd2bc8f3012ac26441a92c1da1c235030d0bab3 | [
"BSD-3-Clause"
] | null | null | null | sctp-mis/src/main/java/org/cga/sctp/mis/transfers/agencies/TransferAgenciesController.java | CGATechnologies/sctp2 | afd2bc8f3012ac26441a92c1da1c235030d0bab3 | [
"BSD-3-Clause"
] | null | null | null | sctp-mis/src/main/java/org/cga/sctp/mis/transfers/agencies/TransferAgenciesController.java | CGATechnologies/sctp2 | afd2bc8f3012ac26441a92c1da1c235030d0bab3 | [
"BSD-3-Clause"
] | null | null | null | 47.6 | 135 | 0.694874 | 10,255 | /*
* BSD 3-Clause License
*
* Copyright (c) 2022, CGATechnologies
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.cga.sctp.mis.transfers.agencies;
import org.cga.sctp.location.Location;
import org.cga.sctp.location.LocationService;
import org.cga.sctp.location.LocationType;
import org.cga.sctp.mis.core.BaseController;
import org.cga.sctp.mis.core.templating.Booleans;
import org.cga.sctp.mis.core.templating.SelectOptionItem;
import org.cga.sctp.transfers.agencies.TransferAgency;
import org.cga.sctp.transfers.agencies.TransferAgencyAlreadyAssignedException;
import org.cga.sctp.transfers.agencies.TransferAgencyServiceImpl;
import org.cga.sctp.transfers.agencies.TransferMethod;
import org.cga.sctp.user.AdminAccessOnly;
import org.cga.sctp.user.AdminAndStandardAccessOnly;
import org.cga.sctp.user.AuthenticatedUser;
import org.cga.sctp.user.AuthenticatedUserDetails;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
@Controller
@RequestMapping("/transfers/agencies")
public class TransferAgenciesController extends BaseController {
@Autowired
private TransferAgencyServiceImpl transferAgencyService;
@Autowired
private LocationService locationService;
@GetMapping
public ModelAndView listAgencies() {
return view("transfers/agencies/list")
.addObject("transferAgencies", transferAgencyService.fetchAllTransferAgencies());
}
@GetMapping("/new")
@AdminAccessOnly
public ModelAndView createPage() {
List<Location> locations = locationService.getActiveDistricts();
return view("/transfers/agencies/new")
.addObject("options", Booleans.VALUES)
.addObject("locations", locations);
}
@GetMapping("/search")
public ResponseEntity<?> searchAgencies(@RequestParam("transferMethod") String transferMethod) {
List<TransferAgency> agencies = Collections.emptyList();
if (transferMethod != null) {
agencies = transferAgencyService.findAllByTransferModality(transferMethod);
}
List<SelectOptionItem> agencyList = agencies.stream()
.map(agency -> {
return new SelectOptionItem(agency.getId(),agency.getName());
})
.toList();
return ResponseEntity.ok(agencyList);
}
@PostMapping("/new")
@AdminAccessOnly
public ModelAndView processCreatePage(@AuthenticationPrincipal String username,
@Validated @ModelAttribute TransferAgencyForm form,
BindingResult result,
RedirectAttributes attributes) {
if (result.hasErrors()) {
setWarningFlashMessage("Failed to save Agency please fix the errors on the form", attributes);
LoggerFactory.getLogger(getClass()).error("Failed to update agency: {}", result.getAllErrors());
return view("transfers/agencies/new")
.addObject("options", Booleans.VALUES)
.addObject("form", form);
}
TransferAgency transferAgency = new TransferAgency();
transferAgency.setName(form.getName());
transferAgency.setActive(form.isActive().value);
transferAgency.setAddress(form.getAddress());
transferAgency.setRepresentativeName(form.getRepresentativeName());
transferAgency.setRepresentativeEmail(form.getRepresentativeEmail());
transferAgency.setWebsite(form.getWebsite());
transferAgency.setBranch(form.getBranch());
transferAgency.setCreatedAt(LocalDate.now());
transferAgency.setModifiedAt(transferAgency.getCreatedAt());
publishGeneralEvent("%s created agency: name=%s", username, transferAgency.getName());
transferAgencyService.getTransferAgenciesRepository().save(transferAgency);
return redirect("/transfers/agencies");
}
@GetMapping("/{transfer-agency-id}/edit")
@AdminAccessOnly
public ModelAndView viewEditPage(@PathVariable("transfer-agency-id") Long id,
@ModelAttribute("form") TransferAgencyForm form,
BindingResult result,
RedirectAttributes attributes) {
TransferAgency transferAgency = transferAgencyService.getTransferAgenciesRepository().getOne(id);
if (transferAgency == null) {
setDangerFlashMessage("Transfer Agency does not exist", attributes);
return redirect("/transfers/agencies");
}
form.setId(transferAgency.getId());
form.setName(transferAgency.getName());
form.setActive(Booleans.of(transferAgency.getActive()));
form.setLocationId(transferAgency.getLocationId());
form.setWebsite(transferAgency.getWebsite());
form.setBranch(transferAgency.getBranch());
form.setPhone(transferAgency.getPhone());
form.setAddress(transferAgency.getAddress());
form.setRepresentativeName(transferAgency.getRepresentativeName());
form.setRepresentativeEmail(transferAgency.getRepresentativeEmail());
form.setRepresentativePhone(transferAgency.getRepresentativePhone());
List<Location> locations = locationService.getActiveDistricts();
return view("/transfers/agencies/edit")
.addObject("options", Booleans.VALUES)
.addObject("locations", locations);
}
@PostMapping("/{transfer-agency-id}/edit")
@AdminAccessOnly
public ModelAndView processEditPage(@AuthenticationPrincipal String username,
@PathVariable("transfer-agency-id") Long id,
@Validated @ModelAttribute TransferAgencyForm form,
BindingResult result,
RedirectAttributes attributes) {
TransferAgency transferAgency = transferAgencyService.getTransferAgenciesRepository().getOne(id);
if (result.hasErrors()) {
setWarningFlashMessage("Failed to Update Agency please fix the errors on the form", attributes);
LoggerFactory.getLogger(getClass()).error("Failed to update agency: {}", attributes);
return view("transfers/agencies/new")
.addObject("options", Booleans.VALUES)
.addObject("form", form);
}
transferAgency.setName(form.getName());
transferAgency.setActive(form.isActive().value);
transferAgency.setAddress(form.getAddress());
transferAgency.setPhone(form.getPhone());
transferAgency.setRepresentativeName(form.getRepresentativeName());
transferAgency.setRepresentativeEmail(form.getRepresentativeEmail());
transferAgency.setRepresentativePhone(form.getRepresentativePhone());
transferAgency.setWebsite(form.getWebsite());
transferAgency.setBranch(form.getBranch());
transferAgency.setLocationId(form.getLocationId());
transferAgency.setModifiedAt(LocalDate.now());
publishGeneralEvent("%s updated agency: name=%s", username, transferAgency.getName());
transferAgencyService.getTransferAgenciesRepository().save(transferAgency);
return redirect(String.format("/transfers/agencies/%s/view",id));
}
@GetMapping("/{transfer-agency-id}/view")
public ModelAndView viewPage(@PathVariable("transfer-agency-id") Long id) {
TransferAgency transferAgency = transferAgencyService.getTransferAgenciesRepository().getOne(id);
return view("/transfers/agencies/view")
.addObject("transferAgency", transferAgency);
}
@GetMapping("/assign")
@AdminAccessOnly
public ModelAndView viewAssignPage() {
List<TransferAgency> transferAgencies = transferAgencyService.fetchAllTransferAgencies();
List<Location> initialLocations = locationService.getActiveDistricts();
return view("/transfers/agencies/assign")
.addObject("transferAgencies", transferAgencies)
.addObject("transferMethodOptions", TransferMethod.values())
.addObject("geolocationTypes", LocationType.values())
.addObject("options", Booleans.VALUES)
// Initially load districts as the locations but locations will be changed by geolocation types
.addObject("locations", initialLocations);
}
@PostMapping("/assign")
@AdminAndStandardAccessOnly
public ModelAndView handleAssignPage(@AuthenticatedUserDetails AuthenticatedUser user,
@Validated @ModelAttribute TransferAgencyAssignmentForm form,
BindingResult result,
RedirectAttributes attributes) {
if (result.hasErrors()) {
setWarningFlashMessage("Invalid request, please fix errors and try again", attributes);
LoggerFactory.getLogger(getClass()).info("Failed to assign {}", form);
return redirect("/transfers/agencies/assign");
}
TransferAgency transferAgency = transferAgencyService.findActiveTransferAgencyById(form.getTransferAgencyId());
Location location = locationService.findById(form.getLocationId());
try {
transferAgencyService.assignAgency(transferAgency, location, form.getTransferMethod(), user.id());
} catch(TransferAgencyAlreadyAssignedException e) {
setDangerFlashMessage("Location already has an assigned Transfer agency, please use 'Change Transfer Agency'", attributes);
return redirect("/transfers/agencies/assign");
}
return redirect("/transfers/agencies/assign");
}
}
|
3e181f086053f5cf3f7e04ebce697ce21955c48e | 5,053 | java | Java | Source/Java/CoreRouter/main/src/java/gov/va/med/imaging/core/router/commands/dicom/importer/GetImporterVersionCompatibleCommandImpl.java | VHAINNOVATIONS/Telepathology | 989c06ccc602b0282c58c4af3455c5e0a33c8593 | [
"Apache-2.0"
] | 3 | 2015-04-09T14:29:34.000Z | 2015-11-10T19:39:06.000Z | Source/Java/CoreRouter/main/src/java/gov/va/med/imaging/core/router/commands/dicom/importer/GetImporterVersionCompatibleCommandImpl.java | VHAINNOVATIONS/Telepathology | 989c06ccc602b0282c58c4af3455c5e0a33c8593 | [
"Apache-2.0"
] | null | null | null | Source/Java/CoreRouter/main/src/java/gov/va/med/imaging/core/router/commands/dicom/importer/GetImporterVersionCompatibleCommandImpl.java | VHAINNOVATIONS/Telepathology | 989c06ccc602b0282c58c4af3455c5e0a33c8593 | [
"Apache-2.0"
] | 9 | 2015-04-14T14:11:09.000Z | 2018-09-26T07:48:23.000Z | 30.624242 | 133 | 0.735998 | 10,256 | /**
*
*/
package gov.va.med.imaging.core.router.commands.dicom.importer;
import gov.va.med.RoutingToken;
import gov.va.med.imaging.artifactsource.ResolvedArtifactSource;
import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException;
import gov.va.med.imaging.core.interfaces.exceptions.MethodException;
import gov.va.med.imaging.core.router.AbstractDataSourceExceptionHandler;
import gov.va.med.imaging.datasource.DataSourceProvider;
import gov.va.med.imaging.datasource.DicomImporterDataSourceSpi;
import gov.va.med.imaging.datasource.StudyGraphDataSourceSpi;
import gov.va.med.imaging.exchange.enums.SiteConnectivityStatus;
import gov.va.med.imaging.transactioncontext.TransactionContext;
import gov.va.med.imaging.transactioncontext.TransactionContextFactory;
import java.net.URL;
import java.util.List;
/**
* @author vhaiswbeckec
*
*/
public class GetImporterVersionCompatibleCommandImpl
extends AbstractDataSourceExceptionHandler<String>
{
private static final long serialVersionUID = 3845559383784181438L;
private final RoutingToken routingToken;
/**
* @param router
* @param accessibilityDate
* @param priority
* @param processingTargetCommencementDate
* @param processingDurationEstimate
*/
public GetImporterVersionCompatibleCommandImpl(RoutingToken routingToken)
{
super();
this.routingToken = routingToken;
}
public RoutingToken getRoutingToken()
{
return this.routingToken;
}
public String getSiteNumber()
{
return this.getRoutingToken().getRepositoryUniqueId();
}
/* (non-Javadoc)
* @see gov.va.med.imaging.core.router.AsynchronousCommandProcessor#callInTransactionContext()
*/
@Override
public String callSynchronouslyInTransactionContext()
throws MethodException
{
TransactionContext context = TransactionContextFactory.get();
getLogger().info( "isSiteAvailable - Transaction ID [" + context.getTransactionId() + "], For site '" + getSiteNumber() + "'." );
ResolvedArtifactSource resolvedSite = getCommandContext().getResolvedArtifactSource(getRoutingToken());
if(resolvedSite == null)
{
getLogger().error("Unable to find site with site number '" + getSiteNumber() +
"', verify this is a valid VA site number. Cannot retrieve data from this site.");
return "false";
}
context.setServicedSource( getRoutingToken().toRoutingTokenString() );
List<URL> metadataUrls = resolvedSite.getMetadataUrls();
if(metadataUrls == null || metadataUrls.isEmpty())
{
getLogger().error("The site '" + getSiteNumber() + "' has no available interface URLs.\n" +
"Please check that the protocol handlers are properly installed and that the \n" +
"protocol preferences for the site specify valid protocols.");
return "false";
}
Exception lastException = null;
// try each of the configured protocols in turn
for(URL url : metadataUrls )
{
try
{
DicomImporterDataSourceSpi dataSourceSpi = getSpi(resolvedSite, url.getProtocol());
if(dataSourceSpi != null)
{
TransactionContextFactory.get().setDatasourceProtocol(url.getProtocol());
return "true";
}
}
catch(ConnectionException cX)
{
getLogger().error(
"Failed to contact site'" + getSiteNumber() + "' using '" + url.toExternalForm() + "'.\n" +
"Exception details follow.",
cX);
lastException = cX;
}
}
if(lastException != null)
{
if(lastException.getClass() == ConnectionException.class)
{
getLogger().info("Unable to contact data source for site '" + getSiteNumber() + "' using ViX, returning Datasource Unavailable");
return "false";
}
}
return "false";
}
private DicomImporterDataSourceSpi getSpi(ResolvedArtifactSource resolvedSite, String protocol)
throws ConnectionException
{
if(canGenerateNewToken())
return getProvider().createVersionableDataSource(DicomImporterDataSourceSpi.class, resolvedSite, protocol, this);
else
{
DataSourceProvider provider = getProvider();
DicomImporterDataSourceSpi s = provider.createVersionableDataSource(DicomImporterDataSourceSpi.class, resolvedSite, protocol);
return s;
//return getProvider().createDataSource(getSpiClass(), url, resolvedSite);
}
}
/* (non-Javadoc)
* @see gov.va.med.imaging.core.router.AsynchronousCommandProcessor#parameterToString()
*/
@Override
protected String parameterToString()
{
return this.getRoutingToken().toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((this.routingToken == null) ? 0 : this.routingToken.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
final GetImporterVersionCompatibleCommandImpl other = (GetImporterVersionCompatibleCommandImpl) obj;
if (this.routingToken == null)
{
if (other.routingToken != null)
return false;
}
else if (!this.routingToken.equals(other.routingToken))
return false;
return true;
}
}
|
3e181f1adc299e8b520ec2205af2e81383480600 | 312 | java | Java | auth-service/src/main/java/com/springboot/cloud/domain/UserRoleParam.java | lirisheng123/mall | 2981dcbb9d8ed81c75a00a53eba1ef38ecac46b5 | [
"Apache-2.0"
] | 1 | 2022-03-29T15:04:58.000Z | 2022-03-29T15:04:58.000Z | auth-service/src/main/java/com/springboot/cloud/domain/UserRoleParam.java | lirisheng123/mall | 2981dcbb9d8ed81c75a00a53eba1ef38ecac46b5 | [
"Apache-2.0"
] | null | null | null | auth-service/src/main/java/com/springboot/cloud/domain/UserRoleParam.java | lirisheng123/mall | 2981dcbb9d8ed81c75a00a53eba1ef38ecac46b5 | [
"Apache-2.0"
] | null | null | null | 15.6 | 45 | 0.711538 | 10,257 | package com.springboot.cloud.domain;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/**
* @Author: lirisheng
* @Date: 2021/2/21 20:39
* @Version 1.0
*/
@Data
@ToString(callSuper=true)
public class UserRoleParam extends MallUser {
List<Long> roleIds;
List<String> roleNames;
}
|
3e181f57424a120e76ac6624d21d8edccc9c2301 | 11,234 | java | Java | provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java | valtri/midpoint | 7ea177966318dea24346a20af82140e96c6f08b2 | [
"Apache-2.0"
] | 1 | 2019-06-25T16:11:25.000Z | 2019-06-25T16:11:25.000Z | provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java | valtri/midpoint | 7ea177966318dea24346a20af82140e96c6f08b2 | [
"Apache-2.0"
] | null | null | null | provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java | valtri/midpoint | 7ea177966318dea24346a20af82140e96c6f08b2 | [
"Apache-2.0"
] | null | null | null | 36.122186 | 122 | 0.785829 | 10,258 | /*
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.provisioning.impl.dummy;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.Collection;
import java.util.List;
import com.evolveum.midpoint.schema.processor.ObjectFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.SchemaTestConstants;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.DummyResourceContoller;
import com.evolveum.midpoint.test.IntegrationTestTools;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationProvisioningScriptsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
/**
* The test of Provisioning service on the API level. The test is using dummy
* resource for speed and flexibility.
*
* @author Radovan Semancik
*
*/
@ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml")
@DirtiesContext
public class TestDummySecurity extends AbstractDummyTest {
private static final Trace LOGGER = TraceManager.getTrace(TestDummySecurity.class);
private String willIcfUid;
@Test
public void test100AddAccountDrink() throws Exception {
final String TEST_NAME = "test100AddAccountDrink";
TestUtil.displayTestTitle(TEST_NAME);
// GIVEN
Task syncTask = taskManager.createTaskInstance(TestDummySecurity.class.getName()
+ "." + TEST_NAME);
OperationResult result = new OperationResult(TestDummySecurity.class.getName()
+ "." + TEST_NAME);
syncServiceMock.reset();
PrismObject<ShadowType> account = prismContext.parseObject(ACCOUNT_WILL_FILE);
account.checkConsistence();
setAttribute(account, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "water");
display("Adding shadow", account);
try {
// WHEN
provisioningService.addObject(account, null, null, syncTask, result);
AssertJUnit.fail("Unexpected success");
} catch (SecurityViolationException e) {
// This is expected
display("Expected exception", e);
}
}
private <T> void setAttribute(PrismObject<ShadowType> account, String attrName, T val) throws SchemaException {
PrismContainer<Containerable> attrsCont = account.findContainer(ShadowType.F_ATTRIBUTES);
ResourceAttribute<T> attr = ObjectFactory.createResourceAttribute(
dummyResourceCtl.getAttributeQName(attrName), null, prismContext);
attr.setRealValue(val);
attrsCont.add(attr);
}
@Test
public void test199AddAccount() throws Exception {
final String TEST_NAME = "test199AddAccount";
TestUtil.displayTestTitle(TEST_NAME);
// GIVEN
Task syncTask = taskManager.createTaskInstance(TestDummySecurity.class.getName()
+ "." + TEST_NAME);
OperationResult result = new OperationResult(TestDummySecurity.class.getName()
+ "." + TEST_NAME);
syncServiceMock.reset();
PrismObject<ShadowType> account = prismContext.parseObject(ACCOUNT_WILL_FILE);
account.checkConsistence();
setAttribute(account, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "At the moment?");
setAttribute(account, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Eunuch");
display("Adding shadow", account);
// WHEN
provisioningService.addObject(account, null, null, syncTask, result);
// THEN
PrismObject<ShadowType> accountProvisioning = provisioningService.getObject(ShadowType.class,
ACCOUNT_WILL_OID, null, syncTask, result);
display("Account provisioning", accountProvisioning);
willIcfUid = getIcfUid(accountProvisioning);
}
@Test
public void test200ModifyAccountDrink() throws Exception {
final String TEST_NAME = "test200ModifyAccountDrink";
TestUtil.displayTestTitle(TEST_NAME);
Task task = taskManager.createTaskInstance(TestDummy.class.getName()
+ "." + TEST_NAME);
OperationResult result = task.getResult();
syncServiceMock.reset();
ObjectDelta<ShadowType> delta = prismContext.deltaFactory().object().createModificationReplaceProperty(ShadowType.class,
ACCOUNT_WILL_OID,
dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME),
"RUM");
display("ObjectDelta", delta);
delta.checkConsistence();
// WHEN
provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(),
new OperationProvisioningScriptsType(), null, task, result);
// THEN
result.computeStatus();
display("modifyObject result", result);
TestUtil.assertSuccess(result);
delta.checkConsistence();
assertDummyAccountAttributeValues(ACCOUNT_WILL_USERNAME, willIcfUid,
DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "RUM");
syncServiceMock.assertNotifySuccessOnly();
}
@Test
public void test201ModifyAccountGossip() throws Exception {
final String TEST_NAME = "test201ModifyAccountGossip";
TestUtil.displayTestTitle(TEST_NAME);
Task task = taskManager.createTaskInstance(TestDummy.class.getName()
+ "." + TEST_NAME);
OperationResult result = task.getResult();
syncServiceMock.reset();
ObjectDelta<ShadowType> delta = prismContext.deltaFactory().object().createModificationReplaceProperty(ShadowType.class,
ACCOUNT_WILL_OID,
dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME),
"pirate");
display("ObjectDelta", delta);
delta.checkConsistence();
// WHEN
provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(),
new OperationProvisioningScriptsType(), null, task, result);
// THEN
result.computeStatus();
display("modifyObject result", result);
TestUtil.assertSuccess(result);
delta.checkConsistence();
assertDummyAccountAttributeValues(ACCOUNT_WILL_USERNAME, willIcfUid,
DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "pirate");
syncServiceMock.assertNotifySuccessOnly();
}
@Test
public void test210ModifyAccountQuote() throws Exception {
final String TEST_NAME = "test210ModifyAccountQuote";
TestUtil.displayTestTitle(TEST_NAME);
Task task = taskManager.createTaskInstance(TestDummy.class.getName()
+ "." + TEST_NAME);
OperationResult result = task.getResult();
syncServiceMock.reset();
ObjectDelta<ShadowType> delta = prismContext.deltaFactory().object().createModificationReplaceProperty(ShadowType.class,
ACCOUNT_WILL_OID,
dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME),
"eh?");
display("ObjectDelta", delta);
delta.checkConsistence();
try {
// WHEN
provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(),
new OperationProvisioningScriptsType(), null, task, result);
AssertJUnit.fail("Unexpected success");
} catch (SecurityViolationException e) {
// This is expected
display("Expected exception", e);
}
}
@Test
public void test300GetAccount() throws Exception {
final String TEST_NAME = "test300GetAccount";
TestUtil.displayTestTitle(TEST_NAME);
// GIVEN
OperationResult result = new OperationResult(TestDummy.class.getName()
+ "." + TEST_NAME);
// WHEN
PrismObject<ShadowType> shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, result);
// THEN
result.computeStatus();
display("getObject result", result);
TestUtil.assertSuccess(result);
display("Retrieved account shadow", shadow);
assertNotNull("No dummy account", shadow);
checkAccountWill(shadow, result);
checkUniqueness(shadow);
}
@Test
public void test310SearchAllShadows() throws Exception {
final String TEST_NAME = "test310SearchAllShadows";
TestUtil.displayTestTitle(TEST_NAME);
// GIVEN
OperationResult result = new OperationResult(TestDummy.class.getName()
+ "." + TEST_NAME);
ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType,
SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext);
display("All shadows query", query);
// WHEN
List<PrismObject<ShadowType>> allShadows = provisioningService.searchObjects(ShadowType.class,
query, null, null, result);
// THEN
result.computeStatus();
display("searchObjects result", result);
TestUtil.assertSuccess(result);
display("Found " + allShadows.size() + " shadows");
assertFalse("No shadows found", allShadows.isEmpty());
checkUniqueness(allShadows);
for (PrismObject<ShadowType> shadow: allShadows) {
assertNoAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME);
assertNoAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME);
}
assertEquals("Wrong number of results", 2, allShadows.size());
}
// TODO: search
private void checkAccountWill(PrismObject<ShadowType> shadow, OperationResult result) {
Collection<ResourceAttribute<?>> attributes = ShadowUtil.getAttributes(shadow);
assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Flying Dutchman");
assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "Sword", "LOVE");
assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42);
assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "RUM");
assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "At the moment?");
assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Will Turner");
assertNoAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME);
assertNoAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME);
assertEquals("Unexpected number of attributes", 8, attributes.size());
}
}
|
3e181f9190ff4603616a3e64c74ed279f6d47f03 | 6,483 | java | Java | services/xkms/xkms-itests/src/test/java/org/apache/cxf/xkms/itests/handlers/validator/ValidatorCRLTest.java | keep-sunshine/cxf | 039e1dec778efffd6af4523f88d8638732afb637 | [
"Apache-2.0"
] | 839 | 2015-01-01T15:33:21.000Z | 2022-03-31T02:40:34.000Z | services/xkms/xkms-itests/src/test/java/org/apache/cxf/xkms/itests/handlers/validator/ValidatorCRLTest.java | keep-sunshine/cxf | 039e1dec778efffd6af4523f88d8638732afb637 | [
"Apache-2.0"
] | 399 | 2015-01-07T19:59:38.000Z | 2022-03-30T21:56:27.000Z | services/xkms/xkms-itests/src/test/java/org/apache/cxf/xkms/itests/handlers/validator/ValidatorCRLTest.java | keep-sunshine/cxf | 039e1dec778efffd6af4523f88d8638732afb637 | [
"Apache-2.0"
] | 1,581 | 2015-01-01T02:22:05.000Z | 2022-03-31T13:29:27.000Z | 43.510067 | 107 | 0.747493 | 10,259 | /**
* 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.cxf.xkms.itests.handlers.validator;
import java.io.InputStream;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.UUID;
import javax.xml.bind.JAXBElement;
import org.apache.cxf.xkms.handlers.XKMSConstants;
import org.apache.cxf.xkms.itests.BasicIntegrationTest;
import org.apache.cxf.xkms.model.xkms.KeyBindingEnum;
import org.apache.cxf.xkms.model.xkms.MessageAbstractType;
import org.apache.cxf.xkms.model.xkms.QueryKeyBindingType;
import org.apache.cxf.xkms.model.xkms.ReasonEnum;
import org.apache.cxf.xkms.model.xkms.StatusType;
import org.apache.cxf.xkms.model.xkms.ValidateRequestType;
import org.apache.cxf.xkms.model.xmldsig.KeyInfoType;
import org.apache.cxf.xkms.model.xmldsig.X509DataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
@RunWith(PaxExam.class)
public class ValidatorCRLTest extends BasicIntegrationTest {
private static final String PATH_TO_RESOURCES = "/data/xkms/certificates/";
private static final org.apache.cxf.xkms.model.xmldsig.ObjectFactory DSIG_OF =
new org.apache.cxf.xkms.model.xmldsig.ObjectFactory();
private static final org.apache.cxf.xkms.model.xkms.ObjectFactory XKMS_OF =
new org.apache.cxf.xkms.model.xkms.ObjectFactory();
private static final Logger LOG = LoggerFactory.getLogger(ValidatorCRLTest.class);
@Configuration
public Option[] getConfig() {
return new Option[] {
CoreOptions.composite(super.getConfig()),
copy("data/xkms/certificates/crls/wss40CACRL.cer"),
editConfigurationFilePut("etc/org.apache.cxf.xkms.cfg", "xkms.enableRevocation", "true")
};
}
@Test
public void testValidCertWithCRL() throws CertificateException {
X509Certificate wss40Certificate = readCertificate("wss40.cer");
ValidateRequestType request = prepareValidateXKMSRequest(wss40Certificate);
StatusType result = doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID, result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(), result
.getValidReason().get(0));
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(), result
.getValidReason().get(1));
}
@Test
public void testRevokedCertificate() throws CertificateException {
X509Certificate wss40Certificate = readCertificate("wss40rev.cer");
ValidateRequestType request = prepareValidateXKMSRequest(wss40Certificate);
StatusType result = doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID, result.getStatusValue());
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(), result
.getInvalidReason().get(0));
}
/*
* Method is taken from {@link org.apache.cxf.xkms.client.XKMSInvoker}.
*/
private ValidateRequestType prepareValidateXKMSRequest(X509Certificate cert) {
JAXBElement<byte[]> x509Cert;
try {
x509Cert = DSIG_OF.createX509DataTypeX509Certificate(cert.getEncoded());
} catch (CertificateEncodingException e) {
throw new IllegalArgumentException(e);
}
X509DataType x509DataType = DSIG_OF.createX509DataType();
x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().add(x509Cert);
JAXBElement<X509DataType> x509Data = DSIG_OF.createX509Data(x509DataType);
KeyInfoType keyInfoType = DSIG_OF.createKeyInfoType();
keyInfoType.getContent().add(x509Data);
QueryKeyBindingType queryKeyBindingType = XKMS_OF.createQueryKeyBindingType();
queryKeyBindingType.setKeyInfo(keyInfoType);
ValidateRequestType validateRequestType = XKMS_OF.createValidateRequestType();
setGenericRequestParams(validateRequestType);
validateRequestType.setQueryKeyBinding(queryKeyBindingType);
// temporary
validateRequestType.setId(cert.getSubjectDN().toString());
return validateRequestType;
}
private void setGenericRequestParams(MessageAbstractType request) {
request.setService(XKMSConstants.XKMS_ENDPOINT_NAME);
request.setId(UUID.randomUUID().toString());
}
private X509Certificate readCertificate(String path) throws CertificateException {
InputStream inputStream = ValidatorCRLTest.class.getResourceAsStream(PATH_TO_RESOURCES + path);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate)cf.generateCertificate(inputStream);
}
private StatusType doValidate(ValidateRequestType request) {
try {
return xkmsService.validate(request).getKeyBinding().get(0).getStatus();
} catch (Exception e) {
// Avoid serialization problems for some exceptions when transported by pax exam
LOG.error(e.getMessage(), e);
throw new RuntimeException(e.getMessage());
}
}
}
|
3e181fd4904db97fc6a3670b83fe5cb469b6a1fd | 2,021 | java | Java | src/game/Window.java | luismy10/Frogger-2D | 1970bd8b5c1d989c8534bd679f5a95138ddcb161 | [
"MIT"
] | null | null | null | src/game/Window.java | luismy10/Frogger-2D | 1970bd8b5c1d989c8534bd679f5a95138ddcb161 | [
"MIT"
] | null | null | null | src/game/Window.java | luismy10/Frogger-2D | 1970bd8b5c1d989c8534bd679f5a95138ddcb161 | [
"MIT"
] | null | null | null | 39.627451 | 121 | 0.576447 | 10,260 | package game;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Window {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame window = new JFrame("Frogger 2D");
window.getContentPane().setBackground(new Color(0x194894));
window.setUndecorated(false);
window.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
WindowCanvas windowadapter = new WindowCanvas();
window.getContentPane().setPreferredSize(new Dimension(WindowCanvas.WIDTHCANVAS, WindowCanvas.HEIGHTCANVAS));
window.getContentPane().setLayout(null);
window.getContentPane().add(windowadapter);
// window.setExtendedState(JFrame.MAXIMIZED_BOTH);
window.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
windowadapter.setLocation((window.getContentPane().getSize().width - windowadapter.getWidth()) / 2,
(window.getContentPane().getSize().height - windowadapter.getHeight()) / 2);
if(window.getExtendedState() == 6){
window.getContentPane().setBackground(new Color(0x194894));
window.getContentPane().repaint();
window.repaint();
}
}
});
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
windowadapter.start();
});
}
}
|
3e182000f7e8f96d68cd29547fa7912067bd2677 | 3,465 | java | Java | cmeditor/CMEditor.java | renanrcrr/concept-map-editor | 98a679fc3ea623556e5a91039c9c53b56738c0f9 | [
"MIT"
] | 1 | 2020-01-03T10:39:49.000Z | 2020-01-03T10:39:49.000Z | cmeditor/CMEditor.java | renanrcrr/concept-map-editor | 98a679fc3ea623556e5a91039c9c53b56738c0f9 | [
"MIT"
] | null | null | null | cmeditor/CMEditor.java | renanrcrr/concept-map-editor | 98a679fc3ea623556e5a91039c9c53b56738c0f9 | [
"MIT"
] | null | null | null | 30.663717 | 71 | 0.773449 | 10,261 | package cmeditor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.ToolTipManager;
import javax.swing.UIManager;
import cmeditor.desenho.AreaDesenho;
import cmeditor.gui.Acoes;
import cmeditor.gui.BarraFerramentas;
import cmeditor.gui.BarraMenus;
import cmeditor.gui.dialogo.Dialogos;
import cmeditor.gui.dialogo.PainelPreferencias;
public class CMEditor extends JFrame
implements PropertyChangeListener, WindowListener {
Acoes acoes;
AreaDesenho areaDesenho;
BarraFerramentas barraFerramentas;
BarraMenus barraMenus;
public CMEditor() throws HeadlessException {
super();
this.setTitle("CMEditor");
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Dimension dimensao = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(dimensao.width, dimensao.height - 30);
this.getContentPane().setLayout(new BorderLayout());
areaDesenho = new AreaDesenho();
this.getContentPane().add(areaDesenho.pegaBarrasRolagem());
acoes = new Acoes(areaDesenho);
areaDesenho.mudaAcoes(acoes);
barraMenus = new BarraMenus(acoes);
this.setJMenuBar(barraMenus);
barraFerramentas = new BarraFerramentas(acoes);
this.getContentPane().add(barraFerramentas, BorderLayout.PAGE_START);
this.addWindowListener(this);
this.areaDesenho.nomeArquivo.addPropertyChangeListener(this);
PainelPreferencias.carregarPreferencias(areaDesenho);
ToolTipManager.sharedInstance().registerComponent(areaDesenho);
ToolTipManager.sharedInstance().setInitialDelay(1500);
ToolTipManager.sharedInstance().setDismissDelay(20000);
}
public void propertyChange(PropertyChangeEvent evt) {
this.setTitle("CMEditor - " +
areaDesenho.pegaCaminhoArquivo());
}
public void windowOpened(WindowEvent evt) {
}
public void windowClosing(WindowEvent evt) {
if (acoes.sair())
System.exit(0);
}
public void windowClosed(WindowEvent evt) {
}
public void windowIconified(WindowEvent evt) {
}
public void windowDeiconified(WindowEvent evt) {
}
public void windowActivated(WindowEvent evt) {
}
public void windowDeactivated(WindowEvent evt) {
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
UIManager.put("OptionPane.yesButtonText", "Sim");
UIManager.put("OptionPane.yesButtonMnemonic",
String.valueOf(KeyEvent.VK_S));
UIManager.put("OptionPane.noButtonText", "N\u00e3o");
UIManager.put("OptionPane.noButtonMnemonic",
String.valueOf(KeyEvent.VK_N));
UIManager.put("OptionPane.okButtonText", "OK");
UIManager.put("OptionPane.okButtonMnemonic",
String.valueOf(KeyEvent.VK_O));
UIManager.put("OptionPane.cancelButtonText", "Cancelar");
UIManager.put("OptionPane.cancelButtonMnemonic",
String.valueOf(KeyEvent.VK_C));
UIManager.put("FileChooser.cancelButtonText", "Cancelar");
UIManager.put("FileChooser.cancelButtonMnemonic",
String.valueOf(KeyEvent.VK_C));
CMEditor f = new CMEditor();
f.setVisible(true);
f.setEnabled(false);
if (Dialogos.mostrarDialogoBoasVindas(f.areaDesenho, f.acoes))
f.setEnabled(true);
else
System.exit(0);
}
}
|
3e18219bd2a6b70768a738b5fe2188d9920bb9e5 | 2,907 | java | Java | util/mtwilson-util-crypto-key/src/main/java/com/intel/mtwilson/util/crypto/key2/CipherKeyAttributes.java | intel-secl/common_java | 79628eba5cca696b06636f78561dd29ef57e2bbb | [
"BSD-3-Clause"
] | 2 | 2021-12-30T05:58:33.000Z | 2022-03-05T03:31:34.000Z | util/mtwilson-util-crypto-key/src/main/java/com/intel/mtwilson/util/crypto/key2/CipherKeyAttributes.java | intel-secl/common_java | 79628eba5cca696b06636f78561dd29ef57e2bbb | [
"BSD-3-Clause"
] | null | null | null | util/mtwilson-util-crypto-key/src/main/java/com/intel/mtwilson/util/crypto/key2/CipherKeyAttributes.java | intel-secl/common_java | 79628eba5cca696b06636f78561dd29ef57e2bbb | [
"BSD-3-Clause"
] | null | null | null | 25.955357 | 77 | 0.640523 | 10,262 | /*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.mtwilson.util.crypto.key2;
import com.intel.dcsg.cpg.io.Attributes;
import com.intel.dcsg.cpg.io.Copyable;
/**
* Extensible with new attributes via the attributes map and Jackson's
* annotations JsonAnyGetter and JsonAnySetter.
*
* @author jbuhacoff
*/
public class CipherKeyAttributes extends Attributes implements Copyable {
private String keyId;
private String algorithm;
private Integer keyLength;
private String mode;
private String paddingMode;
/**
* The key id can be used to look up the key in a database or
* key server when the encoded key is not present
*/
public String getKeyId() {
return keyId;
}
public void setKeyId(String keyId) {
this.keyId = keyId;
}
/**
* For a certificate, refers to the algorithm of the enclosed public key.
* Examples: AES, RSA
*/
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
/**
* In bits, and always refers to the plaintext key without any
* encoding or encryption. For certificates, this refers to the
* length of the enclosed public key.
* Examples of key length for AES: 128, 256
* Examples of key length for RSA: 1024, 2048, 3072
*/
public Integer getKeyLength() {
return keyLength;
}
public void setKeyLength(Integer keyLength) {
this.keyLength = keyLength;
}
/**
* Cipher mode of operation for this key.
* Using the same key for multiple modes is strongly not recommended
* because it could aid cryptanalysis. Therefore the cipher mode is
* required so that all users of the key know which cipher mode should
* be used with it.
* Examples: CBC, OFB
*/
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
/**
* Padding mode used with this key. For example: ANSIX923, ISO10126,
* None, PKCS7, Zeros, PKCS15, OAEP.
* Examples:
*/
public String getPaddingMode() {
return paddingMode;
}
public void setPaddingMode(String paddingMode) {
this.paddingMode = paddingMode;
}
@Override
public CipherKeyAttributes copy() {
CipherKeyAttributes newInstance = new CipherKeyAttributes();
newInstance.copyFrom(this);
return newInstance;
}
public void copyFrom(CipherKeyAttributes source) {
super.copyFrom(source);
this.keyId = source.keyId;
this.algorithm = source.algorithm;
this.keyLength = source.keyLength;
this.mode = source.mode;
this.paddingMode = source.paddingMode;
}
}
|
3e1821ccd38e69093990a725010f9b87f022b237 | 4,370 | java | Java | server/src/main/java/org/engineer365/common/bean/BeanCopyer.java | greedynamic/cloud-native-micro-service-engineering | 2b5615688d444f9ac63575f3d829877292efc61a | [
"MIT"
] | 1 | 2020-12-08T12:54:02.000Z | 2020-12-08T12:54:02.000Z | server/src/main/java/org/engineer365/common/bean/BeanCopyer.java | cyylog/cloud-native-micro-service-engineering | 7d468b5ca8b001309e6d8ae112b4cf1aaea57639 | [
"MIT"
] | null | null | null | server/src/main/java/org/engineer365/common/bean/BeanCopyer.java | cyylog/cloud-native-micro-service-engineering | 7d468b5ca8b001309e6d8ae112b4cf1aaea57639 | [
"MIT"
] | 2 | 2020-12-25T06:47:59.000Z | 2020-12-31T06:03:51.000Z | 30.774648 | 108 | 0.660412 | 10,263 | /*
* MIT License
*
* Copyright (c) 2020 engineer365.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.engineer365.common.bean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.cglib.beans.BeanCopier;
// import org.springframework.cglib.core.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
/**
*
*/
@lombok.Getter
public class BeanCopyer<SOURCE,TARGET> {
final BeanCopier copier;
final Supplier<TARGET> targetSupplier;
Function<Integer, TARGET[]> targetArraySupplier;
// private final Converter converter;
public BeanCopyer( Class<SOURCE> sourceClass,
Class<TARGET> targetClass,
Supplier<TARGET> targetSupplier,
Function<Integer, TARGET[]> targetArraySupplier) {
this.targetSupplier = targetSupplier;
this.targetArraySupplier = targetArraySupplier;
this.copier = BeanCopier.create(sourceClass, targetClass, false);
}
public TARGET newTarget() {
return getTargetSupplier().get();
}
public TARGET[] newTargetArray(int length) {
return getTargetArraySupplier().apply(length);
}
public CompletableFuture<TARGET> copy(CompletableFuture<SOURCE> sourceFuture) {
return sourceFuture.thenApply(this::copy);
}
public CompletableFuture<TARGET[]> copyToArray(CompletableFuture<List<SOURCE>> sourcesFuture) {
return sourcesFuture.thenApply(this::copyToArray);
}
public Page<TARGET> copy(Page<SOURCE> sourcePage) {
var targetContent = copyToList(sourcePage.getContent());
return new PageImpl<TARGET>(targetContent, sourcePage.getPageable(), sourcePage.getTotalElements());
}
public TARGET copy(SOURCE source) {
if (source == null) {
return null;
}
var r = newTarget();
render(source, r);
return r;
}
public void render(SOURCE source, TARGET target) {
if (source != null && target != null) {
doRender(source, target);
}
}
protected void doRender(SOURCE source, TARGET target) {
getCopier().copy(source, target, null);
}
public TARGET[] copyToArray(List<SOURCE> sources) {
if (sources == null) {
return null;
}
return copyToArray(sources, sources.size());
}
public TARGET[] copyToArray(Iterable<SOURCE> sources, int size) {
if (sources == null) {
return null;
}
var r = new ArrayList<TARGET>(size);
for (var src: sources) {
r.add(copy(src));
}
return r.toArray(getTargetArraySupplier().apply(r.size()));
}
public List<TARGET> copyToList(List<SOURCE> sources) {
if (sources == null) {
return null;
}
return copyToList(sources, sources.size());
}
public List<TARGET> copyToList(Iterable<SOURCE> sources, int size) {
if (sources == null) {
return null;
}
var r = new ArrayList<TARGET>();
for (var src: sources) {
r.add(copy(src));
}
return r;
}
}
|
3e1821d07ced8922f8863e0b1bff11a555930833 | 998 | java | Java | src/main/java/com/issue1/demo/utilEntity/issue2ResultUtil/Issue2ResultDetailUtil.java | zhouxv/issue1 | 11460ad31e4808ae875d5a3693bea0111009de88 | [
"MIT"
] | null | null | null | src/main/java/com/issue1/demo/utilEntity/issue2ResultUtil/Issue2ResultDetailUtil.java | zhouxv/issue1 | 11460ad31e4808ae875d5a3693bea0111009de88 | [
"MIT"
] | null | null | null | src/main/java/com/issue1/demo/utilEntity/issue2ResultUtil/Issue2ResultDetailUtil.java | zhouxv/issue1 | 11460ad31e4808ae875d5a3693bea0111009de88 | [
"MIT"
] | null | null | null | 33.266667 | 119 | 0.758517 | 10,264 | package com.issue1.demo.utilEntity.issue2ResultUtil;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.*;
@Valid
@Data
public class Issue2ResultDetailUtil {
@NotBlank(message = "evaluation_results中的secure_group字段不能为空")
public String secure_group;
@NotBlank(message = "evaluation_results中的index_item字段不能为空")
public String index_item;
@NotNull(message = "evaluation_results中的index字段不能为null")
@Max(value = 130, message = "evaluation_results中的index字段的值应在1-130之间")
@Min(value = 1, message = "evaluation_results中的index字段的值应在1-130之间")
public Integer index;
@NotBlank(message = "evaluation_results中的level字段不能为空")
@Pattern(message = "evaluation_results中的level字段只能为“基础定义级/增强控制级/持续优化级/量化完善级”之一", regexp = "基础定义级|增强控制级|持续优化级|量化完善级")
public String level;
@NotBlank(message = "evaluation_results中的conf字段不能为空")
@Pattern(message = "evaluation_results中的conf格式为“整数1/整数2", regexp = "\\d+/\\d+")
public String conf;
}
|
3e182225623817ca75dd3ab7d17c18a697c9ce30 | 2,541 | java | Java | testutils/src/test/java/com/google/android/exoplayer2/testutil/TestExoPlayerTest.java | trinme/ExoPlayerDemo | 0f310f3fa5a6e631a902a36bf236f65dc648eb67 | [
"Apache-2.0"
] | null | null | null | testutils/src/test/java/com/google/android/exoplayer2/testutil/TestExoPlayerTest.java | trinme/ExoPlayerDemo | 0f310f3fa5a6e631a902a36bf236f65dc648eb67 | [
"Apache-2.0"
] | null | null | null | testutils/src/test/java/com/google/android/exoplayer2/testutil/TestExoPlayerTest.java | trinme/ExoPlayerDemo | 0f310f3fa5a6e631a902a36bf236f65dc648eb67 | [
"Apache-2.0"
] | null | null | null | 33.434211 | 91 | 0.741834 | 10,265 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.testutil;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Supplier;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.LooperMode;
/** Unit test for {@link TestExoPlayer}. */
@RunWith(AndroidJUnit4.class)
@LooperMode(LooperMode.Mode.PAUSED)
public final class TestExoPlayerTest {
@Test
public void runUntil_withConditionAlreadyTrue_returnsImmediately() throws Exception {
Clock mockClock = mock(Clock.class);
TestExoPlayer.runUntil(() -> true, /* timeoutMs= */ 0, mockClock);
verify(mockClock, atMost(1)).currentTimeMillis();
}
@Test
public void runUntil_withConditionThatNeverBecomesTrue_timesOut() {
Clock mockClock = mock(Clock.class);
when(mockClock.currentTimeMillis()).thenReturn(0L, 41L, 42L);
assertThrows(
TimeoutException.class,
() -> TestExoPlayer.runUntil(() -> false, /* timeoutMs= */ 42, mockClock));
verify(mockClock, times(3)).currentTimeMillis();
}
@SuppressWarnings("unchecked")
@Test
public void runUntil_whenConditionBecomesTrueAfterDelay_returnsWhenConditionBecomesTrue()
throws Exception {
Supplier<Boolean> mockCondition = mock(Supplier.class);
when(mockCondition.get())
.thenReturn(false)
.thenReturn(false)
.thenReturn(false)
.thenReturn(false)
.thenReturn(true);
TestExoPlayer.runUntil(mockCondition, /* timeoutMs= */ 5674, mock(Clock.class));
verify(mockCondition, times(5)).get();
}
}
|
3e1823720a29701e6b15c7f12b1a5cf1e7b7d5cc | 2,716 | java | Java | src/main/java/org/dasein/cloud/network/VPNConnection.java | TheWeatherCompany/dasein-cloud-core | 5e4803f754d449789a01bc45d40c0494223b7b5d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/dasein/cloud/network/VPNConnection.java | TheWeatherCompany/dasein-cloud-core | 5e4803f754d449789a01bc45d40c0494223b7b5d | [
"Apache-2.0"
] | 1 | 2021-06-04T02:57:24.000Z | 2021-06-04T02:57:24.000Z | src/main/java/org/dasein/cloud/network/VPNConnection.java | TheWeatherCompany/dasein-cloud-core | 5e4803f754d449789a01bc45d40c0494223b7b5d | [
"Apache-2.0"
] | null | null | null | 29.619565 | 83 | 0.666789 | 10,266 | /**
* Copyright (C) 2009-2014 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.network;
/**
* Represents an established connection between a cloud VPN and a customer gateway.
* <p>Created by George Reese: 6/26/12 1:29 PM</p>
* @author George Reese (hzdkv@example.com)
* @since 2012-07
* @version 2012-07 initial version
*/
@SuppressWarnings("UnusedDeclaration")
public class VPNConnection {
private String configurationXml;
private VPNConnectionState currentState;
private VPNProtocol protocol;
private String providerGatewayId;
private String providerVpnId;
private String providerVpnConnectionId;
public VPNConnection() { }
public String getConfigurationXml() {
return configurationXml;
}
public void setConfigurationXml(String configurationXml) {
this.configurationXml = configurationXml;
}
public VPNConnectionState getCurrentState() {
return currentState;
}
public void setCurrentState(VPNConnectionState currentState) {
this.currentState = currentState;
}
public VPNProtocol getProtocol() {
return protocol;
}
public void setProtocol(VPNProtocol protocol) {
this.protocol = protocol;
}
public String getProviderGatewayId() {
return providerGatewayId;
}
public void setProviderGatewayId(String providerGatewayId) {
this.providerGatewayId = providerGatewayId;
}
public String getProviderVpnId() {
return providerVpnId;
}
public void setProviderVpnId(String providerVpnId) {
this.providerVpnId = providerVpnId;
}
public String getProviderVpnConnectionId() {
return providerVpnConnectionId;
}
public void setProviderVpnConnectionId(String vpnConnectionId) {
this.providerVpnConnectionId = vpnConnectionId;
}
public String toString() {
return (providerVpnId + " -> " + providerGatewayId);
}
}
|
3e1823904be973557bf946fd34b07a0562b24787 | 2,746 | java | Java | dlokiosk/src/main/java/com/dlohaiti/dlokiosk/db/ConfigurationRepository.java | dialymatex/Kiosk | 938ac7839a4a0052ab287cbe18340ec32aac1e96 | [
"Apache-2.0"
] | null | null | null | dlokiosk/src/main/java/com/dlohaiti/dlokiosk/db/ConfigurationRepository.java | dialymatex/Kiosk | 938ac7839a4a0052ab287cbe18340ec32aac1e96 | [
"Apache-2.0"
] | null | null | null | dlokiosk/src/main/java/com/dlohaiti/dlokiosk/db/ConfigurationRepository.java | dialymatex/Kiosk | 938ac7839a4a0052ab287cbe18340ec32aac1e96 | [
"Apache-2.0"
] | 1 | 2019-09-11T19:25:37.000Z | 2019-09-11T19:25:37.000Z | 37.616438 | 176 | 0.654771 | 10,267 | package com.dlohaiti.dlokiosk.db;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.google.inject.Inject;
import static com.dlohaiti.dlokiosk.db.KioskDatabaseUtils.matches;
import static com.dlohaiti.dlokiosk.db.KioskDatabaseUtils.where;
public class ConfigurationRepository {
private final static String TAG = ConfigurationRepository.class.getSimpleName();
private final KioskDatabase db;
private final String[] columns = new String[]{KioskDatabase.ConfigurationTable.KEY, KioskDatabase.ConfigurationTable.VALUE};
@Inject
public ConfigurationRepository(KioskDatabase db) {
this.db = db;
}
public String get(ConfigurationKey key) {
SQLiteDatabase rdb = db.getReadableDatabase();
rdb.beginTransaction();
Cursor cursor = rdb.query(KioskDatabase.ConfigurationTable.TABLE_NAME, columns, where(KioskDatabase.ConfigurationTable.KEY), matches(key.name()), null, null, null);
try {
String value = "";
if(cursor.moveToFirst()) {
value = cursor.getString(1);
rdb.setTransactionSuccessful();
}
return value;
} catch (Exception e) {
Log.e(TAG, String.format("Failed to get value for %s from database.", key.name()), e);
return "";
} finally {
cursor.close();
rdb.endTransaction();
}
}
public Integer getInt(ConfigurationKey key) {
try {
return Integer.valueOf(get(key));
} catch (NumberFormatException e) {
return null;
}
}
public boolean save(ConfigurationKey key, Integer value) {
return save(key, String.valueOf(value));
}
public boolean save(ConfigurationKey key, String value) {
SQLiteDatabase writableDatabase = db.getWritableDatabase();
ContentValues val = new ContentValues();
val.put(KioskDatabase.ConfigurationTable.KEY, key.name());
val.put(KioskDatabase.ConfigurationTable.VALUE, value);
writableDatabase.beginTransaction();
try {
//Depends on things being inserted beforehand
writableDatabase.update(KioskDatabase.ConfigurationTable.TABLE_NAME, val, where(KioskDatabase.ConfigurationTable.KEY), matches(key.name()));
writableDatabase.setTransactionSuccessful();
return true;
} catch (Exception e) {
Log.e(TAG, String.format("Failed to save value for configuration key %s to database.", key.name()), e);
return false;
} finally {
writableDatabase.endTransaction();
}
}
}
|
3e1823dd08155ea21847d34f68545a0d308e7baa | 5,070 | java | Java | platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | null | null | null | platform/lang-impl/src/com/intellij/analysis/AnalysisUIOptions.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 1 | 2020-10-15T05:56:42.000Z | 2020-10-15T05:56:42.000Z | 34.965517 | 140 | 0.699803 | 10,268 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.analysis;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ui.InspectionResultsView;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsActions;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.ui.AutoScrollToSourceHandler;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
@State(name = "AnalysisUIOptions", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public class AnalysisUIOptions implements PersistentStateComponent<AnalysisUIOptions> {
public static AnalysisUIOptions getInstance(Project project) {
return ServiceManager.getService(project, AnalysisUIOptions.class);
}
public boolean AUTOSCROLL_TO_SOURCE = false;
public float SPLITTER_PROPORTION = 0.5f;
public volatile boolean GROUP_BY_SEVERITY = false;
public volatile boolean FILTER_RESOLVED_ITEMS = true;
public boolean ANALYZE_TEST_SOURCES = true;
@AnalysisScope.Type
public int SCOPE_TYPE = AnalysisScope.PROJECT;
public String CUSTOM_SCOPE_NAME = "";
@Transient
private final AutoScrollToSourceHandler myAutoScrollToSourceHandler;
public volatile boolean SHOW_STRUCTURE = false;
public @NlsSafe String FILE_MASK;
public boolean ANALYSIS_IN_BACKGROUND = true;
public AnalysisUIOptions() {
myAutoScrollToSourceHandler = new AutoScrollToSourceHandler() {
@Override
protected boolean isAutoScrollMode() {
return AUTOSCROLL_TO_SOURCE;
}
@Override
protected void setAutoScrollMode(boolean state) {
AUTOSCROLL_TO_SOURCE = state;
}
};
}
public AutoScrollToSourceHandler getAutoScrollToSourceHandler() {
return myAutoScrollToSourceHandler;
}
public AnAction createGroupBySeverityAction(final InspectionResultsView view) {
return new InspectionResultsViewToggleAction(view,
InspectionsBundle.message("inspection.action.group.by.severity"),
InspectionsBundle.message("inspection.action.group.by.severity.description"),
AllIcons.Nodes.SortBySeverity) {
@Override
public boolean isSelected(@NotNull AnActionEvent e) {
return GROUP_BY_SEVERITY;
}
@Override
protected void setSelected(boolean state) {
GROUP_BY_SEVERITY = state;
}
};
}
public AnAction createFilterResolvedItemsAction(final InspectionResultsView view){
return new InspectionResultsViewToggleAction(view,
InspectionsBundle.message("inspection.filter.resolved.action.text"),
InspectionsBundle.message("inspection.filter.resolved.action.text"),
AllIcons.General.Filter) {
@Override
public boolean isSelected(@NotNull AnActionEvent e) {
return FILTER_RESOLVED_ITEMS;
}
@Override
public void setSelected(boolean state) {
FILTER_RESOLVED_ITEMS = state;
}
};
}
public AnAction createGroupByDirectoryAction(final InspectionResultsView view) {
String message = InspectionsBundle.message("inspection.action.group.by.directory");
return new InspectionResultsViewToggleAction(view, message, message, AllIcons.Actions.GroupByPackage) {
@Override
public boolean isSelected(@NotNull AnActionEvent e) {
return SHOW_STRUCTURE;
}
@Override
public void setSelected(boolean state) {
SHOW_STRUCTURE = state;
}
};
}
@Override
public AnalysisUIOptions getState() {
return this;
}
@Override
public void loadState(@NotNull AnalysisUIOptions state) {
XmlSerializerUtil.copyBean(state, this);
}
private abstract static class InspectionResultsViewToggleAction extends ToggleAction {
@NotNull private final InspectionResultsView myView;
InspectionResultsViewToggleAction(@NotNull InspectionResultsView view,
@NotNull @NlsActions.ActionText String text,
@NotNull @NlsActions.ActionDescription String description,
@NotNull Icon icon) {
super(text, description, icon);
myView = view;
}
@Override
public final void setSelected(@NotNull AnActionEvent e, boolean state) {
setSelected(state);
myView.update();
}
protected abstract void setSelected(boolean state);
}
}
|
3e1824d8ae188903aaa36ed6946d27a199f163b9 | 3,721 | java | Java | SingularityBase/src/main/java/com/hubspot/singularity/SingularityDeployStatisticsBuilder.java | benhardy/Singularity | 8a5ce4f8366c93404f15897454865ce6dc9f8c1d | [
"Apache-2.0"
] | 11 | 2016-05-25T15:44:34.000Z | 2021-07-24T19:37:30.000Z | SingularityBase/src/main/java/com/hubspot/singularity/SingularityDeployStatisticsBuilder.java | benhardy/Singularity | 8a5ce4f8366c93404f15897454865ce6dc9f8c1d | [
"Apache-2.0"
] | 1 | 2022-01-21T23:54:50.000Z | 2022-01-21T23:54:50.000Z | SingularityBase/src/main/java/com/hubspot/singularity/SingularityDeployStatisticsBuilder.java | benhardy/Singularity | 8a5ce4f8366c93404f15897454865ce6dc9f8c1d | [
"Apache-2.0"
] | 6 | 2016-05-30T06:41:24.000Z | 2022-02-27T10:57:58.000Z | 29.070313 | 209 | 0.766461 | 10,269 | package com.hubspot.singularity;
import com.google.common.base.Optional;
import com.google.common.collect.ListMultimap;
public class SingularityDeployStatisticsBuilder {
private final String requestId;
private final String deployId;
private int numTasks;
private int numSuccess;
private int numFailures;
private int numSequentialRetries;
private ListMultimap<Integer, Long> instanceSequentialFailureTimestamps;
private Optional<Long> lastFinishAt;
private Optional<ExtendedTaskState> lastTaskState;
private Optional<Long> averageRuntimeMillis;
public SingularityDeployStatisticsBuilder(String requestId, String deployId) {
this.requestId = requestId;
this.deployId = deployId;
this.lastFinishAt = Optional.absent();
this.lastTaskState = Optional.absent();
this.averageRuntimeMillis = Optional.absent();
}
public SingularityDeployStatistics build() {
return new SingularityDeployStatistics(requestId, deployId, numSuccess, numFailures, numSequentialRetries, lastFinishAt, lastTaskState, instanceSequentialFailureTimestamps, numTasks, averageRuntimeMillis);
}
public ListMultimap<Integer, Long> getInstanceSequentialFailureTimestamps() {
return instanceSequentialFailureTimestamps;
}
public SingularityDeployStatisticsBuilder setInstanceSequentialFailureTimestamps(ListMultimap<Integer, Long> instanceSequentialFailureTimestamps) {
this.instanceSequentialFailureTimestamps = instanceSequentialFailureTimestamps;
return this;
}
public int getNumSuccess() {
return numSuccess;
}
public SingularityDeployStatisticsBuilder setNumSuccess(int numSuccess) {
this.numSuccess = numSuccess;
return this;
}
public int getNumFailures() {
return numFailures;
}
public SingularityDeployStatisticsBuilder setNumFailures(int numFailures) {
this.numFailures = numFailures;
return this;
}
public int getNumSequentialRetries() {
return numSequentialRetries;
}
public SingularityDeployStatisticsBuilder setNumSequentialRetries(int numSequentialRetries) {
this.numSequentialRetries = numSequentialRetries;
return this;
}
public Optional<Long> getLastFinishAt() {
return lastFinishAt;
}
public SingularityDeployStatisticsBuilder setLastFinishAt(Optional<Long> lastFinishAt) {
this.lastFinishAt = lastFinishAt;
return this;
}
public Optional<ExtendedTaskState> getLastTaskState() {
return lastTaskState;
}
public SingularityDeployStatisticsBuilder setLastTaskState(Optional<ExtendedTaskState> lastTaskState) {
this.lastTaskState = lastTaskState;
return this;
}
public String getRequestId() {
return requestId;
}
public int getNumTasks() {
return numTasks;
}
public SingularityDeployStatisticsBuilder setNumTasks(int numTasks) {
this.numTasks = numTasks;
return this;
}
public Optional<Long> getAverageRuntimeMillis() {
return averageRuntimeMillis;
}
public SingularityDeployStatisticsBuilder setAverageRuntimeMillis(Optional<Long> averageRuntimeMillis) {
this.averageRuntimeMillis = averageRuntimeMillis;
return this;
}
public String getDeployId() {
return deployId;
}
@Override
public String toString() {
return "SingularityDeployStatisticsBuilder [requestId=" + requestId + ", deployId=" + deployId + ", numTasks=" + numTasks + ", numSuccess=" + numSuccess + ", numFailures=" + numFailures
+ ", numSequentialRetries=" + numSequentialRetries + ", instanceSequentialFailureTimestamps=" + instanceSequentialFailureTimestamps + ", lastFinishAt=" + lastFinishAt + ", lastTaskState="
+ lastTaskState + ", averageRuntimeMillis=" + averageRuntimeMillis + "]";
}
}
|
3e1825c04fda381717e43463ad9c2d2e6f70a131 | 2,667 | java | Java | core/src/main/java/org/cloudfoundry/test/core/RedisUtils.java | hybris/java-test-applications | 803210766e019381d67d6512457391bc5f997f7a | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/cloudfoundry/test/core/RedisUtils.java | hybris/java-test-applications | 803210766e019381d67d6512457391bc5f997f7a | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/cloudfoundry/test/core/RedisUtils.java | hybris/java-test-applications | 803210766e019381d67d6512457391bc5f997f7a | [
"Apache-2.0"
] | null | null | null | 38.652174 | 143 | 0.687289 | 10,270 | /*
* Copyright 2014-2019 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.cloudfoundry.test.core;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Utility class for analysing a {@link RedisConnectionFactory}.
*/
@RestController
@RequestMapping("/redis")
public final class RedisUtils extends AbstractServiceUtils<RedisConnectionFactory> {
public RedisUtils(RedisConnectionFactory redisConnectionFactory) {
super(redisConnectionFactory);
}
public String checkAccess(RedisConnectionFactory redisConnectionFactory) {
RedisConnection connection = null;
try {
connection = redisConnectionFactory.getConnection();
connection.echo("hello".getBytes());
return "ok";
} catch (Exception e) {
return String.format("failed with %s", e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
return String.format("Redis connection close failed with %s", e.getMessage());
}
}
}
public String getUrl(RedisConnectionFactory redisConnectionFactory) {
if (isClass(redisConnectionFactory, "org.cloudfoundry.test.fake.FakeRedisConnectionFactory")) {
return "redis://fake";
} else if (isClass(redisConnectionFactory, "org.springframework.data.redis.connection.jedis.JedisConnectionFactory")) {
String hostname = invokeMethod(redisConnectionFactory, "getHostName");
Integer port = invokeMethod(redisConnectionFactory, "getPort");
return String.format("redis://%s:%d", hostname, port);
} else {
return String.format("Unable to determine URL for RedisConnectionFactory of type %s", redisConnectionFactory.getClass().getName());
}
}
}
|
3e1825e8c2ae77e54da90b5662639cb42e51825f | 2,272 | java | Java | ucloud-sdk-java-umem/src/main/java/cn/ucloud/umem/model/DescribeURedisSlaveGroupParam.java | liuchangfitcloud/ucloud-sdk-java | ca370c2141527f713feb0c1548d8cc42a8687c2a | [
"Apache-2.0"
] | null | null | null | ucloud-sdk-java-umem/src/main/java/cn/ucloud/umem/model/DescribeURedisSlaveGroupParam.java | liuchangfitcloud/ucloud-sdk-java | ca370c2141527f713feb0c1548d8cc42a8687c2a | [
"Apache-2.0"
] | null | null | null | ucloud-sdk-java-umem/src/main/java/cn/ucloud/umem/model/DescribeURedisSlaveGroupParam.java | liuchangfitcloud/ucloud-sdk-java | ca370c2141527f713feb0c1548d8cc42a8687c2a | [
"Apache-2.0"
] | null | null | null | 21.233645 | 88 | 0.621039 | 10,271 | package cn.ucloud.umem.model;
import cn.ucloud.common.annotation.UcloudParam;
import cn.ucloud.common.pojo.BaseRequestParam;
import javax.validation.constraints.NotEmpty;
/**
* @Description : 查询主备Redis关联Slave 参数类
* @Author : ucloud-sdk-generator
* @Date : 2019-03-15 10:00
**/
public class DescribeURedisSlaveGroupParam extends BaseRequestParam {
/**
* 地域。 参见 [地域和可用区列表](../summary/regionlist.html)
*/
@UcloudParam("Region")
@NotEmpty(message = "region can not be empty")
private String region;
/**
* 可用区。参见 [可用区列表](../summary/regionlist.html)
*/
@UcloudParam("Zone")
private String zone;
/**
* 依赖的Master URedis Group ID
*/
@UcloudParam("MasterGroupId")
@NotEmpty(message = "masterGroupId can not be empty")
private String masterGroupId;
/**
* Slave Redis Group ID,指定此ID,返回单个实例信息;否则返回Master Redis Group对应所有Slave Redis Group信息
*/
@UcloudParam("GroupId")
private String groupId;
/**
*
*/
@UcloudParam("Offset")
private String offset;
/**
*
*/
@UcloudParam("Limit")
private String limit;
public DescribeURedisSlaveGroupParam(String region
, String masterGroupId
) {
super("DescribeURedisSlaveGroup");
this.region = region;
this.masterGroupId = masterGroupId;
}
public String getRegion() {
return this.region;
}
public void setRegion(String region) {
this.region = region;
}
public String getZone() {
return this.zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getMasterGroupId() {
return this.masterGroupId;
}
public void setMasterGroupId(String masterGroupId) {
this.masterGroupId = masterGroupId;
}
public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getOffset() {
return this.offset;
}
public void setOffset(String offset) {
this.offset = offset;
}
public String getLimit() {
return this.limit;
}
public void setLimit(String limit) {
this.limit = limit;
}
} |
3e18260e73961292fec67b42449779dbe12bbea1 | 1,016 | java | Java | mall-order/src/main/java/com/xpcf/mall/order/entity/PaymentInfoEntity.java | pascalcpp/mall | 4fb6132d576a0395ae2e9f1b1047982e75e9a9ce | [
"MIT"
] | null | null | null | mall-order/src/main/java/com/xpcf/mall/order/entity/PaymentInfoEntity.java | pascalcpp/mall | 4fb6132d576a0395ae2e9f1b1047982e75e9a9ce | [
"MIT"
] | null | null | null | mall-order/src/main/java/com/xpcf/mall/order/entity/PaymentInfoEntity.java | pascalcpp/mall | 4fb6132d576a0395ae2e9f1b1047982e75e9a9ce | [
"MIT"
] | null | null | null | 14.471429 | 56 | 0.666338 | 10,272 | package com.xpcf.mall.order.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 支付信息表
*
* @author xpcf
* @email lyhxr@example.com
* @date 2020-12-12 03:41:21
*/
@Data
@TableName("oms_payment_info")
public class PaymentInfoEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 订单号(对外业务号)
*/
private String orderSn;
/**
* 订单id
*/
private Long orderId;
/**
* 支付宝交易流水号
*/
private String alipayTradeNo;
/**
* 支付总金额
*/
private BigDecimal totalAmount;
/**
* 交易内容
*/
private String subject;
/**
* 支付状态
*/
private String paymentStatus;
/**
* 创建时间
*/
private Date createTime;
/**
* 确认时间
*/
private Date confirmTime;
/**
* 回调内容
*/
private String callbackContent;
/**
* 回调时间
*/
private Date callbackTime;
}
|
3e18263563dc65eeb062b84004d07d1fc8bee78d | 1,156 | java | Java | src/main/java/ac/za/cput/Controller/LecturerController.java | AdamWarlock21/MyRepo2 | 267e1fb50ece3b5ce353c258943486b624df9db8 | [
"MIT"
] | null | null | null | src/main/java/ac/za/cput/Controller/LecturerController.java | AdamWarlock21/MyRepo2 | 267e1fb50ece3b5ce353c258943486b624df9db8 | [
"MIT"
] | null | null | null | src/main/java/ac/za/cput/Controller/LecturerController.java | AdamWarlock21/MyRepo2 | 267e1fb50ece3b5ce353c258943486b624df9db8 | [
"MIT"
] | null | null | null | 22.666667 | 62 | 0.698097 | 10,273 | package ac.za.cput.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import ac.za.cput.Domain.Lecturer;
import ac.za.cput.Service.Impl.LecturerServiceImpl;
import java.util.Set;
@RestController
@RequestMapping("/lecturer")
public class LecturerController {
@Autowired
@Qualifier("LecturerServiceImpl")
private LecturerServiceImpl service;
@PostMapping("/new")
public Lecturer create(@RequestBody Lecturer lecturer){
return service.create(lecturer);
}
@GetMapping(path = "/find/{id}")
public Lecturer findById(@PathVariable String id){
Lecturer lecturer = service.read(id);
return lecturer;
}
@PutMapping("/update")
public void update(@RequestBody Lecturer lecturer){
service.update(lecturer);
}
@DeleteMapping(path = "/delete/{id}")
public void delete(@PathVariable String id){
service.delete(id);
}
@GetMapping("/getall")
public Set<Lecturer> getAll(){
return service.getAll();
}
}
|
3e1827a140238b6d37d6cfb73b353fec2094ad23 | 4,653 | java | Java | core/trino-main/src/test/java/io/trino/operator/TestDriverStats.java | kbendick/trino | cf29082c8735f7d0a994c1867b1525720f7fe279 | [
"Apache-2.0"
] | 1,695 | 2019-01-19T09:05:17.000Z | 2020-12-27T17:39:08.000Z | core/trino-main/src/test/java/io/trino/operator/TestDriverStats.java | kbendick/trino | cf29082c8735f7d0a994c1867b1525720f7fe279 | [
"Apache-2.0"
] | 4,549 | 2019-01-21T02:50:11.000Z | 2020-12-27T20:38:26.000Z | core/trino-main/src/test/java/io/trino/operator/TestDriverStats.java | kbendick/trino | cf29082c8735f7d0a994c1867b1525720f7fe279 | [
"Apache-2.0"
] | 909 | 2019-01-19T06:51:51.000Z | 2020-12-26T20:06:11.000Z | 35.519084 | 88 | 0.685579 | 10,274 | /*
* 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.trino.operator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.airlift.json.JsonCodec;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import io.trino.execution.Lifespan;
import org.joda.time.DateTime;
import org.testng.annotations.Test;
import static io.trino.operator.TestOperatorStats.assertExpectedOperatorStats;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.joda.time.DateTimeZone.UTC;
import static org.testng.Assert.assertEquals;
public class TestDriverStats
{
public static final DriverStats EXPECTED = new DriverStats(
Lifespan.driverGroup(21),
new DateTime(1),
new DateTime(2),
new DateTime(3),
new Duration(4, NANOSECONDS),
new Duration(5, NANOSECONDS),
DataSize.ofBytes(6),
DataSize.ofBytes(7),
new Duration(9, NANOSECONDS),
new Duration(10, NANOSECONDS),
new Duration(12, NANOSECONDS),
false,
ImmutableSet.of(),
DataSize.ofBytes(131),
141,
new Duration(151, NANOSECONDS),
DataSize.ofBytes(132),
142,
DataSize.ofBytes(13),
14,
new Duration(15, NANOSECONDS),
DataSize.ofBytes(16),
17,
new Duration(101, NANOSECONDS),
DataSize.ofBytes(18),
19,
new Duration(102, NANOSECONDS),
DataSize.ofBytes(20),
ImmutableList.of(TestOperatorStats.EXPECTED));
@Test
public void testJson()
{
JsonCodec<DriverStats> codec = JsonCodec.jsonCodec(DriverStats.class);
String json = codec.toJson(EXPECTED);
DriverStats actual = codec.fromJson(json);
assertExpectedDriverStats(actual);
}
public static void assertExpectedDriverStats(DriverStats actual)
{
assertEquals(actual.getLifespan(), Lifespan.driverGroup(21));
assertEquals(actual.getCreateTime(), new DateTime(1, UTC));
assertEquals(actual.getStartTime(), new DateTime(2, UTC));
assertEquals(actual.getEndTime(), new DateTime(3, UTC));
assertEquals(actual.getQueuedTime(), new Duration(4, NANOSECONDS));
assertEquals(actual.getElapsedTime(), new Duration(5, NANOSECONDS));
assertEquals(actual.getUserMemoryReservation(), DataSize.ofBytes(6));
assertEquals(actual.getRevocableMemoryReservation(), DataSize.ofBytes(7));
assertEquals(actual.getTotalScheduledTime(), new Duration(9, NANOSECONDS));
assertEquals(actual.getTotalCpuTime(), new Duration(10, NANOSECONDS));
assertEquals(actual.getTotalBlockedTime(), new Duration(12, NANOSECONDS));
assertEquals(actual.getPhysicalInputDataSize(), DataSize.ofBytes(131));
assertEquals(actual.getPhysicalInputPositions(), 141);
assertEquals(actual.getPhysicalInputReadTime(), new Duration(151, NANOSECONDS));
assertEquals(actual.getInternalNetworkInputDataSize(), DataSize.ofBytes(132));
assertEquals(actual.getInternalNetworkInputPositions(), 142);
assertEquals(actual.getRawInputDataSize(), DataSize.ofBytes(13));
assertEquals(actual.getRawInputPositions(), 14);
assertEquals(actual.getRawInputReadTime(), new Duration(15, NANOSECONDS));
assertEquals(actual.getProcessedInputDataSize(), DataSize.ofBytes(16));
assertEquals(actual.getProcessedInputPositions(), 17);
assertEquals(actual.getInputBlockedTime(), new Duration(101, NANOSECONDS));
assertEquals(actual.getOutputDataSize(), DataSize.ofBytes(18));
assertEquals(actual.getOutputPositions(), 19);
assertEquals(actual.getOutputBlockedTime(), new Duration(102, NANOSECONDS));
assertEquals(actual.getPhysicalWrittenDataSize(), DataSize.ofBytes(20));
assertEquals(actual.getOperatorStats().size(), 1);
assertExpectedOperatorStats(actual.getOperatorStats().get(0));
}
}
|
3e1827c1f8e6d7f120e5f2a37690200b08b2d388 | 435 | java | Java | examples/storm-starter/src/jvm/storm/starter/util/StringGenerator.java | wangli1426/my-storm | c03af1ee8302c0f059079dff31c84fa94a002b61 | [
"Apache-2.0"
] | 3 | 2018-03-07T18:27:57.000Z | 2019-09-18T13:37:30.000Z | examples/storm-starter/src/jvm/storm/starter/util/StringGenerator.java | ADSC-Cloud/Elasticutor | c682c802a1500005c9b467989265a81410c9f6f1 | [
"Apache-2.0"
] | 1 | 2019-07-02T17:19:41.000Z | 2019-07-02T17:19:41.000Z | examples/storm-starter/src/jvm/storm/starter/util/StringGenerator.java | wangli1426/my-storm | c03af1ee8302c0f059079dff31c84fa94a002b61 | [
"Apache-2.0"
] | 1 | 2020-09-27T03:21:58.000Z | 2020-09-27T03:21:58.000Z | 19.772727 | 72 | 0.708046 | 10,275 | package storm.starter.util;
import java.util.Random;
/**
* Created by robert on 1/8/16.
*/
public class StringGenerator {
int numberOfDistinctValues;
Random random = new Random();
public StringGenerator(int numberOfDistinctValues) {
this.numberOfDistinctValues = numberOfDistinctValues;
}
public String nextString() {
return Integer.toString(random.nextInt(numberOfDistinctValues));
}
}
|
3e1827e186a142db5b08e99445ff3df198812346 | 2,507 | java | Java | app/src/main/java/com/azra2/ui/mainfrag/NotificationAdapter.java | takemurakimio/hibadeen-azra2 | ec75f5ac4912fc5e7ad8d1974a8b1760fa9a7333 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/azra2/ui/mainfrag/NotificationAdapter.java | takemurakimio/hibadeen-azra2 | ec75f5ac4912fc5e7ad8d1974a8b1760fa9a7333 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/azra2/ui/mainfrag/NotificationAdapter.java | takemurakimio/hibadeen-azra2 | ec75f5ac4912fc5e7ad8d1974a8b1760fa9a7333 | [
"Apache-2.0"
] | null | null | null | 29.494118 | 150 | 0.676107 | 10,276 | package com.azra2.ui.mainfrag;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.azra2.R;
import com.azra2.model.YMNotification;
import java.util.ArrayList;
public class NotificationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ArrayList<YMNotification> dataList;
private Context context;
public NotificationAdapter(Context context, ArrayList<YMNotification> dataList){
this.context = context;
this.dataList = dataList;
}
@Override
public int getItemViewType(int position){
// return dataList.get(position).getType();
return 0;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =null;
RecyclerView.ViewHolder viewHolder = null;
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notif_00_layout,parent,false);
viewHolder = new NotificationAdapter.NotificationViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()){
case 0:
NotificationViewHolder vh0 = (NotificationViewHolder)holder;
vh0.tvContent.setText("Notification 1 Admin approved \nyour request to change rooms.\nYou have officially joined the\nPrivate Room.");
vh0.tvTime.setText("2m");
break;
case 1:
NotificationViewHolder vh1 = (NotificationViewHolder)holder;
vh1.tvContent.setText("Notification 1 username1 \nnotified you for a Private Room Call.");
vh1.tvTime.setText("2m");
break;
}
}
@Override
public int getItemCount() {
return dataList.size();
}
public class NotificationViewHolder extends RecyclerView.ViewHolder{
public ImageView ivImage;
public TextView tvContent;
public TextView tvTime;
public NotificationViewHolder(View itemView){
super(itemView);
ivImage = itemView.findViewById(R.id.ivImage);
tvContent = itemView.findViewById(R.id.tvContent);
tvTime = itemView.findViewById(R.id.tvTime);
}
}
}
|
3e1827f8067d08719148dbaf04677b9da17eab17 | 2,798 | java | Java | src/main/java/com/yahoo/test/monitor/MonitoringTools.java | areese/TestJVMConnections | 920d22a956af0f4a63de628adabc32942e6a7a86 | [
"BSD-3-Clause"
] | 1 | 2016-02-19T19:04:47.000Z | 2016-02-19T19:04:47.000Z | src/main/java/com/yahoo/test/monitor/MonitoringTools.java | areese/TestJVMConnections | 920d22a956af0f4a63de628adabc32942e6a7a86 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/yahoo/test/monitor/MonitoringTools.java | areese/TestJVMConnections | 920d22a956af0f4a63de628adabc32942e6a7a86 | [
"BSD-3-Clause"
] | null | null | null | 33.710843 | 119 | 0.654039 | 10,277 | // Copyright 2016 Yahoo Inc.
// Licensed under the terms of the New-BSD license. Please see LICENSE file in the project root for terms.
package com.yahoo.test.monitor;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Properties;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
public class MonitoringTools {
private final PrintStream out;
public MonitoringTools(OutputStream out) {
this.out = new PrintStream(out);
}
public MonitoringTools(PrintStream out) {
this.out = out;
}
public void foreachVM(VMRunnable vmr) {
for (VirtualMachineDescriptor virtualMachineDescriptor : VirtualMachine.list()) {
vmr.preAttach(virtualMachineDescriptor);
VirtualMachine virtualMachine = attach(virtualMachineDescriptor);
if (null != virtualMachine) {
vmr.attached(virtualMachine);
}
detachSilently(virtualMachine);
vmr.postDetatch(virtualMachineDescriptor);
}
}
public VirtualMachine attach(VirtualMachineDescriptor virtualMachineDescriptor) {
try {
VirtualMachine vm = VirtualMachine.attach(virtualMachineDescriptor);
String agent =
vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator
+ "management-agent.jar";
try {
vm.loadAgentLibrary(agent);
} catch (AgentLoadException e) {
}
return vm;
} catch (AttachNotSupportedException | AgentInitializationException e) {
out.println("Couldn't attach");
e.printStackTrace(out);
} catch (IOException ioe) {
out.println("Exception attaching or reading a jvm.");
ioe.printStackTrace();
}
return null;
}
public static String readSystemProperty(VirtualMachine virtualMachine, String propertyName) throws IOException {
Properties systemProperties = virtualMachine.getSystemProperties();
return systemProperties.getProperty(propertyName);
}
public void detachSilently(VirtualMachine virtualMachine) {
if (virtualMachine != null) {
try {
virtualMachine.detach();
} catch (IOException e) {
e.printStackTrace();
}
};
}
}
|
3e182933bef796ce58f4a918bff7c192cfe929b1 | 13,781 | java | Java | src/main/java/org/selenium/runner/model/SeleniumActionType.java | pguillerm/selenium-runner | c1aeae391c708f57616f173802ba1daa41c68b5d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/selenium/runner/model/SeleniumActionType.java | pguillerm/selenium-runner | c1aeae391c708f57616f173802ba1daa41c68b5d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/selenium/runner/model/SeleniumActionType.java | pguillerm/selenium-runner | c1aeae391c708f57616f173802ba1daa41c68b5d | [
"Apache-2.0"
] | null | null | null | 25.615242 | 80 | 0.700312 | 10,278 | /*
* 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.selenium.runner.model;
/**
* SeleniumActionType
*
* @author pguillerm
* @since 16 févr. 2015
*/
public enum SeleniumActionType {
//@formatter:off
storeEval,
addLocationStrategy,
addLocationStrategyAndWait,
addScript,
addScriptAndWait,
addSelection,
addSelectionAndWait,
allowNativeXpath,
allowNativeXpathAndWait,
altKeyDown,
altKeyDownAndWait,
altKeyUp,
altKeyUpAndWait,
answerOnNextPrompt,
assertAlert,
assertAlertNotPresent,
assertAlertPresent,
assertAllButtons,
assertAllFields,
assertAllLinks,
assertAllWindowIds,
assertAllWindowNames,
assertAllWindowTitles,
assertAttribute,
assertAttributeFromAllWindows,
assertBodyText,
assertChecked,
assertConfirmation,
assertConfirmationNotPresent,
assertConfirmationPresent,
assertCookie,
assertCookieByName,
assertCookieNotPresent,
assertCookiePresent,
assertCssCount,
assertCursorPosition,
assertEditable,
assertElementHeight,
assertElementIndex,
assertElementNotPresent,
assertElementPositionLeft,
assertElementPositionTop,
assertElementPresent,
assertElementWidth,
assertEval,
assertExpression,
assertHtmlSource,
assertLocation,
assertMouseSpeed,
assertNotAlert,
assertNotAllButtons,
assertNotAllFields,
assertNotAllLinks,
assertNotAllWindowIds,
assertNotAllWindowNames,
assertNotAllWindowTitles,
assertNotAttribute,
assertNotAttributeFromAllWindows,
assertNotBodyText,
assertNotChecked,
assertNotConfirmation,
assertNotCookie,
assertNotCookieByName,
assertNotCssCount,
assertNotCursorPosition,
assertNotEditable,
assertNotElementHeight,
assertNotElementIndex,
assertNotElementPositionLeft,
assertNotElementPositionTop,
assertNotElementWidth,
assertNotEval,
assertNotExpression,
assertNotHtmlSource,
assertNotLocation,
assertNotMouseSpeed,
assertNotOrdered,
assertNotPrompt,
assertNotSelectOptions,
assertNotSelectedId,
assertNotSelectedIds,
assertNotSelectedIndex,
assertNotSelectedIndexes,
assertNotSelectedLabel,
assertNotSelectedLabels,
assertNotSelectedValue,
assertNotSelectedValues,
assertNotSomethingSelected,
assertNotSpeed,
assertNotTable,
assertNotText,
assertNotTitle,
assertNotValue,
assertNotVisible,
assertNotWhetherThisFrameMatchFrameExpression,
assertNotWhetherThisWindowMatchWindowExpression,
assertNotXpathCount,
assertOrdered,
assertPrompt,
assertPromptNotPresent,
assertPromptPresent,
assertSelectOptions,
assertSelectedId,
assertSelectedIds,
assertSelectedIndex,
assertSelectedIndexes,
assertSelectedLabel,
assertSelectedLabels,
assertSelectedValue,
assertSelectedValues,
assertSomethingSelected,
assertSpeed,
assertTable,
assertText,
assertTextNotPresent,
assertTextPresent,
assertTitle,
assertValue,
assertVisible,
assertWhetherThisFrameMatchFrameExpression,
assertWhetherThisWindowMatchWindowExpression,
assertXpathCount,
assignId,
assignIdAndWait,
captureEntirePageScreenshot,
captureEntirePageScreenshotAndWait,
check,
checkAndWait,
chooseCancelOnNextConfirmation,
chooseOkOnNextConfirmation,
chooseOkOnNextConfirmationAndWait,
click,
clickAndWait,
clickAt,
clickAtAndWait,
close,
contextMenu,
contextMenuAndWait,
contextMenuAt,
contextMenuAtAndWait,
controlKeyDown,
controlKeyDownAndWait,
controlKeyUp,
controlKeyUpAndWait,
createCookie,
createCookieAndWait,
deleteAllVisibleCookies,
deleteAllVisibleCookiesAndWait,
deleteCookie,
deleteCookieAndWait,
deselectPopUp,
deselectPopUpAndWait,
doubleClick,
doubleClickAndWait,
doubleClickAt,
doubleClickAtAndWait,
dragAndDrop,
dragAndDropAndWait,
dragAndDropToObject,
dragAndDropToObjectAndWait,
dragdrop,
dragdropAndWait,
echo,
fireEvent,
fireEventAndWait,
focus,
focusAndWait,
goBack,
goBackAndWait,
highlight,
highlightAndWait,
ignoreAttributesWithoutValue,
ignoreAttributesWithoutValueAndWait,
keyDown,
keyDownAndWait,
keyPress,
keyPressAndWait,
keyUp,
keyUpAndWait,
metaKeyDown,
metaKeyDownAndWait,
metaKeyUp,
metaKeyUpAndWait,
mouseDown,
mouseDownAndWait,
mouseDownAt,
mouseDownAtAndWait,
mouseDownRight,
mouseDownRightAndWait,
mouseDownRightAt,
mouseDownRightAtAndWait,
mouseMove,
mouseMoveAndWait,
mouseMoveAt,
mouseMoveAtAndWait,
mouseOut,
mouseOutAndWait,
mouseOver,
mouseOverAndWait,
mouseUp,
mouseUpAndWait,
mouseUpAt,
mouseUpAtAndWait,
mouseUpRight,
mouseUpRightAndWait,
mouseUpRightAt,
mouseUpRightAtAndWait,
open,
openWindow,
openWindowAndWait,
pause,
refresh,
refreshAndWait,
removeAllSelections,
removeAllSelectionsAndWait,
removeScript,
removeScriptAndWait,
removeSelection,
removeSelectionAndWait,
rollup,
rollupAndWait,
runScript,
runScriptAndWait,
select,
selectAndWait,
selectFrame,
selectPopUp,
selectPopUpAndWait,
selectWindow,
setBrowserLogLevel,
setBrowserLogLevelAndWait,
setCursorPosition,
setCursorPositionAndWait,
setMouseSpeed,
setMouseSpeedAndWait,
setSpeed,
setSpeedAndWait,
setTimeout,
shiftKeyDown,
shiftKeyDownAndWait,
shiftKeyUp,
shiftKeyUpAndWait,
submit,
submitAndWait,
type,
typeAndWait,
typeKeys,
typeKeysAndWait,
uncheck,
uncheckAndWait,
useXpathLibrary,
useXpathLibraryAndWait,
verifyAlert,
verifyAlertNotPresent,
verifyAlertPresent,
verifyAllButtons,
verifyAllFields,
verifyAllLinks,
verifyAllWindowIds,
verifyAllWindowNames,
verifyAllWindowTitles,
verifyAttribute,
verifyAttributeFromAllWindows,
verifyBodyText,
verifyChecked,
verifyConfirmation,
verifyConfirmationNotPresent,
verifyConfirmationPresent,
verifyCookie,
verifyCookieByName,
verifyCookieNotPresent,
verifyCookiePresent,
verifyCssCount,
verifyCursorPosition,
verifyEditable,
verifyElementHeight,
verifyElementIndex,
verifyElementNotPresent,
verifyElementPositionLeft,
verifyElementPositionTop,
verifyElementPresent,
verifyElementWidth,
verifyEval,
verifyExpression,
verifyHtmlSource,
verifyLocation,
verifyMouseSpeed,
verifyNotAlert,
verifyNotAllButtons,
verifyNotAllFields,
verifyNotAllLinks,
verifyNotAllWindowIds,
verifyNotAllWindowNames,
verifyNotAllWindowTitles,
verifyNotAttribute,
verifyNotAttributeFromAllWindows,
verifyNotBodyText,
verifyNotChecked,
verifyNotConfirmation,
verifyNotCookie,
verifyNotCookieByName,
verifyNotCssCount,
verifyNotCursorPosition,
verifyNotEditable,
verifyNotElementHeight,
verifyNotElementIndex,
verifyNotElementPositionLeft,
verifyNotElementPositionTop,
verifyNotElementWidth,
verifyNotEval,
verifyNotExpression,
verifyNotHtmlSource,
verifyNotLocation,
verifyNotMouseSpeed,
verifyNotOrdered,
verifyNotPrompt,
verifyNotSelectOptions,
verifyNotSelectedId,
verifyNotSelectedIds,
verifyNotSelectedIndex,
verifyNotSelectedIndexes,
verifyNotSelectedLabel,
verifyNotSelectedLabels,
verifyNotSelectedValue,
verifyNotSelectedValues,
verifyNotSomethingSelected,
verifyNotSpeed,
verifyNotTable,
verifyNotText,
verifyNotTitle,
verifyNotValue,
verifyNotVisible,
verifyNotWhetherThisFrameMatchFrameExpression,
verifyNotWhetherThisWindowMatchWindowExpression,
verifyNotXpathCount,
verifyOrdered,
verifyPrompt,
verifyPromptNotPresent,
verifyPromptPresent,
verifySelectOptions,
verifySelectedId,
verifySelectedIds,
verifySelectedIndex,
verifySelectedIndexes,
verifySelectedLabel,
verifySelectedLabels,
verifySelectedValue,
verifySelectedValues,
verifySomethingSelected,
verifySpeed,
verifyTable,
verifyText,
verifyTextNotPresent,
verifyTextPresent,
verifyTitle,
verifyValue,
verifyVisible,
verifyWhetherThisFrameMatchFrameExpression,
verifyWhetherThisWindowMatchWindowExpression,
verifyXpathCount,
waitForAlert,
waitForAlertNotPresent,
waitForAlertPresent,
waitForAllButtons,
waitForAllFields,
waitForAllLinks,
waitForAllWindowIds,
waitForAllWindowNames,
waitForAllWindowTitles,
waitForAttribute,
waitForAttributeFromAllWindows,
waitForBodyText,
waitForChecked,
waitForCondition,
waitForConfirmation,
waitForConfirmationNotPresent,
waitForConfirmationPresent,
waitForCookie,
waitForCookieByName,
waitForCookieNotPresent,
waitForCookiePresent,
waitForCssCount,
waitForCursorPosition,
waitForEditable,
waitForElementHeight,
waitForElementIndex,
waitForElementNotPresent,
waitForElementPositionLeft,
waitForElementPositionTop,
waitForElementPresent,
waitForElementWidth,
waitForExpression,
waitForEval,
waitForFrameToLoad,
waitForHtmlSource,
waitForLocation,
waitForMouseSpeed,
waitForNotAlert,
waitForNotAllButtons,
waitForNotAllFields,
waitForNotAllLinks,
waitForNotAllWindowIds,
waitForNotAllWindowNames,
waitForNotAllWindowTitles,
waitForNotAttribute,
waitForNotAttributeFromAllWindows,
waitForNotBodyText,
waitForNotChecked,
waitForNotConfirmation,
waitForNotCookie,
waitForNotCookieByName,
waitForNotCssCount,
waitForNotCursorPosition,
waitForNotEditable,
waitForNotElementHeight,
waitForNotElementIndex,
waitForNotElementPositionLeft,
waitForNotElementPositionTop,
waitForNotElementWidth,
waitForNotEval,
waitForNotExpression,
waitForNotHtmlSource,
waitForNotLocation,
waitForNotMouseSpeed,
waitForNotOrdered,
waitForNotPrompt,
waitForNotSelectOptions,
waitForNotSelectedId,
waitForNotSelectedIds,
waitForNotSelectedIndex,
waitForNotSelectedIndexes,
waitForNotSelectedLabel,
waitForNotSelectedLabels,
waitForNotSelectedValue,
waitForNotSelectedValues,
waitForNotSomethingSelected,
waitForNotSpeed,
waitForNotTable,
waitForNotText,
waitForNotTitle,
waitForNotValue,
waitForNotVisible,
waitForNotWhetherThisFrameMatchFrameExpression,
waitForNotWhetherThisWindowMatchWindowExpression,
waitForNotXpathCount,
waitForOrdered,
waitForPageToLoad,
waitForPopUp,
waitForPrompt,
waitForPromptNotPresent,
waitForPromptPresent,
waitForSelectOptions,
waitForSelectedId,
waitForSelectedIds,
waitForSelectedIndex,
waitForSelectedIndexes,
waitForSelectedLabel,
waitForSelectedLabels,
waitForSelectedValue,
waitForSelectedValues,
waitForSomethingSelected,
waitForSpeed,
waitForTable,
waitForText,
waitForTextNotPresent,
waitForTextPresent,
waitForTitle,
waitForValue,
waitForVisible,
waitForWhetherThisFrameMatchFrameExpression,
waitForWhetherThisWindowMatchWindowExpression,
waitForXpathCount,
windowFocus,
windowFocusAndWait,
windowMaximize,
windowMaximizeAndWait;
//@formatter:on
// =========================================================================
// ENUM METHODS
// =========================================================================
private int hash = 0;
private SeleniumActionType() {
this.hash = name().hashCode();
}
/**
* Gets the enum.
*
* @param name the name
* @return the enum
*/
public static SeleniumActionType getEnum(final String name) {
SeleniumActionType res = null;
if (name != null) {
for (SeleniumActionType item : SeleniumActionType.values()) {
if (item.name().equals(name)) {
res = item;
break;
}
}
}
return res;
}
public int getHash() {
return hash;
}
}
|
3e182b83594fc9486044327899834ce7eb551875 | 973 | java | Java | src/engine/TestPlayer.java | lakes1126/CS-2D | 633e07129e09d37eb31552f43f1a777372387739 | [
"Apache-2.0"
] | null | null | null | src/engine/TestPlayer.java | lakes1126/CS-2D | 633e07129e09d37eb31552f43f1a777372387739 | [
"Apache-2.0"
] | null | null | null | src/engine/TestPlayer.java | lakes1126/CS-2D | 633e07129e09d37eb31552f43f1a777372387739 | [
"Apache-2.0"
] | null | null | null | 19.078431 | 85 | 0.586845 | 10,279 | package engine;
import java.awt.Color;
import java.awt.Graphics;
public class TestPlayer extends Entity{
public TestPlayer(int xPos, int yPos, int width, int height, String imgPath) {
super(xPos, yPos, width, height, imgPath);
}
public void playerDim() {
setHeight(100);
setWidth(100);
}
public void displayDim() {
System.out.println("Player height = " + getHeight() + " , width = " + getWidth());
}
public void drawPlayer(Graphics g) {
g.setColor(Color.RED);
g.drawRect(getXPos(), getYPos(), getWidth(), getHeight());
g.fillRect(getXPos(), getYPos(), getWidth(), getHeight());
}
public void movePlayer() {
if(KeyInput.Keys[0] == true) {
setYPos(getYPos() - 2);
}
if(KeyInput.Keys[1] == true) {
setXPos(getXPos() - 2);
}
if(KeyInput.Keys[2] == true) {
setYPos(getYPos() + 2);
}
if(KeyInput.Keys[3] == true) {
setXPos(getXPos() + 2);
}
}
}
|
3e182c5749d3a6288d0d510dbe44352ba8242d51 | 865 | java | Java | src/main/java/com/demo/api/user/domain/PropertyOwner.java | tntsl/mini-program | 710a3164df5b10efea7f705f470c3834a03a0156 | [
"BSD-3-Clause"
] | 2 | 2020-01-04T14:30:01.000Z | 2020-09-22T06:41:29.000Z | src/main/java/com/demo/api/user/domain/PropertyOwner.java | tntsl/mini-program | 710a3164df5b10efea7f705f470c3834a03a0156 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/demo/api/user/domain/PropertyOwner.java | tntsl/mini-program | 710a3164df5b10efea7f705f470c3834a03a0156 | [
"BSD-3-Clause"
] | 3 | 2019-01-28T07:09:59.000Z | 2020-01-04T14:30:39.000Z | 22.763158 | 62 | 0.716763 | 10,280 | package com.demo.api.user.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author Lye
*/
@TableName("dt_property_owners")
@Data
public class PropertyOwner {
/**
* 资料类型:用户信息
*/
public static final Integer OWNER_TYPE_USER_INFO = 1;
/**
* 资料类型:产权人信息
*/
public static final Integer OWNER_TYPE_PROPERTY_OWNER = 2;
@TableId
private Integer id;
private Integer belongAccount;
private String name;
private String mobile;
private String certificate;
private String idCard;
private String address;
private Boolean isDefault;
private Date createTime;
private Date modifyTime;
private BigDecimal propertyProprotion;
private Integer type;
}
|
3e182cb9ee0bc2730195b71e3cd9e2731e4e9d35 | 303 | java | Java | program_data/github_java_sort_function/9/115.java | yifan-zhou19/ggnn_graph_classification | 37bca1315fdf95933f52b4cd504ce89a768a86df | [
"MIT"
] | 19 | 2019-02-26T05:43:39.000Z | 2022-02-21T04:14:46.000Z | program_data/github_java_sort_function/9/115.java | yifan-zhou19/ggnn_graph_classification | 37bca1315fdf95933f52b4cd504ce89a768a86df | [
"MIT"
] | null | null | null | program_data/github_java_sort_function/9/115.java | yifan-zhou19/ggnn_graph_classification | 37bca1315fdf95933f52b4cd504ce89a768a86df | [
"MIT"
] | 8 | 2018-12-25T02:05:41.000Z | 2022-02-23T07:50:48.000Z | 23.307692 | 68 | 0.429043 | 10,281 | public static <T extends Comparable<? super T>> int sort(T[] a) {
writes = 0;
int N = a.length;
for (int i = 0; i < N; i++) {
int min = i;
for (int j = i+1; j < N; j++)
if (less(a[j], a[min])) min = j;
exch(a, i, min);
}
return writes;
} |
3e182d3d20eb0189a0ae1b14d1d48bc79df013b2 | 1,295 | java | Java | src/main/java/com/chothuesach/controller/NguoiDungController.java | ntduy96/book-rental-system | 2c87c1f3f24e03e6ad232c01bba97ee3e342ab72 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/chothuesach/controller/NguoiDungController.java | ntduy96/book-rental-system | 2c87c1f3f24e03e6ad232c01bba97ee3e342ab72 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/chothuesach/controller/NguoiDungController.java | ntduy96/book-rental-system | 2c87c1f3f24e03e6ad232c01bba97ee3e342ab72 | [
"Apache-2.0"
] | null | null | null | 30.116279 | 195 | 0.696525 | 10,282 | package com.chothuesach.controller;
import com.chothuesach.model.NguoiDung;
import com.chothuesach.service.NguoiDungService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
@RestController
@RequestMapping("/api/nguoidung")
public class NguoiDungController {
@Autowired
private NguoiDungService nguoiDungService;
@GetMapping("/{username}")
public NguoiDung getByUsername(@PathVariable String username) {
return nguoiDungService.getOneByUsername(username);
}
@PostMapping("/check")
public HashMap<String, Boolean> checkExist(@RequestParam(required = false) String tenNguoiDung, @RequestParam(required = false) String email, @RequestParam(required = false) String soCmnd) {
HashMap<String, Boolean> response = new HashMap<>();
if (tenNguoiDung != null) {
response.put("tenNguoiDungExist", nguoiDungService.tenNguoiDungExist(tenNguoiDung));
}
if (email != null) {
response.put("emailExist", nguoiDungService.emailExist(email));
}
if (soCmnd != null) {
response.put("soCmndExist", nguoiDungService.soCmndExist(soCmnd));
}
return response;
}
}
|
3e182d6ae24d2a1be781600ff832ad0c2bdae5b0 | 996 | java | Java | kendzi3d-plugin/src/main/java/kendzi/josm/kendzi3d/jogl/layer/models/OrList.java | filedos9ig1d/kendzi0 | 6722da8fca52d5fbc1f1a8e20772d74f6f4b7641 | [
"BSD-3-Clause"
] | 45 | 2015-04-05T07:24:05.000Z | 2022-02-17T17:29:54.000Z | kendzi3d-plugin/src/main/java/kendzi/josm/kendzi3d/jogl/layer/models/OrList.java | filedos9ig1d/kendzi0 | 6722da8fca52d5fbc1f1a8e20772d74f6f4b7641 | [
"BSD-3-Clause"
] | 56 | 2015-01-18T17:24:19.000Z | 2022-03-09T22:21:52.000Z | kendzi3d-plugin/src/main/java/kendzi/josm/kendzi3d/jogl/layer/models/OrList.java | filedos9ig1d/kendzi0 | 6722da8fca52d5fbc1f1a8e20772d74f6f4b7641 | [
"BSD-3-Clause"
] | 15 | 2015-03-09T03:35:44.000Z | 2022-02-15T23:25:05.000Z | 19.92 | 68 | 0.514056 | 10,283 | package kendzi.josm.kendzi3d.jogl.layer.models;
import java.util.List;
import org.openstreetmap.josm.data.osm.search.SearchCompiler.Match;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
/**
* Or match on list.
*
* @author Tomasz Kędziora (kendzi)
*
*/
public class OrList extends Match {
private final List<Match> lhs;
/**
* @param lhs list of match
*/
public OrList(List<Match> lhs) {
this.lhs = lhs;
}
@Override
public boolean match(OsmPrimitive osm) {
for (Match m : this.lhs) {
if (m.match(osm)) {
return true;
}
}
return false;
}
@Override
public String toString() {
String ret = "";
for (Match m : this.lhs) {
ret += " || " + m;
}
return ret;
}
/**
* @return list of match
*/
public List<Match> getLhs() {
return this.lhs;
}
}
|
3e182ede1416168fe245b811978ef7f7e9fabfa2 | 8,883 | java | Java | searchview/src/main/java/com/lapism/searchview/SearchAdapter.java | adetuyiTolu/SearchView | 34065b8c3a2ad48c5a3ef185ecfd3da471312be0 | [
"Apache-2.0"
] | 1 | 2017-12-14T14:30:51.000Z | 2017-12-14T14:30:51.000Z | searchview/src/main/java/com/lapism/searchview/SearchAdapter.java | adetuyiTolu/SearchView | 34065b8c3a2ad48c5a3ef185ecfd3da471312be0 | [
"Apache-2.0"
] | null | null | null | searchview/src/main/java/com/lapism/searchview/SearchAdapter.java | adetuyiTolu/SearchView | 34065b8c3a2ad48c5a3ef185ecfd3da471312be0 | [
"Apache-2.0"
] | 2 | 2018-05-04T19:14:14.000Z | 2021-05-16T17:56:50.000Z | 36.706612 | 190 | 0.572554 | 10,284 | package com.lapism.searchview;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@SuppressWarnings({"unused", "WeakerAccess"})
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ResultViewHolder> implements Filterable {
private final SearchHistoryTable mHistoryDatabase;
public Integer mDatabaseKey = null;
private List<SearchItem> mSuggestionsList = new ArrayList<>();
private String key = "";
private List<SearchItem> mResultList = new ArrayList<>();
private List<OnItemClickListener> mItemClickListeners;
// ---------------------------------------------------------------------------------------------
public SearchAdapter(Context context) {
mHistoryDatabase = new SearchHistoryTable(context);
getFilter().filter("");
}
public SearchAdapter(Context context, List<SearchItem> suggestionsList) {
mSuggestionsList = suggestionsList;
mResultList = suggestionsList;
mHistoryDatabase = new SearchHistoryTable(context);// TODO PUT DB IN VIEW
getFilter().filter("");
}
// ---------------------------------------------------------------------------------------------
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
key = constraint.toString().toLowerCase(Locale.getDefault());
List<SearchItem> results = new ArrayList<>();
List<SearchItem> history = new ArrayList<>();
List<SearchItem> databaseAllItems = mHistoryDatabase.getAllItems(mDatabaseKey);
if (!databaseAllItems.isEmpty()) {
history.addAll(databaseAllItems);
}
history.addAll(mSuggestionsList);
for (SearchItem item : history) {
String string = item.get_text().toString().toLowerCase(Locale.getDefault());
if (string.contains(key)) {
results.add(item);
}// TODO ADVANCED COMPARE METHOD
}
if (results.size() > 0) {
filterResults.values = results;
filterResults.count = results.size();
}
} else {
key = "";
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
List<SearchItem> dataSet = new ArrayList<>();
if (results.count > 0) {
List<?> result = (ArrayList<?>) results.values;
for (Object object : result) {
if (object instanceof SearchItem) {
dataSet.add((SearchItem) object);
}
}
} else {
if (key.isEmpty()) {
if (!mSuggestionsList.isEmpty()) {
dataSet = mSuggestionsList;
} else {
List<SearchItem> allItems = mHistoryDatabase.getAllItems(mDatabaseKey);
if (!allItems.isEmpty()) {
dataSet = allItems;
}
}
}
}
setData(dataSet);
}
};
}
@Override
public ResultViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.search_item, parent, false);
return new ResultViewHolder(view);
}
@Override
public void onBindViewHolder(ResultViewHolder viewHolder, int position) {
SearchItem item = mResultList.get(position);
viewHolder.icon_left.setImageResource(item.get_icon());
viewHolder.icon_left.setColorFilter(SearchView.getIconColor(), PorterDuff.Mode.SRC_IN);
viewHolder.text.setTypeface((Typeface.create(SearchView.getTextFont(), SearchView.getTextStyle())));
viewHolder.text.setTextColor(SearchView.getTextColor());
String itemText = item.get_text().toString();
String itemTextLower = itemText.toLowerCase(Locale.getDefault());
if (itemTextLower.contains(key) && !key.isEmpty()) {
SpannableString s = new SpannableString(itemText);
s.setSpan(new ForegroundColorSpan(SearchView.getTextHighlightColor()), itemTextLower.indexOf(key), itemTextLower.indexOf(key) + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
viewHolder.text.setText(s, TextView.BufferType.SPANNABLE);
} else {
viewHolder.text.setText(item.get_text());
}
viewHolder.id_tag = item.get_tag();
}
@Override
public int getItemCount() {
return mResultList.size();
}
@Override
public int getItemViewType(int position) {
return position;
}
public List<SearchItem> getSuggestionsList() {
return mSuggestionsList;
}
// ---------------------------------------------------------------------------------------------
public void setSuggestionsList(List<SearchItem> suggestionsList) {
mSuggestionsList = suggestionsList;
mResultList = suggestionsList;
}
public void setDatabaseKey(Integer key) {
mDatabaseKey = key;
getFilter().filter("");
}
@Deprecated
public void setOnItemClickListener(OnItemClickListener mItemClickListener) {
addOnItemClickListener(mItemClickListener);
}
public void addOnItemClickListener(OnItemClickListener listener) {
addOnItemClickListener(listener, null);
}
public void addOnItemClickListener(OnItemClickListener listener, Integer position) {
if (mItemClickListeners == null)
mItemClickListeners = new ArrayList<>();
if (position == null)
mItemClickListeners.add(listener);
else
mItemClickListeners.add(position, listener);
}
public void setData(List<SearchItem> data) {
if (mResultList.size() == 0) {
mResultList = data;
if (data.size() != 0) {
notifyItemRangeInserted(0, data.size());
}
} else {
int previousSize = mResultList.size();
int nextSize = data.size();
mResultList = data;
if (previousSize == nextSize && nextSize != 0)
notifyItemRangeChanged(0, previousSize);
else if (previousSize > nextSize) {
if (nextSize == 0)
notifyItemRangeRemoved(0, previousSize);
else {
notifyItemRangeChanged(0, nextSize);
notifyItemRangeRemoved(nextSize - 1, previousSize);
}
} else {
notifyItemRangeChanged(0, previousSize);
notifyItemRangeInserted(previousSize, nextSize - previousSize);
}
}
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public class ResultViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected String id_tag;
final ImageView icon_left;
final TextView text;
public ResultViewHolder(View view) {
super(view);
icon_left = (ImageView) view.findViewById(R.id.imageView_item_icon_left);
text = (TextView) view.findViewById(R.id.textView_item_text);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mItemClickListeners != null) {
for (OnItemClickListener listener : mItemClickListeners) {
v.setTag(id_tag);
listener.onItemClick(v, getLayoutPosition());
}
}
}
}
}
|
3e182ef20d699265c72e48d9fc75ec76c8f42746 | 1,233 | java | Java | x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CcrDisabledIT.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 3 | 2017-05-31T14:46:18.000Z | 2022-02-15T08:04:05.000Z | x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CcrDisabledIT.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 23 | 2019-08-09T06:41:49.000Z | 2021-06-25T15:21:21.000Z | x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CcrDisabledIT.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 2 | 2020-02-03T07:05:44.000Z | 2020-02-05T01:51:57.000Z | 35.228571 | 124 | 0.759124 | 10,285 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ccr;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.xpack.core.XPackSettings;
import java.util.Collection;
import java.util.Collections;
public class CcrDisabledIT extends ESIntegTestCase {
public void testClusterCanStartWithCcrInstalledButNotEnabled() throws Exception {
// TODO: Assert that x-pack ccr feature is not enabled once feature functionality has been added
ensureGreen();
}
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder().put(super.nodeSettings(nodeOrdinal)).put(XPackSettings.CCR_ENABLED_SETTING.getKey(), true)
.put(XPackSettings.SECURITY_ENABLED.getKey(), false).build();
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singletonList(LocalStateCcr.class);
}
}
|
3e182fffb4ad2947bac381f8ffd61001ca5ab547 | 1,595 | java | Java | projects/previousProjects/eCarStreet/src/main/java/eCarStreet/eCar/helper/decisions/PriceOptimizedDecision.java | SES-fortiss/SmartGridCoSimulation | f36af788b2c4de0e63688cd8faf0b0645c20264a | [
"Apache-2.0"
] | 10 | 2018-03-14T15:47:10.000Z | 2022-01-16T14:21:49.000Z | projects/previousProjects/eCarStreet/src/main/java/eCarStreet/eCar/helper/decisions/PriceOptimizedDecision.java | SES-fortiss/SmartGridCoSimulation | f36af788b2c4de0e63688cd8faf0b0645c20264a | [
"Apache-2.0"
] | 132 | 2019-08-27T15:01:56.000Z | 2022-02-16T01:15:51.000Z | projects/previousProjects/eCarStreet/src/main/java/eCarStreet/eCar/helper/decisions/PriceOptimizedDecision.java | SES-fortiss/SmartGridCoSimulation | f36af788b2c4de0e63688cd8faf0b0645c20264a | [
"Apache-2.0"
] | 7 | 2017-12-11T11:33:13.000Z | 2021-09-16T03:03:20.000Z | 28.482143 | 99 | 0.715987 | 10,286 | /*
* Copyright (c) 2011-2015, fortiss GmbH.
* Licensed under the Apache License, Version 2.0.
*
* Use, modification and distribution are subject to the terms specified
* in the accompanying license file LICENSE.txt located at the root directory
* of this software distribution.
*/
package eCarStreet.eCar.helper.decisions;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import eCarStreet.eCar.ECar;
import eCarStreet.helper.PricePrognosis;
public class PriceOptimizedDecision implements Decision {
Optimizer optimizer = null;
OptimizationPoint[] fahrplan;
@Override
public double getDemand(ECar eCar, LocalDateTime time, Duration period) {
if (optimizer == null){
calculateOptimizedFahrplan(eCar, period);
}
double power = 0.0;
LocalTime internalTime = LocalTime.of(time.getHour(), time.getMinute());
for (int i = 0; i < fahrplan.length-1; i++) {
if (internalTime.compareTo(fahrplan[i].time) >= 0
&& ( (internalTime.compareTo(fahrplan[i+1].time) < 0)
|| fahrplan[i+1].time.compareTo(LocalTime.of(0, 0)) == 0) ) {
power = fahrplan[i].nextPowerDemand;
eCar.setSOC(fahrplan[i+1].SOC);
}
}
return -power;
}
public void calculateOptimizedFahrplan(ECar eCar, Duration period) {
if (period == null) period = Duration.ofMinutes(15);
optimizer = new Optimizer(eCar, period);
PricePrognosis pp = new PricePrognosis();
double[] preisArray = pp.convertPricePrognosisToDoubleArray(optimizer.timeN, eCar.arrivalTime);
fahrplan = optimizer.optimize(preisArray);
}
}
|
3e18300b9adf9a64ac5087b8b7a85eba874d9663 | 7,741 | java | Java | bmob/src/main/java/com/chaos/bmob/kit/BmobKit.java | snpmyn/Chaos | 7839e43da4473bf1d00035c4755751cc8d610822 | [
"Apache-2.0"
] | null | null | null | bmob/src/main/java/com/chaos/bmob/kit/BmobKit.java | snpmyn/Chaos | 7839e43da4473bf1d00035c4755751cc8d610822 | [
"Apache-2.0"
] | null | null | null | bmob/src/main/java/com/chaos/bmob/kit/BmobKit.java | snpmyn/Chaos | 7839e43da4473bf1d00035c4755751cc8d610822 | [
"Apache-2.0"
] | null | null | null | 29.773077 | 135 | 0.599793 | 10,287 | package com.chaos.bmob.kit;
import androidx.annotation.NonNull;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
/**
* Created on 2021/2/5
*
* @author zsp
* @desc Bmob 配套元件
* 为提供更稳定服务,后端启用 QPS 限制。推荐采用批量数据操作替换于循环多次提交请求操作,否则 QPS 达到限制报错。
* 1. 批量操作每次只支持最大 50 条记录操作。
* 2. 批量操作不支持对 User 表操作。
* <p>
* insertBatch 批量添加数据(返所添加数据 objectId 字段)
* updateBatch 批量更新数据
* deleteBatch 批量删除数据
* doBatch 批量添加、批量更新、批量删除同时操作
*/
public class BmobKit {
private static BmobKit instance;
public static BmobKit getInstance() {
if (null == instance) {
synchronized (BmobKit.class) {
if (null == instance) {
instance = new BmobKit();
}
}
}
return instance;
}
/**
* 单个保存
*
* @param t T
* @param saveListener 保存监听
* @param <T> <T>
*/
public <T extends BmobObject> void singleSave(@NotNull T t, SaveListener<String> saveListener) {
t.save(saveListener);
}
/**
* 多个保存
*
* @param bmobObjectList 数据集合
* @param queryListListener 查询集合监听
*/
public void multiSave(List<BmobObject> bmobObjectList, QueryListListener<BatchResult> queryListListener) {
new BmobBatch().insertBatch(bmobObjectList).doBatch(queryListListener);
}
/**
* 单个删除
*
* @param t T
* @param objectId 数据唯一标示
* @param updateListener 更新监听
* @param <T> <T>
*/
public <T extends BmobObject> void singleDelete(@NotNull T t, String objectId, UpdateListener updateListener) {
t.delete(objectId, updateListener);
}
/**
* 多个删除
*
* @param bmobObjectList 数据集合(所含对象仅需设被删数据之 objectId)
* @param queryListListener 查询集合监听
*/
public void multiDelete(List<BmobObject> bmobObjectList, QueryListListener<BatchResult> queryListListener) {
new BmobBatch().deleteBatch(bmobObjectList).doBatch(queryListListener);
}
/**
* 单个更新
*
* @param t T
* @param objectId 数据唯一标示
* @param updateListener 更新监听
* @param <T> <T>
*/
public <T extends BmobObject> void singleUpdate(@NotNull T t, String objectId, UpdateListener updateListener) {
t.update(objectId, updateListener);
}
/**
* 多个更新
*
* @param bmobObjectList 数据集合
* @param queryListListener 查询集合监听
*/
public void multiUpdate(List<BmobObject> bmobObjectList, QueryListListener<BatchResult> queryListListener) {
new BmobBatch().updateBatch(bmobObjectList).doBatch(queryListListener);
}
/**
* 单个查询
*
* @param objectId 对象 ID
* @param queryListener 查询监听
* @param <T> <T>
*/
public <T extends BmobObject> void singleQuery(String objectId, QueryListener<T> queryListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.getObject(objectId, queryListener);
}
/**
* 多个查询
*
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void multiQuery(FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.findObjects(findListener);
}
/**
* 等于查询
*
* @param key 键
* @param value 值
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereEqualTo(String key, Object value, FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereEqualTo(key, value);
bmobQuery.findObjects(findListener);
}
/**
* 并且等于查询
*
* @param key 并且等于查询
* @param values 值数组
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereEqualToWithAnd(String key, @NonNull Object[] values, FindListener<T> findListener) {
List<BmobQuery<T>> bmobQueryList = new ArrayList<>(values.length);
for (Object value : values) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereEqualTo(key, value);
bmobQueryList.add(bmobQuery);
}
BmobQuery<T> multiBmobQuery = new BmobQuery<>();
multiBmobQuery.and(bmobQueryList);
multiBmobQuery.findObjects(findListener);
}
/**
* 或等于查询
*
* @param key 并且等于查询
* @param values 值数组
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereEqualToWithOr(String key, @NonNull Object[] values, FindListener<T> findListener) {
List<BmobQuery<T>> bmobQueryList = new ArrayList<>(values.length);
for (Object value : values) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereEqualTo(key, value);
bmobQueryList.add(bmobQuery);
}
BmobQuery<T> multiBmobQuery = new BmobQuery<>();
multiBmobQuery.or(bmobQueryList);
multiBmobQuery.findObjects(findListener);
}
/**
* 不等于查询
*
* @param key 键
* @param value 值
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereNotEqualTo(String key, Object value, FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereNotEqualTo(key, value);
bmobQuery.findObjects(findListener);
}
/**
* 小于查询
*
* @param key 键
* @param value 值
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereLessThan(String key, Object value, FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereLessThan(key, value);
bmobQuery.findObjects(findListener);
}
/**
* 小于等于查询
*
* @param key 键
* @param value 值
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereLessThanOrEqualTo(String key, Object value, FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereLessThanOrEqualTo(key, value);
bmobQuery.findObjects(findListener);
}
/**
* 大于查询
*
* @param key 键
* @param value 值
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereGreaterThan(String key, Object value, FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereGreaterThan(key, value);
bmobQuery.findObjects(findListener);
}
/**
* 大于等于查询
*
* @param key 键
* @param value 值
* @param findListener 查找监听
* @param <T> <T>
*/
public <T extends BmobObject> void queryByWhereGreaterThanOrEqualTo(String key, Object value, FindListener<T> findListener) {
BmobQuery<T> bmobQuery = new BmobQuery<>();
bmobQuery.addWhereGreaterThanOrEqualTo(key, value);
bmobQuery.findObjects(findListener);
}
}
|
3e18307cc19420f0be00b74e62e61fde79f34329 | 21,084 | java | Java | google/cloud/aiplatform/v1/google-cloud-aiplatform-v1-java/proto-google-cloud-aiplatform-v1-java/src/main/java/com/google/cloud/aiplatform/v1/MigrationServiceProto.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/aiplatform/v1/google-cloud-aiplatform-v1-java/proto-google-cloud-aiplatform-v1-java/src/main/java/com/google/cloud/aiplatform/v1/MigrationServiceProto.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/aiplatform/v1/google-cloud-aiplatform-v1-java/proto-google-cloud-aiplatform-v1-java/src/main/java/com/google/cloud/aiplatform/v1/MigrationServiceProto.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | 68.012903 | 178 | 0.799991 | 10,288 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/migration_service.proto
package com.google.cloud.aiplatform.v1;
public final class MigrationServiceProto {
private MigrationServiceProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateMlEngineModelVersionConfig_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateMlEngineModelVersionConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlModelConfig_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlModelConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlDatasetConfig_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlDatasetConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_MigrateDataLabelingAnnotatedDatasetConfig_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_MigrateDataLabelingAnnotatedDatasetConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_MigrateResourceResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_MigrateResourceResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_PartialResult_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_PartialResult_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n2google/cloud/aiplatform/v1/migration_s" +
"ervice.proto\022\032google.cloud.aiplatform.v1" +
"\032(google/cloud/aiplatform/v1/dataset.pro" +
"to\032&google/cloud/aiplatform/v1/model.pro" +
"to\032\034google/api/annotations.proto\032\027google" +
"/api/client.proto\032\037google/api/field_beha" +
"vior.proto\032\031google/api/resource.proto\0324g" +
"oogle/cloud/aiplatform/v1/migratable_res" +
"ource.proto\032*google/cloud/aiplatform/v1/" +
"operation.proto\032#google/longrunning/oper" +
"ations.proto\032\027google/rpc/status.proto\"\224\001" +
"\n SearchMigratableResourcesRequest\0229\n\006pa" +
"rent\030\001 \001(\tB)\340A\002\372A#\n!locations.googleapis" +
".com/Location\022\021\n\tpage_size\030\002 \001(\005\022\022\n\npage" +
"_token\030\003 \001(\t\022\016\n\006filter\030\004 \001(\t\"\212\001\n!SearchM" +
"igratableResourcesResponse\022L\n\024migratable" +
"_resources\030\001 \003(\0132..google.cloud.aiplatfo" +
"rm.v1.MigratableResource\022\027\n\017next_page_to" +
"ken\030\002 \001(\t\"\265\001\n\034BatchMigrateResourcesReque" +
"st\0229\n\006parent\030\001 \001(\tB)\340A\002\372A#\n!locations.go" +
"ogleapis.com/Location\022Z\n\031migrate_resourc" +
"e_requests\030\002 \003(\01322.google.cloud.aiplatfo" +
"rm.v1.MigrateResourceRequestB\003\340A\002\"\342\n\n\026Mi" +
"grateResourceRequest\022\206\001\n&migrate_ml_engi" +
"ne_model_version_config\030\001 \001(\0132T.google.c" +
"loud.aiplatform.v1.MigrateResourceReques" +
"t.MigrateMlEngineModelVersionConfigH\000\022r\n" +
"\033migrate_automl_model_config\030\002 \001(\0132K.goo" +
"gle.cloud.aiplatform.v1.MigrateResourceR" +
"equest.MigrateAutomlModelConfigH\000\022v\n\035mig" +
"rate_automl_dataset_config\030\003 \001(\0132M.googl" +
"e.cloud.aiplatform.v1.MigrateResourceReq" +
"uest.MigrateAutomlDatasetConfigH\000\022\203\001\n$mi" +
"grate_data_labeling_dataset_config\030\004 \001(\013" +
"2S.google.cloud.aiplatform.v1.MigrateRes" +
"ourceRequest.MigrateDataLabelingDatasetC" +
"onfigH\000\032\225\001\n!MigrateMlEngineModelVersionC" +
"onfig\022\025\n\010endpoint\030\001 \001(\tB\003\340A\002\0228\n\rmodel_ve" +
"rsion\030\002 \001(\tB!\340A\002\372A\033\n\031ml.googleapis.com/V" +
"ersion\022\037\n\022model_display_name\030\003 \001(\tB\003\340A\002\032" +
"o\n\030MigrateAutomlModelConfig\0222\n\005model\030\001 \001" +
"(\tB#\340A\002\372A\035\n\033automl.googleapis.com/Model\022" +
"\037\n\022model_display_name\030\002 \001(\tB\003\340A\001\032w\n\032Migr" +
"ateAutomlDatasetConfig\0226\n\007dataset\030\001 \001(\tB" +
"%\340A\002\372A\037\n\035automl.googleapis.com/Dataset\022!" +
"\n\024dataset_display_name\030\002 \001(\tB\003\340A\002\032\277\003\n Mi" +
"grateDataLabelingDatasetConfig\022<\n\007datase" +
"t\030\001 \001(\tB+\340A\002\372A%\n#datalabeling.googleapis" +
".com/Dataset\022!\n\024dataset_display_name\030\002 \001" +
"(\tB\003\340A\001\022\273\001\n/migrate_data_labeling_annota" +
"ted_dataset_configs\030\003 \003(\0132}.google.cloud" +
".aiplatform.v1.MigrateResourceRequest.Mi" +
"grateDataLabelingDatasetConfig.MigrateDa" +
"taLabelingAnnotatedDatasetConfigB\003\340A\001\032|\n" +
")MigrateDataLabelingAnnotatedDatasetConf" +
"ig\022O\n\021annotated_dataset\030\001 \001(\tB4\340A\002\372A.\n,d" +
"atalabeling.googleapis.com/AnnotatedData" +
"setB\t\n\007request\"x\n\035BatchMigrateResourcesR" +
"esponse\022W\n\032migrate_resource_responses\030\001 " +
"\003(\01323.google.cloud.aiplatform.v1.Migrate" +
"ResourceResponse\"\355\001\n\027MigrateResourceResp" +
"onse\0229\n\007dataset\030\001 \001(\tB&\372A#\n!aiplatform.g" +
"oogleapis.com/DatasetH\000\0225\n\005model\030\002 \001(\tB$" +
"\372A!\n\037aiplatform.googleapis.com/ModelH\000\022K" +
"\n\023migratable_resource\030\003 \001(\0132..google.clo" +
"ud.aiplatform.v1.MigratableResourceB\023\n\021m" +
"igrated_resource\"\333\003\n&BatchMigrateResourc" +
"esOperationMetadata\022N\n\020generic_metadata\030" +
"\001 \001(\01324.google.cloud.aiplatform.v1.Gener" +
"icOperationMetadata\022i\n\017partial_results\030\002" +
" \003(\0132P.google.cloud.aiplatform.v1.BatchM" +
"igrateResourcesOperationMetadata.Partial" +
"Result\032\365\001\n\rPartialResult\022#\n\005error\030\002 \001(\0132" +
"\022.google.rpc.StatusH\000\0225\n\005model\030\003 \001(\tB$\372A" +
"!\n\037aiplatform.googleapis.com/ModelH\000\0229\n\007" +
"dataset\030\004 \001(\tB&\372A#\n!aiplatform.googleapi" +
"s.com/DatasetH\000\022C\n\007request\030\001 \001(\01322.googl" +
"e.cloud.aiplatform.v1.MigrateResourceReq" +
"uestB\010\n\006result2\202\005\n\020MigrationService\022\354\001\n\031" +
"SearchMigratableResources\022<.google.cloud" +
".aiplatform.v1.SearchMigratableResources" +
"Request\032=.google.cloud.aiplatform.v1.Sea" +
"rchMigratableResourcesResponse\"R\202\323\344\223\002C\">" +
"/v1/{parent=projects/*/locations/*}/migr" +
"atableResources:search:\001*\332A\006parent\022\257\002\n\025B" +
"atchMigrateResources\0228.google.cloud.aipl" +
"atform.v1.BatchMigrateResourcesRequest\032\035" +
".google.longrunning.Operation\"\274\001\202\323\344\223\002I\"D" +
"/v1/{parent=projects/*/locations/*}/migr" +
"atableResources:batchMigrate:\001*\332A parent" +
",migrate_resource_requests\312AG\n\035BatchMigr" +
"ateResourcesResponse\022&BatchMigrateResour" +
"cesOperationMetadata\032M\312A\031aiplatform.goog" +
"leapis.com\322A.https://www.googleapis.com/" +
"auth/cloud-platformB\331\001\n\036com.google.cloud" +
".aiplatform.v1B\025MigrationServiceProtoP\001Z" +
"Dgoogle.golang.org/genproto/googleapis/c" +
"loud/aiplatform/v1;aiplatform\252\002\032Google.C" +
"loud.AIPlatform.V1\312\002\032Google\\Cloud\\AIPlat" +
"form\\V1\352\002\035Google::Cloud::AIPlatform::V1b" +
"\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.cloud.aiplatform.v1.DatasetProto.getDescriptor(),
com.google.cloud.aiplatform.v1.ModelProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.cloud.aiplatform.v1.MigratableResourceProto.getDescriptor(),
com.google.cloud.aiplatform.v1.OperationProto.getDescriptor(),
com.google.longrunning.OperationsProto.getDescriptor(),
com.google.rpc.StatusProto.getDescriptor(),
});
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesRequest_descriptor,
new java.lang.String[] { "Parent", "PageSize", "PageToken", "Filter", });
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesResponse_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_SearchMigratableResourcesResponse_descriptor,
new java.lang.String[] { "MigratableResources", "NextPageToken", });
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesRequest_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesRequest_descriptor,
new java.lang.String[] { "Parent", "MigrateResourceRequests", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor,
new java.lang.String[] { "MigrateMlEngineModelVersionConfig", "MigrateAutomlModelConfig", "MigrateAutomlDatasetConfig", "MigrateDataLabelingDatasetConfig", "Request", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateMlEngineModelVersionConfig_descriptor =
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor.getNestedTypes().get(0);
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateMlEngineModelVersionConfig_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateMlEngineModelVersionConfig_descriptor,
new java.lang.String[] { "Endpoint", "ModelVersion", "ModelDisplayName", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlModelConfig_descriptor =
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor.getNestedTypes().get(1);
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlModelConfig_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlModelConfig_descriptor,
new java.lang.String[] { "Model", "ModelDisplayName", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlDatasetConfig_descriptor =
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor.getNestedTypes().get(2);
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlDatasetConfig_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateAutomlDatasetConfig_descriptor,
new java.lang.String[] { "Dataset", "DatasetDisplayName", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_descriptor =
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_descriptor.getNestedTypes().get(3);
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_descriptor,
new java.lang.String[] { "Dataset", "DatasetDisplayName", "MigrateDataLabelingAnnotatedDatasetConfigs", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_MigrateDataLabelingAnnotatedDatasetConfig_descriptor =
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_descriptor.getNestedTypes().get(0);
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_MigrateDataLabelingAnnotatedDatasetConfig_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceRequest_MigrateDataLabelingDatasetConfig_MigrateDataLabelingAnnotatedDatasetConfig_descriptor,
new java.lang.String[] { "AnnotatedDataset", });
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesResponse_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesResponse_descriptor,
new java.lang.String[] { "MigrateResourceResponses", });
internal_static_google_cloud_aiplatform_v1_MigrateResourceResponse_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_aiplatform_v1_MigrateResourceResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_MigrateResourceResponse_descriptor,
new java.lang.String[] { "Dataset", "Model", "MigratableResource", "MigratedResource", });
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_descriptor,
new java.lang.String[] { "GenericMetadata", "PartialResults", });
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_PartialResult_descriptor =
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_descriptor.getNestedTypes().get(0);
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_PartialResult_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_BatchMigrateResourcesOperationMetadata_PartialResult_descriptor,
new java.lang.String[] { "Error", "Model", "Dataset", "Request", "Result", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.methodSignature);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
registry.add(com.google.longrunning.OperationsProto.operationInfo);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
com.google.cloud.aiplatform.v1.DatasetProto.getDescriptor();
com.google.cloud.aiplatform.v1.ModelProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.cloud.aiplatform.v1.MigratableResourceProto.getDescriptor();
com.google.cloud.aiplatform.v1.OperationProto.getDescriptor();
com.google.longrunning.OperationsProto.getDescriptor();
com.google.rpc.StatusProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
3e1831411e9b178719f9b1122446a63d5ae4debd | 857 | java | Java | AI Arena/src/Bullets.java | stopitcarl/JBot-Arena | 140a6f1eefff4ee6308ba857b913acae8866d97f | [
"Apache-2.0"
] | 3 | 2017-07-09T22:25:40.000Z | 2018-02-14T04:36:05.000Z | AI Arena/src/Bullets.java | stopitcarl/JBot-Arena | 140a6f1eefff4ee6308ba857b913acae8866d97f | [
"Apache-2.0"
] | null | null | null | AI Arena/src/Bullets.java | stopitcarl/JBot-Arena | 140a6f1eefff4ee6308ba857b913acae8866d97f | [
"Apache-2.0"
] | null | null | null | 25.205882 | 72 | 0.627771 | 10,289 | import java.awt.Color;
import java.awt.geom.Ellipse2D;
public class Bullets {
final int radius = 20;
double vel = 1;
private long time_bullet = 0L;
private long delta = 0L;
double degree = 0;
static public final Color red = new Color(240, 10, 100);
Ellipse2D.Double bul = null;
public Bullets(double x1, double y1, double deg) {
// System.out.println(x1 + " " + y1 + " " + deg);
bul = new Ellipse2D.Double(x1, y1, radius, radius);
degree = deg;
// System.out.println("Created Bullet: " + bul.getCenterX() + " ; " +
// bul.getCenterY());
}
void moveBullet() {
this.bul.x += this.vel * 10 * Math.cos(degree);
this.bul.y += this.vel * 10 * Math.sin(degree);
}
long getDelta() {
delta = System.currentTimeMillis() - time_bullet;
time_bullet = System.currentTimeMillis();
return delta;
}
}
|
3e1831427a83d4ec8367dbd8e5bb5810d2a16d53 | 636 | java | Java | hello-fxml/src/main/java/org/example/transform/NewTransformApp.java | xuxiaocong/learn-javafx | 1d0ba746bc8590b170431ca3cc4013a277608664 | [
"MIT"
] | null | null | null | hello-fxml/src/main/java/org/example/transform/NewTransformApp.java | xuxiaocong/learn-javafx | 1d0ba746bc8590b170431ca3cc4013a277608664 | [
"MIT"
] | null | null | null | hello-fxml/src/main/java/org/example/transform/NewTransformApp.java | xuxiaocong/learn-javafx | 1d0ba746bc8590b170431ca3cc4013a277608664 | [
"MIT"
] | null | null | null | 25.44 | 88 | 0.683962 | 10,290 | package org.example.transform;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class NewTransformApp extends Application {
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage stage) throws IOException {
// 加载视图文件
FXMLLoader loader = new FXMLLoader(getClass().getResource("newtransform.fxml"));
Scene scene = new Scene(loader.load());
stage.setTitle("fxml窗体-深入理解fxml");
stage.setScene(scene);
stage.show();
}
}
|
3e18314c0861fd0995230b712b1749b42578c91a | 2,210 | java | Java | cloud-s-api/src/main/java/com/cb/platform/yq/api/utils/StampUtils.java | JsonDogLas/dc | 4651ff081ce89913f90aa7a578b33e3b43c1e1c4 | [
"Apache-2.0"
] | 1 | 2019-05-14T07:20:09.000Z | 2019-05-14T07:20:09.000Z | cloud-s-api/src/main/java/com/cb/platform/yq/api/utils/StampUtils.java | JsonDogLas/dc | 4651ff081ce89913f90aa7a578b33e3b43c1e1c4 | [
"Apache-2.0"
] | null | null | null | cloud-s-api/src/main/java/com/cb/platform/yq/api/utils/StampUtils.java | JsonDogLas/dc | 4651ff081ce89913f90aa7a578b33e3b43c1e1c4 | [
"Apache-2.0"
] | 2 | 2018-11-07T11:31:37.000Z | 2019-05-14T07:20:21.000Z | 26.626506 | 100 | 0.562896 | 10,291 | package com.cb.platform.yq.api.utils;
import com.ceba.cebautils.Base64FileUtils;
import org.apache.commons.lang.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class StampUtils {
/**
* 透明章
* @return
*/
public static void transparentStamp(String path)throws Exception{
BufferedImage image= new BufferedImage(1,1, BufferedImage.TYPE_INT_RGB);
// 获取Graphics2D
Graphics2D g2d = image.createGraphics();
image = g2d.getDeviceConfiguration().createCompatibleImage(1, 1, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
g2d.setColor(new Color(255,0,0));
g2d.setStroke(new BasicStroke(1));
g2d.dispose();
g2d.draw(null);
File file=new File(path);
ImageIO.write(image,"png", file);
}
/**
* base64转图片
* @param base64
* @param imageFilePath
*/
public static void base64ToImage(String base64,String imageFilePath){
Base64FileUtils.string2Image(base64, imageFilePath);
}
/**
* 取得base64净化数据
* @return
*/
private static String getBase64PurifyData(String base64){
String[] base64s= StringUtils.split(base64,",");
if(base64s.length == 2){
return base64s[1];
}
return null;
}
/**
* 根据文件名或者文件路径取得文件后缀
* @param path
* @return
*/
public static String fileExt(String path){
if(StringUtils.isNotEmpty(path)){
int index=path.lastIndexOf(".");
if(0<index && index < path.length()){
return path.substring(index+1,path.length());
}
}
return null;
}
/**
* 取得文件名 没有后缀
* @param path
* @return
*/
public static String fileName(String path){
if(StringUtils.isNotEmpty(path)){
int index=path.lastIndexOf(".");
if(0<index && index < path.length()){
return path.substring(0,index);
}
}
return null;
}
}
|
3e1831677a6bb65df972c5cb9e157fb875cb91c5 | 1,372 | java | Java | pokeros/core/src/main/java/pokeros/core/AboutScreen.java | samskivert/mashups | 16d1980fbaa253e5876e4d75c65fc16b1fa735ad | [
"BSD-3-Clause"
] | 3 | 2015-02-25T03:12:25.000Z | 2017-08-28T01:45:20.000Z | pokeros/core/src/main/java/pokeros/core/AboutScreen.java | samskivert/mashups | 16d1980fbaa253e5876e4d75c65fc16b1fa735ad | [
"BSD-3-Clause"
] | null | null | null | pokeros/core/src/main/java/pokeros/core/AboutScreen.java | samskivert/mashups | 16d1980fbaa253e5876e4d75c65fc16b1fa735ad | [
"BSD-3-Clause"
] | 3 | 2015-02-26T10:37:30.000Z | 2017-01-01T23:57:31.000Z | 37.081081 | 98 | 0.60277 | 10,292 | //
// Mashups - a series of mashed up game prototypes
// https://github.com/samskivert/mashups/blob/master/LICENSE
package pokeros.core;
import react.UnitSlot;
import tripleplay.ui.*;
public class AboutScreen extends UIScreen {
public AboutScreen (Pokeros game) {
super(game);
}
@Override protected void createUI (Root root) {
addTitle(root, "About Pokeros");
root.add(new Shim(5, 5),
new Label("Copyright \u00A9 2013-2014\nMichael Bayne").addStyles(Style.TEXT_WRAP.on),
UI.stretchShim(),
new Label("Pokeros (pronounced \"poker-ohs\") was initially developed as a game " +
"design experiment. It turned out to be fun enough to merit polishing " +
"it up and making it more widely available.").addStyles(UI.textStyles),
UI.stretchShim(),
new Label("More information about Pokeros and the game design experiments is " +
"here:").addStyles(UI.textStyles),
new Button("github.com/samskivert/mashups").onClick(
new UnitSlot() { public void onEmit () {
game().plat.openURL(
"https://github.com/samskivert/mashups/blob/master/pokeros/README.md");
}}),
UI.stretchShim(),
new Button("Back").onClick(popSlot()));
}
}
|
3e1831a3091c8db9be64aeb86138090a269b2394 | 360 | java | Java | FirstWorkSpace/IOProject/src/com/ym/IODemo.java | CoderSteveJones/JavaSE_Part1 | f1544171565e68b7af62931e7bac38e0e88f1d80 | [
"MIT"
] | null | null | null | FirstWorkSpace/IOProject/src/com/ym/IODemo.java | CoderSteveJones/JavaSE_Part1 | f1544171565e68b7af62931e7bac38e0e88f1d80 | [
"MIT"
] | null | null | null | FirstWorkSpace/IOProject/src/com/ym/IODemo.java | CoderSteveJones/JavaSE_Part1 | f1544171565e68b7af62931e7bac38e0e88f1d80 | [
"MIT"
] | null | null | null | 18 | 60 | 0.647222 | 10,293 | package com.ym;
import java.io.FileWriter;
import java.io.IOException;
public class IODemo {
public static void main(String[] args) throws IOException {
// FileWriter fw = new FileWriter("a.txt");
// fw.write("IOhahh");
// fw.flush();
// fw.close();
//
FileWriter fw1 = new FileWriter("b.txt");
fw1.write(10);
fw1.flush();
fw1.close();
}
}
|
3e1832acd839beb681a7ace64179481ed99c2838 | 556 | java | Java | src/main/java/com/labr4/crawler/Node.java | Guacha/web-crawler | 0409918eff6897d985a038ac114e570559d98ab4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/labr4/crawler/Node.java | Guacha/web-crawler | 0409918eff6897d985a038ac114e570559d98ab4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/labr4/crawler/Node.java | Guacha/web-crawler | 0409918eff6897d985a038ac114e570559d98ab4 | [
"Apache-2.0"
] | null | null | null | 17.935484 | 80 | 0.586331 | 10,294 | /*
* 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.labr4.crawler;
import java.net.URL;
import java.util.LinkedList;
/**
*
* @author Guacha
*/
public class Node {
private URL url;
LinkedList<Node> hijos;
public Node(URL url) {
this.url = url;
hijos = new LinkedList<>();
}
public URL getUrl() {
return url;
}
}
|
3e1834bba6523bd25b7b0db428944fb4d8c5c2cc | 770 | java | Java | aries/common/common-tx/src/main/java/common/tx/service/coordinator/CoordinatorIdImple.java | tfisher1226/ARIES | 814e3a4b4b48396bcd6d082e78f6519679ccaa01 | [
"Apache-2.0"
] | 2 | 2019-09-16T10:06:07.000Z | 2021-02-25T11:46:23.000Z | aries/common/common-tx/src/main/java/common/tx/service/coordinator/CoordinatorIdImple.java | tfisher1226/ARIES | 814e3a4b4b48396bcd6d082e78f6519679ccaa01 | [
"Apache-2.0"
] | null | null | null | aries/common/common-tx/src/main/java/common/tx/service/coordinator/CoordinatorIdImple.java | tfisher1226/ARIES | 814e3a4b4b48396bcd6d082e78f6519679ccaa01 | [
"Apache-2.0"
] | null | null | null | 17.613636 | 77 | 0.649032 | 10,295 | package common.tx.service.coordinator;
import com.arjuna.ats.arjuna.common.Uid;
/**
* This implementation of CoordinatorId uses the ArjunaCore Uid class.
*
* @author Mark Little (lyhxr@example.com)
* @version $Id: CoordinatorIdImple.java,v 1.3 2004/03/15 13:25:13 nmcl Exp $
* @since 1.0.
*/
public class CoordinatorIdImple extends Uid implements CoordinatorId {
public CoordinatorIdImple ()
{
super();
_value = stringForm().getBytes();
}
public CoordinatorIdImple (String id)
{
super(id);
_value = stringForm().getBytes();
}
public CoordinatorIdImple (Uid id)
{
super(id);
_value = stringForm().getBytes();
}
public byte[] value ()
{
return _value;
}
private byte[] _value;
}
|
3e18350f6174932e8fd462589c5d7643c976d8f3 | 432 | java | Java | src/main/java/crain/exceptions/RoomException.java | Crain-32/Multiworld_Server | d1062c7d972b61caf7e826a510e495b6d0cbad04 | [
"MIT"
] | null | null | null | src/main/java/crain/exceptions/RoomException.java | Crain-32/Multiworld_Server | d1062c7d972b61caf7e826a510e495b6d0cbad04 | [
"MIT"
] | null | null | null | src/main/java/crain/exceptions/RoomException.java | Crain-32/Multiworld_Server | d1062c7d972b61caf7e826a510e495b6d0cbad04 | [
"MIT"
] | null | null | null | 22.736842 | 59 | 0.664352 | 10,296 | package crain.exceptions;
public class RoomException extends Exception {
private final String GAMEROOM_NAME;
public RoomException(String message) {
super(message);
this.GAMEROOM_NAME = "";
}
public RoomException(String message, String gameRoom) {
super(message);
this.GAMEROOM_NAME = gameRoom;
}
public String getGameRoomName() {
return this.GAMEROOM_NAME;
}
}
|
3e18358d6be7052332350c421a632202f5c7a7f0 | 32,028 | java | Java | helix-rest/src/main/java/org/apache/helix/rest/server/resources/helix/ClusterAccessor.java | mgao0/helix | 0412e9e7c4389da7f7ca4eb8cb07f46bd60fb2c3 | [
"Apache-2.0"
] | 1 | 2020-08-15T08:54:32.000Z | 2020-08-15T08:54:32.000Z | helix-rest/src/main/java/org/apache/helix/rest/server/resources/helix/ClusterAccessor.java | mgao0/helix | 0412e9e7c4389da7f7ca4eb8cb07f46bd60fb2c3 | [
"Apache-2.0"
] | null | null | null | helix-rest/src/main/java/org/apache/helix/rest/server/resources/helix/ClusterAccessor.java | mgao0/helix | 0412e9e7c4389da7f7ca4eb8cb07f46bd60fb2c3 | [
"Apache-2.0"
] | null | null | null | 34.775244 | 127 | 0.683683 | 10,297 | package org.apache.helix.rest.server.resources.helix;
/*
* 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.
*/
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.helix.AccessOption;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.manager.zk.ZKUtil;
import org.apache.helix.model.CloudConfig;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ControllerHistory;
import org.apache.helix.model.CustomizedStateConfig;
import org.apache.helix.model.HelixConfigScope;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.MaintenanceSignal;
import org.apache.helix.model.Message;
import org.apache.helix.model.RESTConfig;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.apache.helix.rest.server.json.cluster.ClusterTopology;
import org.apache.helix.rest.server.service.ClusterService;
import org.apache.helix.rest.server.service.ClusterServiceImpl;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/clusters")
public class ClusterAccessor extends AbstractHelixResource {
private static Logger LOG = LoggerFactory.getLogger(ClusterAccessor.class.getName());
public enum ClusterProperties {
controller,
instances,
liveInstances,
resources,
paused,
maintenance,
messages,
stateModelDefinitions,
clusters,
maintenanceSignal,
maintenanceHistory,
clusterName
}
@GET
public Response getClusters() {
HelixAdmin helixAdmin = getHelixAdmin();
List<String> clusters = helixAdmin.getClusters();
Map<String, List<String>> dataMap = new HashMap<>();
dataMap.put(ClusterProperties.clusters.name(), clusters);
return JSONRepresentation(dataMap);
}
@GET
@Path("{clusterId}")
public Response getClusterInfo(@PathParam("clusterId") String clusterId) {
if (!doesClusterExist(clusterId)) {
return notFound();
}
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder();
Map<String, Object> clusterInfo = new HashMap<>();
clusterInfo.put(Properties.id.name(), clusterId);
LiveInstance controller = dataAccessor.getProperty(keyBuilder.controllerLeader());
if (controller != null) {
clusterInfo.put(ClusterProperties.controller.name(), controller.getInstanceName());
} else {
clusterInfo.put(ClusterProperties.controller.name(), "No Lead Controller!");
}
boolean paused = dataAccessor.getBaseDataAccessor()
.exists(keyBuilder.pause().getPath(), AccessOption.PERSISTENT);
clusterInfo.put(ClusterProperties.paused.name(), paused);
boolean maintenance = getHelixAdmin().isInMaintenanceMode(clusterId);
clusterInfo.put(ClusterProperties.maintenance.name(), maintenance);
List<String> idealStates = dataAccessor.getChildNames(keyBuilder.idealStates());
clusterInfo.put(ClusterProperties.resources.name(), idealStates);
List<String> instances = dataAccessor.getChildNames(keyBuilder.instanceConfigs());
clusterInfo.put(ClusterProperties.instances.name(), instances);
List<String> liveInstances = dataAccessor.getChildNames(keyBuilder.liveInstances());
clusterInfo.put(ClusterProperties.liveInstances.name(), liveInstances);
return JSONRepresentation(clusterInfo);
}
@PUT
@Path("{clusterId}")
public Response createCluster(@PathParam("clusterId") String clusterId,
@DefaultValue("false") @QueryParam("recreate") String recreate,
@DefaultValue("false") @QueryParam("addCloudConfig") String addCloudConfig,
String cloudConfigManifest) {
boolean recreateIfExists = Boolean.parseBoolean(recreate);
boolean cloudConfigIncluded = Boolean.parseBoolean(addCloudConfig);
ClusterSetup clusterSetup = getClusterSetup();
CloudConfig cloudConfig = null;
if (cloudConfigIncluded) {
ZNRecord record;
try {
record = toZNRecord(cloudConfigManifest);
cloudConfig = new CloudConfig.Builder(record).build();
} catch (IOException | HelixException e) {
String errMsg = "Failed to generate a valid CloudConfig from " + cloudConfigManifest;
LOG.error(errMsg, e);
return badRequest(errMsg + " Exception: " + e.getMessage());
}
}
try {
clusterSetup.addCluster(clusterId, recreateIfExists, cloudConfig);
} catch (Exception ex) {
LOG.error("Failed to create cluster {}. Exception: {}.", clusterId, ex);
return serverError(ex);
}
return created();
}
@DELETE
@Path("{clusterId}")
public Response deleteCluster(@PathParam("clusterId") String clusterId) {
ClusterSetup clusterSetup = getClusterSetup();
try {
clusterSetup.deleteCluster(clusterId);
} catch (HelixException ex) {
LOG.info("Failed to delete cluster {}, cluster is still in use. Exception: {}.", clusterId,
ex);
return badRequest(ex.getMessage());
} catch (Exception ex) {
LOG.error("Failed to delete cluster {}. Exception: {}.", clusterId, ex);
return serverError(ex);
}
return OK();
}
@POST
@Path("{clusterId}")
public Response updateCluster(@PathParam("clusterId") String clusterId,
@QueryParam("command") String commandStr, @QueryParam("superCluster") String superCluster,
String content) {
Command command;
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
ClusterSetup clusterSetup = getClusterSetup();
HelixAdmin helixAdmin = getHelixAdmin();
switch (command) {
case activate:
if (superCluster == null) {
return badRequest("Super Cluster name is missing!");
}
try {
clusterSetup.activateCluster(clusterId, superCluster, true);
} catch (Exception ex) {
LOG.error("Failed to add cluster {} to super cluster {}.", clusterId, superCluster);
return serverError(ex);
}
break;
case expand:
try {
clusterSetup.expandCluster(clusterId);
} catch (Exception ex) {
LOG.error("Failed to expand cluster {}.", clusterId);
return serverError(ex);
}
break;
case enable:
try {
helixAdmin.enableCluster(clusterId, true);
} catch (Exception ex) {
LOG.error("Failed to enable cluster {}.", clusterId);
return serverError(ex);
}
break;
case disable:
try {
helixAdmin.enableCluster(clusterId, false);
} catch (Exception ex) {
LOG.error("Failed to disable cluster {}.", clusterId);
return serverError(ex);
}
break;
case enableMaintenanceMode:
case disableMaintenanceMode:
// Try to parse the content string. If parseable, use it as a KV mapping. Otherwise, treat it
// as a REASON String
Map<String, String> customFieldsMap = null;
try {
// Try to parse content
customFieldsMap =
OBJECT_MAPPER.readValue(content, new TypeReference<HashMap<String, String>>() {
});
// content is given as a KV mapping. Nullify content
content = null;
} catch (Exception e) {
// NOP
}
helixAdmin
.manuallyEnableMaintenanceMode(clusterId, command == Command.enableMaintenanceMode,
content, customFieldsMap);
break;
case enableWagedRebalanceForAllResources:
// Enable WAGED rebalance for all resources in the cluster
List<String> resources = helixAdmin.getResourcesInCluster(clusterId);
try {
helixAdmin.enableWagedRebalance(clusterId, resources);
} catch (HelixException e) {
return badRequest(e.getMessage());
}
break;
default:
return badRequest("Unsupported command {}." + command);
}
return OK();
}
@GET
@Path("{clusterId}/configs")
public Response getClusterConfig(@PathParam("clusterId") String clusterId) {
ConfigAccessor accessor = getConfigAccessor();
ClusterConfig config = null;
try {
config = accessor.getClusterConfig(clusterId);
} catch (HelixException ex) {
// cluster not found.
LOG.info("Failed to get cluster config for cluster {}, cluster not found. Exception: {}.",
clusterId, ex);
} catch (Exception ex) {
LOG.error("Failed to get cluster config for cluster {}. Exception: {}", clusterId, ex);
return serverError(ex);
}
if (config == null) {
return notFound();
}
return JSONRepresentation(config.getRecord());
}
@PUT
@Path("{clusterId}/customized-state-config")
public Response addCustomizedStateConfig(@PathParam("clusterId") String clusterId,
String content) {
if (!doesClusterExist(clusterId)) {
return notFound(String.format("Cluster %s does not exist", clusterId));
}
HelixAdmin admin = getHelixAdmin();
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
return badRequest("Input is not a vaild ZNRecord!");
}
try {
CustomizedStateConfig customizedStateConfig =
new CustomizedStateConfig.Builder(record).build();
admin.addCustomizedStateConfig(clusterId, customizedStateConfig);
} catch (Exception ex) {
LOG.error("Cannot add CustomizedStateConfig to cluster: {} Exception: {}",
clusterId, ex);
return serverError(ex);
}
return OK();
}
@DELETE
@Path("{clusterId}/customized-state-config")
public Response removeCustomizedStateConfig(@PathParam("clusterId") String clusterId) {
if (!doesClusterExist(clusterId)) {
return notFound(String.format("Cluster %s does not exist", clusterId));
}
HelixAdmin admin = getHelixAdmin();
try {
admin.removeCustomizedStateConfig(clusterId);
} catch (Exception ex) {
LOG.error(
"Cannot remove CustomizedStateConfig from cluster: {}, Exception: {}",
clusterId, ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{clusterId}/customized-state-config")
public Response getCustomizedStateConfig(@PathParam("clusterId") String clusterId) {
if (!doesClusterExist(clusterId)) {
return notFound(String.format("Cluster %s does not exist", clusterId));
}
ConfigAccessor configAccessor = getConfigAccessor();
CustomizedStateConfig customizedStateConfig =
configAccessor.getCustomizedStateConfig(clusterId);
if (customizedStateConfig != null) {
return JSONRepresentation(customizedStateConfig.getRecord());
}
return notFound();
}
@POST
@Path("{clusterId}/customized-state-config")
public Response updateCustomizedStateConfig(@PathParam("clusterId") String clusterId,
@QueryParam("command") String commandStr, @QueryParam("type") String type) {
if (!doesClusterExist(clusterId)) {
return notFound(String.format("Cluster %s does not exist", clusterId));
}
Command command;
if (commandStr == null || commandStr.isEmpty()) {
command = Command.add; // Default behavior
} else {
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
}
HelixAdmin admin = getHelixAdmin();
try {
switch (command) {
case delete:
admin.removeTypeFromCustomizedStateConfig(clusterId, type);
break;
case add:
admin.addTypeToCustomizedStateConfig(clusterId, type);
break;
default:
return badRequest("Unsupported command " + commandStr);
}
} catch (Exception ex) {
LOG.error("Failed to {} CustomizedStateConfig for cluster {} new type: {}, Exception: {}", command, clusterId, type, ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{clusterId}/topology")
public Response getClusterTopology(@PathParam("clusterId") String clusterId) throws IOException {
//TODO reduce the GC by dependency injection
ClusterService clusterService =
new ClusterServiceImpl(getDataAccssor(clusterId), getConfigAccessor());
ObjectMapper objectMapper = new ObjectMapper();
ClusterTopology clusterTopology = clusterService.getClusterTopology(clusterId);
return OK(objectMapper.writeValueAsString(clusterTopology));
}
@POST
@Path("{clusterId}/configs")
public Response updateClusterConfig(@PathParam("clusterId") String clusterId,
@QueryParam("command") String commandStr, String content) {
Command command;
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input {}. Exception: {}.", content, e);
return badRequest("Input is not a valid ZNRecord!");
}
if (!record.getId().equals(clusterId)) {
return badRequest("ID does not match the cluster name in input!");
}
ClusterConfig config = new ClusterConfig(record);
ConfigAccessor configAccessor = getConfigAccessor();
try {
switch (command) {
case update:
configAccessor.updateClusterConfig(clusterId, config);
break;
case delete: {
HelixConfigScope clusterScope =
new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER)
.forCluster(clusterId).build();
configAccessor.remove(clusterScope, config.getRecord());
}
break;
default:
return badRequest("Unsupported command " + commandStr);
}
} catch (HelixException ex) {
return notFound(ex.getMessage());
} catch (Exception ex) {
LOG
.error("Failed to {} cluster config, cluster {}, new config: {}. Exception: {}.", command,
clusterId, content, ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{clusterId}/controller")
public Response getClusterController(@PathParam("clusterId") String clusterId) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
Map<String, Object> controllerInfo = new HashMap<>();
controllerInfo.put(Properties.id.name(), clusterId);
LiveInstance leader = dataAccessor.getProperty(dataAccessor.keyBuilder().controllerLeader());
if (leader != null) {
controllerInfo.put(ClusterProperties.controller.name(), leader.getInstanceName());
controllerInfo.putAll(leader.getRecord().getSimpleFields());
} else {
controllerInfo.put(ClusterProperties.controller.name(), "No Lead Controller!");
}
return JSONRepresentation(controllerInfo);
}
@GET
@Path("{clusterId}/controller/history")
public Response getClusterControllerLeadershipHistory(@PathParam("clusterId") String clusterId) {
return JSONRepresentation(
getControllerHistory(clusterId, ControllerHistory.HistoryType.CONTROLLER_LEADERSHIP));
}
@GET
@Path("{clusterId}/controller/maintenanceHistory")
public Response getClusterMaintenanceHistory(@PathParam("clusterId") String clusterId) {
return JSONRepresentation(
getControllerHistory(clusterId, ControllerHistory.HistoryType.MAINTENANCE));
}
@GET
@Path("{clusterId}/controller/maintenanceSignal")
public Response getClusterMaintenanceSignal(@PathParam("clusterId") String clusterId) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
MaintenanceSignal maintenanceSignal =
dataAccessor.getProperty(dataAccessor.keyBuilder().maintenance());
if (maintenanceSignal != null) {
Map<String, String> maintenanceInfo = maintenanceSignal.getRecord().getSimpleFields();
maintenanceInfo.put(ClusterProperties.clusterName.name(), clusterId);
return JSONRepresentation(maintenanceInfo);
}
return notFound(String.format("Cluster %s is not in maintenance mode!", clusterId));
}
@GET
@Path("{clusterId}/controller/messages")
public Response getClusterControllerMessages(@PathParam("clusterId") String clusterId) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
Map<String, Object> controllerMessages = new HashMap<>();
controllerMessages.put(Properties.id.name(), clusterId);
List<String> messages =
dataAccessor.getChildNames(dataAccessor.keyBuilder().controllerMessages());
controllerMessages.put(ClusterProperties.messages.name(), messages);
controllerMessages.put(Properties.count.name(), messages.size());
return JSONRepresentation(controllerMessages);
}
@GET
@Path("{clusterId}/controller/messages/{messageId}")
public Response getClusterControllerMessages(@PathParam("clusterId") String clusterId,
@PathParam("messageId") String messageId) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
Message message =
dataAccessor.getProperty(dataAccessor.keyBuilder().controllerMessage(messageId));
return JSONRepresentation(message.getRecord());
}
@GET
@Path("{clusterId}/statemodeldefs")
public Response getClusterStateModelDefinitions(@PathParam("clusterId") String clusterId) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
List<String> stateModelDefs =
dataAccessor.getChildNames(dataAccessor.keyBuilder().stateModelDefs());
Map<String, Object> clusterStateModelDefs = new HashMap<>();
clusterStateModelDefs.put(Properties.id.name(), clusterId);
clusterStateModelDefs.put(ClusterProperties.stateModelDefinitions.name(), stateModelDefs);
return JSONRepresentation(clusterStateModelDefs);
}
@GET
@Path("{clusterId}/statemodeldefs/{statemodel}")
public Response getClusterStateModelDefinition(@PathParam("clusterId") String clusterId,
@PathParam("statemodel") String statemodel) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
StateModelDefinition stateModelDef =
dataAccessor.getProperty(dataAccessor.keyBuilder().stateModelDef(statemodel));
if (stateModelDef == null) {
return badRequest("Statemodel not found!");
}
return JSONRepresentation(stateModelDef.getRecord());
}
@PUT
@Path("{clusterId}/statemodeldefs/{statemodel}")
public Response createClusterStateModelDefinition(@PathParam("clusterId") String clusterId,
@PathParam("statemodel") String statemodel, String content) {
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input {}. Exception: {}.", content, e);
return badRequest("Input is not a valid ZNRecord!");
}
RealmAwareZkClient zkClient = getRealmAwareZkClient();
String path = PropertyPathBuilder.stateModelDef(clusterId);
try {
ZKUtil.createChildren(zkClient, path, record);
} catch (Exception e) {
LOG.error("Failed to create zk node with path {}. Exception: {}", path, e);
return badRequest("Failed to create a Znode for stateModel! " + e);
}
return OK();
}
@POST
@Path("{clusterId}/statemodeldefs/{statemodel}")
public Response setClusterStateModelDefinition(@PathParam("clusterId") String clusterId,
@PathParam("statemodel") String statemodel, String content) {
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input {}. Exception: {}.", content, e);
return badRequest("Input is not a valid ZNRecord!");
}
StateModelDefinition stateModelDefinition = new StateModelDefinition(record);
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
PropertyKey key = dataAccessor.keyBuilder().stateModelDef(stateModelDefinition.getId());
boolean retcode = true;
try {
retcode = dataAccessor.setProperty(key, stateModelDefinition);
} catch (Exception e) {
LOG.error("Failed to set StateModelDefinition key: {}. Exception: {}.", key, e);
return badRequest("Failed to set the content " + content);
}
return OK();
}
@DELETE
@Path("{clusterId}/statemodeldefs/{statemodel}")
public Response removeClusterStateModelDefinition(@PathParam("clusterId") String clusterId,
@PathParam("statemodel") String statemodel) {
//Shall we validate the statemodel string not having special character such as ../ etc?
if (!StringUtils.isAlphanumeric(statemodel)) {
return badRequest("Invalid statemodel name!");
}
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
PropertyKey key = dataAccessor.keyBuilder().stateModelDef(statemodel);
boolean retcode = true;
try {
retcode = dataAccessor.removeProperty(key);
} catch (Exception e) {
LOG.error("Failed to remove StateModelDefinition key: {}. Exception: {}.", key, e);
retcode = false;
}
if (!retcode) {
return badRequest("Failed to remove!");
}
return OK();
}
@PUT
@Path("{clusterId}/restconfig")
public Response createRESTConfig(@PathParam("clusterId") String clusterId,
String content) {
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input {}. Exception: {}.", content, e);
return badRequest("Input is not a valid ZNRecord!");
}
if (!record.getId().equals(clusterId)) {
return badRequest("ID does not match the cluster name in input!");
}
RESTConfig config = new RESTConfig(record);
ConfigAccessor configAccessor = getConfigAccessor();
try {
configAccessor.setRESTConfig(clusterId, config);
} catch (HelixException ex) {
// TODO: Could use a more generic error for HelixException
return notFound(ex.getMessage());
} catch (Exception ex) {
LOG.error("Failed to create rest config, cluster {}, new config: {}. Exception: {}.", clusterId, content, ex);
return serverError(ex);
}
return OK();
}
@POST
@Path("{clusterId}/restconfig")
public Response updateRESTConfig(@PathParam("clusterId") String clusterId,
@QueryParam("command") String commandStr, String content) {
//TODO: abstract out the logic that is duplicated from cluster config methods
Command command;
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input {}. Exception: {}", content, e);
return badRequest("Input is not a valid ZNRecord!");
}
RESTConfig config = new RESTConfig(record);
ConfigAccessor configAccessor = getConfigAccessor();
try {
switch (command) {
case update:
configAccessor.updateRESTConfig(clusterId, config);
break;
case delete: {
HelixConfigScope scope =
new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.REST)
.forCluster(clusterId).build();
configAccessor.remove(scope, config.getRecord());
}
break;
default:
return badRequest("Unsupported command " + commandStr);
}
} catch (HelixException ex) {
return notFound(ex.getMessage());
} catch (Exception ex) {
LOG.error(
"Failed to {} rest config, cluster {}, new config: {}. Exception: {}", command, clusterId, content, ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{clusterId}/restconfig")
public Response getRESTConfig(@PathParam("clusterId") String clusterId) {
ConfigAccessor accessor = getConfigAccessor();
RESTConfig config = null;
try {
config = accessor.getRESTConfig(clusterId);
} catch (HelixException ex) {
LOG.info(
"Failed to get rest config for cluster {}, cluster not found. Exception: {}.", clusterId, ex);
} catch (Exception ex) {
LOG.error("Failed to get rest config for cluster {}. Exception: {}.", clusterId, ex);
return serverError(ex);
}
if (config == null) {
return notFound();
}
return JSONRepresentation(config.getRecord());
}
@DELETE
@Path("{clusterId}/restconfig")
public Response deleteRESTConfig(@PathParam("clusterId") String clusterId) {
ConfigAccessor accessor = getConfigAccessor();
try {
accessor.deleteRESTConfig(clusterId);
} catch (HelixException ex) {
LOG.info("Failed to delete rest config for cluster {}, cluster rest config is not found. Exception: {}.", clusterId, ex);
return notFound(ex.getMessage());
} catch (Exception ex) {
LOG.error("Failed to delete rest config, cluster {}, Exception: {}.", clusterId, ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{clusterId}/maintenance")
public Response getClusterMaintenanceMode(@PathParam("clusterId") String clusterId) {
return JSONRepresentation(ImmutableMap
.of(ClusterProperties.maintenance.name(), getHelixAdmin().isInMaintenanceMode(clusterId)));
}
private boolean doesClusterExist(String cluster) {
RealmAwareZkClient zkClient = getRealmAwareZkClient();
return ZKUtil.isClusterSetup(cluster, zkClient);
}
@PUT
@Path("{clusterId}/cloudconfig")
public Response addCloudConfig(@PathParam("clusterId") String clusterId, String content) {
RealmAwareZkClient zkClient = getRealmAwareZkClient();
if (!ZKUtil.isClusterSetup(clusterId, zkClient)) {
return notFound("Cluster is not properly setup!");
}
HelixAdmin admin = getHelixAdmin();
ZNRecord record;
try {
record = toZNRecord(content);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input " + content + ", Exception: " + e);
return badRequest("Input is not a vaild ZNRecord!");
}
try {
CloudConfig cloudConfig = new CloudConfig.Builder(record).build();
admin.addCloudConfig(clusterId, cloudConfig);
} catch (HelixException ex) {
LOG.error("Error in adding a CloudConfig to cluster: " + clusterId, ex);
return badRequest(ex.getMessage());
} catch (Exception ex) {
LOG.error("Cannot add CloudConfig to cluster: " + clusterId, ex);
return serverError(ex);
}
return OK();
}
@GET
@Path("{clusterId}/cloudconfig")
public Response getCloudConfig(@PathParam("clusterId") String clusterId) {
RealmAwareZkClient zkClient = getRealmAwareZkClient();
if (!ZKUtil.isClusterSetup(clusterId, zkClient)) {
return notFound();
}
ConfigAccessor configAccessor = new ConfigAccessor(zkClient);
CloudConfig cloudConfig = configAccessor.getCloudConfig(clusterId);
if (cloudConfig != null) {
return JSONRepresentation(cloudConfig.getRecord());
}
return notFound();
}
@DELETE
@Path("{clusterId}/cloudconfig")
public Response deleteCloudConfig(@PathParam("clusterId") String clusterId) {
HelixAdmin admin = getHelixAdmin();
admin.removeCloudConfig(clusterId);
return OK();
}
@POST
@Path("{clusterId}/cloudconfig")
public Response updateCloudConfig(@PathParam("clusterId") String clusterId,
@QueryParam("command") String commandStr, String content) {
RealmAwareZkClient zkClient = getRealmAwareZkClient();
if (!ZKUtil.isClusterSetup(clusterId, zkClient)) {
return notFound();
}
ConfigAccessor configAccessor = new ConfigAccessor(zkClient);
// Here to update cloud config
Command command;
if (commandStr == null || commandStr.isEmpty()) {
command = Command.update; // Default behavior
} else {
try {
command = getCommand(commandStr);
} catch (HelixException ex) {
return badRequest(ex.getMessage());
}
}
ZNRecord record;
CloudConfig cloudConfig;
try {
record = toZNRecord(content);
cloudConfig = new CloudConfig(record);
} catch (IOException e) {
LOG.error("Failed to deserialize user's input " + content + ", Exception: " + e);
return badRequest("Input is not a vaild ZNRecord!");
}
try {
switch (command) {
case delete: {
configAccessor.deleteCloudConfigFields(clusterId, cloudConfig);
}
break;
case update: {
try {
configAccessor.updateCloudConfig(clusterId, cloudConfig);
} catch (HelixException ex) {
LOG.error("Error in updating a CloudConfig to cluster: " + clusterId, ex);
return badRequest(ex.getMessage());
} catch (Exception ex) {
LOG.error("Cannot update CloudConfig for cluster: " + clusterId, ex);
return serverError(ex);
}
}
break;
default:
return badRequest("Unsupported command " + commandStr);
}
} catch (Exception ex) {
LOG.error("Failed to " + command + " cloud config, cluster " + clusterId + " new config: "
+ content + ", Exception: " + ex);
return serverError(ex);
}
return OK();
}
/**
* Reads HISTORY ZNode from the metadata store and generates a Map object that contains the
* pertinent history entries depending on the history type.
* @param clusterId
* @param historyType
* @return
*/
private Map<String, Object> getControllerHistory(String clusterId,
ControllerHistory.HistoryType historyType) {
HelixDataAccessor dataAccessor = getDataAccssor(clusterId);
Map<String, Object> history = new HashMap<>();
history.put(Properties.id.name(), clusterId);
ControllerHistory historyRecord =
dataAccessor.getProperty(dataAccessor.keyBuilder().controllerLeaderHistory());
switch (historyType) {
case CONTROLLER_LEADERSHIP:
history.put(Properties.history.name(),
historyRecord != null ? historyRecord.getHistoryList() : Collections.emptyList());
break;
case MAINTENANCE:
history.put(ClusterProperties.maintenanceHistory.name(),
historyRecord != null ? historyRecord.getMaintenanceHistoryList()
: Collections.emptyList());
break;
}
return history;
}
}
|
3e1835d0de674deb1a296a94e1c4b3289856fd8c | 1,123 | java | Java | ace-gate/ace-gate-ratelimit/src/main/java/com/github/wxiaoqi/gate/ratelimit/config/RateLimiter.java | idyg0215/springCloudStudy | 65d0189696b67f24285492a7fbb896dd397f66cf | [
"Apache-2.0"
] | 6 | 2018-12-05T07:38:37.000Z | 2021-07-06T08:28:58.000Z | ace-gate/ace-gate-ratelimit/src/main/java/com/github/wxiaoqi/gate/ratelimit/config/RateLimiter.java | idyg0215/springCloudStudy | 65d0189696b67f24285492a7fbb896dd397f66cf | [
"Apache-2.0"
] | 1 | 2022-03-31T21:37:35.000Z | 2022-03-31T21:37:35.000Z | ace-gate/ace-gate-ratelimit/src/main/java/com/github/wxiaoqi/gate/ratelimit/config/RateLimiter.java | idyg0215/springCloudStudy | 65d0189696b67f24285492a7fbb896dd397f66cf | [
"Apache-2.0"
] | 11 | 2018-06-12T09:40:18.000Z | 2021-02-28T12:28:02.000Z | 34.030303 | 119 | 0.728406 | 10,298 | /*
* Copyright 2012-2017 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 com.github.wxiaoqi.gate.ratelimit.config;
import com.github.wxiaoqi.gate.ratelimit.config.properties.RateLimitProperties.Policy;
/**
* @author Marcos Barbero
*/
public interface RateLimiter {
/**
* @param policy - Template for which rates should be created in case there's no rate limit associated with the key
* @param key - Unique key that identifies a request
* @return a view of a user's rate request limit
*/
Rate consume(Policy policy, String key);
}
|
3e1836978bef8e0f2921f2616a347582a87a8f73 | 1,895 | java | Java | openjdk11/test/hotspot/jtreg/vmTestbase/nsk/jvmti/GarbageCollectionStart/gcstart001/TestDescription.java | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | test/hotspot/jtreg/vmTestbase/nsk/jvmti/GarbageCollectionStart/gcstart001/TestDescription.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/hotspot/jtreg/vmTestbase/nsk/jvmti/GarbageCollectionStart/gcstart001/TestDescription.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 38.673469 | 83 | 0.732454 | 10,299 | /*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase nsk/jvmti/GarbageCollectionStart/gcstart001.
* VM Testbase keywords: [jpda, jvmti, noras, nonconcurrent]
* VM Testbase readme:
* DESCRIPTION
* This test exercises the JVMTI event GarbageCollectionStart.
* It verifies that this event is always sent as a matched pair with
* GarbageCollectionFinish.
* All GarbageCollectionStart-GarbageCollectionFinish pairs are checked
* during the events themselves and, finally, during the VMDeath event.
* COMMENTS
* The test has been fixed due to the bug 4968106.
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @run main/othervm/native
* -XX:-UseGCOverheadLimit
* -agentlib:gcstart001=-waittime=5
* nsk.jvmti.GarbageCollectionStart.gcstart001
*/
|
3e1837564b50ad9e6fc4d3c0f1de273323385604 | 886 | java | Java | service-report/src/main/java/com/java110/report/dao/IReportCommunityServiceDao.java | 2669430363/MicroCommunity | f7cdc8cc9b1d092403abf18239cdc88fa9c3522d | [
"Apache-2.0"
] | 711 | 2017-04-09T15:59:16.000Z | 2022-03-27T07:19:02.000Z | service-report/src/main/java/com/java110/report/dao/IReportCommunityServiceDao.java | yasudarui/MicroCommunity | 1026aa5eaa86446aedfdefd092a3d6fcf0dfe470 | [
"Apache-2.0"
] | 16 | 2017-04-09T16:13:09.000Z | 2022-01-04T16:36:13.000Z | service-report/src/main/java/com/java110/report/dao/IReportCommunityServiceDao.java | yasudarui/MicroCommunity | 1026aa5eaa86446aedfdefd092a3d6fcf0dfe470 | [
"Apache-2.0"
] | 334 | 2017-04-16T05:01:12.000Z | 2022-03-30T00:49:37.000Z | 18.081633 | 78 | 0.628668 | 10,300 | package com.java110.report.dao;
import com.java110.dto.report.ReportCarDto;
import com.java110.dto.report.ReportRoomDto;
import java.util.List;
/**
* @ClassName ICommunityServiceDao
* @Description TODO
* @Author wuxw
* @Date 2020/10/15 22:10
* @Version 1.0
* add by wuxw 2020/10/15
**/
public interface IReportCommunityServiceDao {
/**
* 查询房屋个数
*
* @param reportRoomDto
* @return
*/
int getRoomCount(ReportRoomDto reportRoomDto);
/**
* 查询 房屋 楼栋 单元 和 业主 信息
*
* @return
*/
List<ReportRoomDto> getRoomFloorUnitAndOwner(ReportRoomDto reportRoomDto);
/**
* 查询房屋个数
*
* @param reportCarDto
* @return
*/
int getCarCount(ReportCarDto reportCarDto);
/**
* 查询 房屋 楼栋 单元 和 业主 信息
*
* @return
*/
List<ReportCarDto> getCarParkingSpace(ReportCarDto reportCarDto);
}
|
3e18375af7588ac9408b09a1b128b674d52993cd | 3,950 | java | Java | rt/test/unit/src/com/sun/xml/ws/addressing/policy/AddressingFeatureConfiguratorTest.java | torstenwerner/metro2.0 | fc42cce41cbeb6532efbcd0cd7f612e61a5f29f9 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | rt/test/unit/src/com/sun/xml/ws/addressing/policy/AddressingFeatureConfiguratorTest.java | torstenwerner/metro2.0 | fc42cce41cbeb6532efbcd0cd7f612e61a5f29f9 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | rt/test/unit/src/com/sun/xml/ws/addressing/policy/AddressingFeatureConfiguratorTest.java | torstenwerner/metro2.0 | fc42cce41cbeb6532efbcd0cd7f612e61a5f29f9 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 45.930233 | 111 | 0.744051 | 10,301 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.ws.addressing.policy;
import com.sun.xml.ws.developer.MemberSubmissionAddressingFeature;
import junit.framework.*;
import com.sun.xml.ws.api.model.wsdl.WSDLModel;
import javax.xml.namespace.QName;
import javax.xml.ws.soap.AddressingFeature;
import static com.sun.xml.ws.policy.testutils.PolicyResourceLoader.getWSDLModel;
/**
*
* @author japod
*/
public class AddressingFeatureConfiguratorTest extends TestCase {
/**
* Test of configure method, of class com.sun.xml.ws.policy.jaxws.addressing.AddressingFeatureConfigurator.
* policy assertion present
*/
public void testConfigureW3CAddressingAssertionPresent() throws Exception {
WSDLModel model = getWSDLModel("jaxws-spi/testModelConfigProviderAddrW3C.wsdl");
assertTrue(model.getService(new QName("http://example.org","DictionaryService")).
getFirstPort().getFeature(AddressingFeature.class).isEnabled());
}
/**
* Test of configure method, of class com.sun.xml.ws.policy.jaxws.addressing.AddressingFeatureConfigurator.
* policy assertion present
*/
public void testConfigureMEMBERAddressingAssertionPresent() throws Exception {
WSDLModel model = getWSDLModel("jaxws-spi/testModelConfigProviderAddrMEMBER.wsdl");
assertTrue(model.getService(new QName("http://example.org","DictionaryService")).
getFirstPort().getFeature(MemberSubmissionAddressingFeature.class).isEnabled());
}
/**
* Test of configure method, of class com.sun.xml.ws.policy.jaxws.addressing.AddressingFeatureConfigurator.
* policy assertion not present
*/
public void testConfigureAddressingAssertionNotPresent() throws Exception {
WSDLModel model = getWSDLModel("jaxws-spi/testModelConfigProviderAddrPolicyNotPresent.wsdl");
assertNull(model.getService(new QName("http://example.org","DictionaryService")).
getFirstPort().getFeature(AddressingFeature.class));
}
}
|
3e183876db28215dd765f97caba7766abd6cfa70 | 1,878 | java | Java | presentation/src/main/java/fr/bourgmapper/tub/presentation/mapper/LineModelDataMapper.java | axellebot/tub-android | 042b4347413f657ad472e8b696435743fb0c4863 | [
"Apache-2.0"
] | null | null | null | presentation/src/main/java/fr/bourgmapper/tub/presentation/mapper/LineModelDataMapper.java | axellebot/tub-android | 042b4347413f657ad472e8b696435743fb0c4863 | [
"Apache-2.0"
] | null | null | null | presentation/src/main/java/fr/bourgmapper/tub/presentation/mapper/LineModelDataMapper.java | axellebot/tub-android | 042b4347413f657ad472e8b696435743fb0c4863 | [
"Apache-2.0"
] | null | null | null | 28.892308 | 96 | 0.652822 | 10,302 | package fr.bourgmapper.tub.presentation.mapper;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.inject.Inject;
import fr.bourgmapper.tub.domain.Line;
import fr.bourgmapper.tub.presentation.internal.di.PerFragment;
import fr.bourgmapper.tub.presentation.model.LineModel;
/**
* Mapper class used to transform {@link Line} (in the domain layer) to {@link LineModel} in the
* presentation layer.
*/
@PerFragment
public class LineModelDataMapper {
@Inject
public LineModelDataMapper() {
}
/**
* Transform a {@link Line} into an {@link LineModel}.
*
* @param line Object to be transformed.
* @return {@link LineModel}.
*/
public LineModel transform(Line line) {
if (line == null) {
throw new IllegalArgumentException("Cannot transform a null value");
}
final LineModel lineModel = new LineModel(line.getLineId());
lineModel.setNumber(line.getNumber());
lineModel.setLabel(line.getLabel());
lineModel.setColor(line.getColor());
lineModel.setKmlPath(line.getKmlPath());
return lineModel;
}
/**
* Transform a Collection of {@link Line} into a Collection of {@link LineModel}.
*
* @param lineCollection Objects to be transformed.
* @return List of {@link LineModel}.
*/
public Collection<LineModel> transform(Collection<Line> lineCollection) {
Collection<LineModel> lineModelCollection;
if (lineCollection != null && !lineCollection.isEmpty()) {
lineModelCollection = new ArrayList<>();
for (Line user : lineCollection) {
lineModelCollection.add(transform(user));
}
} else {
lineModelCollection = Collections.emptyList();
}
return lineModelCollection;
}
}
|
3e18394113fb6298bcc61e3c936165b544e9f2d8 | 4,936 | java | Java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/GroupIdentifier.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/GroupIdentifier.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/GroupIdentifier.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 26.972678 | 137 | 0.583671 | 10,303 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes a security group.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GroupIdentifier" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GroupIdentifier implements Serializable, Cloneable {
/**
* <p>
* The name of the security group.
* </p>
*/
private String groupName;
/**
* <p>
* The ID of the security group.
* </p>
*/
private String groupId;
/**
* <p>
* The name of the security group.
* </p>
*
* @param groupName
* The name of the security group.
*/
public void setGroupName(String groupName) {
this.groupName = groupName;
}
/**
* <p>
* The name of the security group.
* </p>
*
* @return The name of the security group.
*/
public String getGroupName() {
return this.groupName;
}
/**
* <p>
* The name of the security group.
* </p>
*
* @param groupName
* The name of the security group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GroupIdentifier withGroupName(String groupName) {
setGroupName(groupName);
return this;
}
/**
* <p>
* The ID of the security group.
* </p>
*
* @param groupId
* The ID of the security group.
*/
public void setGroupId(String groupId) {
this.groupId = groupId;
}
/**
* <p>
* The ID of the security group.
* </p>
*
* @return The ID of the security group.
*/
public String getGroupId() {
return this.groupId;
}
/**
* <p>
* The ID of the security group.
* </p>
*
* @param groupId
* The ID of the security group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GroupIdentifier withGroupId(String groupId) {
setGroupId(groupId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getGroupName() != null)
sb.append("GroupName: ").append(getGroupName()).append(",");
if (getGroupId() != null)
sb.append("GroupId: ").append(getGroupId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GroupIdentifier == false)
return false;
GroupIdentifier other = (GroupIdentifier) obj;
if (other.getGroupName() == null ^ this.getGroupName() == null)
return false;
if (other.getGroupName() != null && other.getGroupName().equals(this.getGroupName()) == false)
return false;
if (other.getGroupId() == null ^ this.getGroupId() == null)
return false;
if (other.getGroupId() != null && other.getGroupId().equals(this.getGroupId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getGroupName() == null) ? 0 : getGroupName().hashCode());
hashCode = prime * hashCode + ((getGroupId() == null) ? 0 : getGroupId().hashCode());
return hashCode;
}
@Override
public GroupIdentifier clone() {
try {
return (GroupIdentifier) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
3e183975d32c615ad4d930b0e1242d733114079c | 2,757 | java | Java | src/test/java/pmhsfelix/async/examples/CallbackExamples.java | pmhsfelix/jvm-async-examples | fbc654ea5d25826a0948b304c5ba6739c236acad | [
"Apache-2.0"
] | null | null | null | src/test/java/pmhsfelix/async/examples/CallbackExamples.java | pmhsfelix/jvm-async-examples | fbc654ea5d25826a0948b304c5ba6739c236acad | [
"Apache-2.0"
] | null | null | null | src/test/java/pmhsfelix/async/examples/CallbackExamples.java | pmhsfelix/jvm-async-examples | fbc654ea5d25826a0948b304c5ba6739c236acad | [
"Apache-2.0"
] | null | null | null | 47.534483 | 119 | 0.494741 | 10,304 | package pmhsfelix.async.examples;
import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;
public class CallbackExamples {
@Test
public void testSimpleGet() throws IOException, InterruptedException {
final CountDownLatch c = new CountDownLatch(1);
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(new InetSocketAddress("httpbin.org", 80), ch,
new CompletionHandler<Void, Object>() {
@Override
public void completed(Void result, Object attachment) {
ByteBuffer src = ByteBuffer.wrap("GET /get HTTP/1.1\r\nHost: httpbin.org\r\n\r\n".getBytes());
ch.write(src, ch, new CompletionHandler<Integer, AsynchronousSocketChannel>() {
@Override
public void completed(Integer result, AsynchronousSocketChannel attachment) {
ByteBuffer dst = ByteBuffer.allocate(2048);
ch.read(dst, ch, new CompletionHandler<Integer, AsynchronousSocketChannel>() {
@Override
public void completed(Integer result, AsynchronousSocketChannel attachment) {
String txt = new String(dst.array(), 0, result, Charset.forName("UTF-8"));
System.out.println(txt);
c.countDown();
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
// everything is going to be fine, trust me
}
});
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
// everything is going to be fine, trust me
}
});
}
@Override
public void failed(Throwable exc, Object attachment) {
// everything is going to be fine, trust me
}
});
c.await();
}
}
|
3e1839cfab55a2e5228ea9dd24f5e7591868d6a4 | 3,841 | java | Java | serverside/guice/main/java/org/directwebremoting/guice/AbstractDwrGuiceServletContextListener.java | stevekaminskiacp/dwr | 3c04641b673cdc300a4e9a09978349d49c00782a | [
"ECL-2.0",
"Apache-2.0"
] | 72 | 2016-12-14T12:18:18.000Z | 2022-03-14T04:27:27.000Z | serverside/guice/main/java/org/directwebremoting/guice/AbstractDwrGuiceServletContextListener.java | stevekaminskiacp/dwr | 3c04641b673cdc300a4e9a09978349d49c00782a | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-10T02:36:34.000Z | 2021-12-27T19:31:55.000Z | serverside/guice/main/java/org/directwebremoting/guice/AbstractDwrGuiceServletContextListener.java | stevekaminskiacp/dwr | 3c04641b673cdc300a4e9a09978349d49c00782a | [
"ECL-2.0",
"Apache-2.0"
] | 32 | 2017-01-03T10:28:33.000Z | 2022-03-26T20:18:03.000Z | 32.277311 | 120 | 0.694611 | 10,305 | package org.directwebremoting.guice;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.google.inject.Injector;
import static org.directwebremoting.guice.DwrGuiceUtil.*;
import static org.directwebremoting.guice.util.ContextCloseHandlers.*;
/**
* Not for subclassing directly; this is a common base for two different approaches
* to {@code Injector} creation and configuration, {@link DwrGuiceServletContextListener}
* and {@link CustomInjectorServletContextListener}.
* @author Tim Peierls [tim at peierls dot net]
*/
public abstract class AbstractDwrGuiceServletContextListener extends AbstractDwrModule implements ServletContextListener
{
/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent servletContextEvent)
{
final ServletContext servletContext = servletContextEvent.getServletContext();
DwrGuiceUtil.withServletContext(servletContext, new Runnable()
{
public void run()
{
publishInjector(servletContext, createInjector());
}
});
}
/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
List<Exception> exceptions = new ArrayList<Exception>();
DwrScopes.GLOBAL.closeAll(newExceptionLoggingCloseableHandler(exceptions));
for (Exception e : exceptions)
{
log.warn("During context destroy, closing GLOBAL-scoped Closeables: " + e, e);
}
}
/**
* Abstract subclasses define either this method or {@link #configure},
* but not both.
*/
protected abstract Injector createInjector();
/**
* Abstract subclasses define either this method or {@link #createInjector},
* but not both.
*/
@Override
protected abstract void configure();
/**
* Subclasses can use this during stage determination and binding to
* read values from the current servlet context.
*/
protected final ServletContext getServletContext()
{
return DwrGuiceUtil.getServletContext();
}
/**
* Returns the Injector instance installed in the given ServletContext.
* @param servletContext the servlet context from which to get the injector
*/
protected static Injector getPublishedInjector(ServletContext servletContext)
{
Injector injector = (Injector) servletContext.getAttribute(INJECTOR);
if (injector == null)
{
throw new IllegalStateException("Cannot find Injector in servlet context."
+ " You need to register a concrete extension of either "
+ DwrGuiceServletContextListener.class.getName()
+ " or "
+ CustomInjectorServletContextListener.class.getName()
+ " as a servlet context listener in your web.xml.");
}
return injector;
}
/**
* Stores the Injector instance in the given ServletContext.
* @param servletContext the servlet context in which to store the injector
* @param injector the injector to store
*/
protected static void publishInjector(ServletContext servletContext, Injector injector)
{
servletContext.setAttribute(INJECTOR, injector);
}
/**
* The log stream
*/
private static final Log log = LogFactory.getLog(AbstractDwrGuiceServletContextListener.class);
}
|
3e183a59dd61db9f7ceb3aaf5f3399b75a5f3ea8 | 2,729 | java | Java | src/main/java/org/fife/ui/ImageTranscodingUtil.java | bobbylight/FifeCommon | 1b940f9cbca230dba8eb9f237ae9a4b2bb54bad9 | [
"BSD-3-Clause"
] | 8 | 2015-10-01T14:37:52.000Z | 2022-03-18T09:01:35.000Z | src/main/java/org/fife/ui/ImageTranscodingUtil.java | bobbylight/FifeCommon | 1b940f9cbca230dba8eb9f237ae9a4b2bb54bad9 | [
"BSD-3-Clause"
] | 8 | 2015-03-28T16:00:33.000Z | 2021-10-17T04:51:51.000Z | src/main/java/org/fife/ui/ImageTranscodingUtil.java | bobbylight/FifeCommon | 1b940f9cbca230dba8eb9f237ae9a4b2bb54bad9 | [
"BSD-3-Clause"
] | 7 | 2015-01-16T18:26:05.000Z | 2021-10-31T18:14:10.000Z | 29.663043 | 85 | 0.750824 | 10,306 | /*
* Copyright (C) 2018 Robert Futrell
* http://fifesoft.com/rtext
* Licensed under a modified BSD license.
* See the included license file for details.
*/
package org.fife.ui;
import org.apache.batik.anim.dom.SVGDOMImplementation;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.TranscodingHints;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.util.SVGConstants;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* Utility methods for converting SVGs to images.
*/
public final class ImageTranscodingUtil {
/**
* Private constructor to prevent instantiation.
*/
private ImageTranscodingUtil() {
// Do nothing (comment for Sonar)
}
/**
* Converts an SVG into an image.
*
* @param svgName The name of the SVG. Used only in error messages.
* @param svg The SVG content.
* @param w The width of the desired image.
* @param h The height of the desired image.
* @return The created image.
* @throws IOException If an IO error occurs.
*/
public static BufferedImage rasterize(String svgName, InputStream svg, int w, int h)
throws IOException {
try (BufferedInputStream bin = new BufferedInputStream(svg)) {
TranscoderInput input = new TranscoderInput(bin);
BufferedImageGenerator t = new BufferedImageGenerator(w, h);
t.transcode(input, null);
return t.image;
} catch (TranscoderException e) {
throw new IOException("Couldn't convert " + svgName + " to an image", e);
}
}
private static class BufferedImageGenerator extends ImageTranscoder {
private BufferedImage image;
private int width;
private int height;
BufferedImageGenerator(int width, int height) {
this.width = width;
this.height = height;
setTranscodingHints(createTranscodingHints(width, height));
}
@Override
public BufferedImage createImage(int w, int h) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
private static TranscodingHints createTranscodingHints(int width, int height) {
TranscodingHints hints = new TranscodingHints();
hints.put(ImageTranscoder.KEY_DOM_IMPLEMENTATION,
SVGDOMImplementation.getDOMImplementation());
hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI,
SVGConstants.SVG_NAMESPACE_URI);
hints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT, "svg");
hints.put(ImageTranscoder.KEY_WIDTH, (float)width);
hints.put(ImageTranscoder.KEY_HEIGHT, (float)height);
return hints;
}
@Override
public void writeImage(BufferedImage image, TranscoderOutput out) {
this.image = image;
}
}
}
|
3e183b544d997bcb1a0ced941239bb8514d06520 | 817 | java | Java | src/main/java/ch/sharedvd/tipi/engine/client/TipiVariable.java | shared-vd/tipi | 460bbfa05bb288382d88b0ebcf8559a346b1e527 | [
"Apache-2.0"
] | 3 | 2017-12-21T08:21:37.000Z | 2018-01-09T13:18:00.000Z | src/main/java/ch/sharedvd/tipi/engine/client/TipiVariable.java | shared-vd/tipi | 460bbfa05bb288382d88b0ebcf8559a346b1e527 | [
"Apache-2.0"
] | null | null | null | src/main/java/ch/sharedvd/tipi/engine/client/TipiVariable.java | shared-vd/tipi | 460bbfa05bb288382d88b0ebcf8559a346b1e527 | [
"Apache-2.0"
] | null | null | null | 25.53125 | 155 | 0.746634 | 10,307 | package ch.sharedvd.tipi.engine.client;
import ch.sharedvd.tipi.engine.meta.VariableType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation utilisée pour définire une variable Tipi
*/
@Target(ElementType.TYPE)
// Applies to classes, interfaces
@Retention(RetentionPolicy.RUNTIME)
// Load all annotations at runtime
public @interface TipiVariable {
String name();
String description() default "";
VariableType type();
/**
* La valeur par défaut de la variable qui sera utilisée si aucune valeur explicite n'est fournie. Une valeur vide signifie "pas de valeur par défaut".
*/
String defaultValue() default "";
boolean required() default false;
}
|
3e183bb32eb5dd736ab7549c5f826009e7c191bd | 5,431 | java | Java | ClansPro/src/main/java/com/github/sanctum/clans/construct/api/Channel.java | the-h-team/ClansPro | 021cdf942f10e9d0ab264804b181c66c55a73c02 | [
"MIT"
] | 2 | 2021-07-26T00:10:38.000Z | 2022-02-06T08:08:54.000Z | ClansPro/src/main/java/com/github/sanctum/clans/construct/api/Channel.java | the-h-team/ClansPro | 021cdf942f10e9d0ab264804b181c66c55a73c02 | [
"MIT"
] | null | null | null | ClansPro/src/main/java/com/github/sanctum/clans/construct/api/Channel.java | the-h-team/ClansPro | 021cdf942f10e9d0ab264804b181c66c55a73c02 | [
"MIT"
] | 2 | 2021-08-03T22:43:43.000Z | 2021-08-03T22:44:35.000Z | 37.715278 | 333 | 0.720678 | 10,308 | package com.github.sanctum.clans.construct.api;
import com.github.sanctum.clans.construct.extra.BukkitColor;
import com.github.sanctum.labyrinth.LabyrinthProvider;
import com.github.sanctum.labyrinth.annotation.Note;
import com.github.sanctum.labyrinth.data.service.Constant;
import com.github.sanctum.labyrinth.formatting.FancyMessage;
import com.github.sanctum.labyrinth.formatting.Message;
import com.github.sanctum.labyrinth.formatting.string.RandomHex;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
public interface Channel {
Channel CLAN = valueOf("CLAN");
Channel ALLY = valueOf("ALLY");
Channel GLOBAL = valueOf("GLOBAL");
static Channel[] values() {
return Constant.values(Channel.class, Channel.class).toArray(new Channel[0]);
}
/**
* @apiNote Safe to use for custom chat channel provision!
*/
static Channel valueOf(String name) {
return Constant.values(Channel.class).stream().filter(c -> c.getName().equals(name)).map(Constant::getValue).findFirst().orElse(new Channel() {
@Override
public @NotNull String getId() {
return name;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Channel)) return false;
Channel chatChannel = (Channel) obj;
return chatChannel.getId().equals(getId());
}
@Override
public String toString() {
return getId();
}
});
}
@NotNull String getId();
default Filter[] getFilters() {
return InoperableSpecialMemory.FILTERS.stream().filter(f -> f.getChannel().equals(this)).toArray(Filter[]::new);
}
default void register(Filter filter) {
InoperableSpecialMemory.FILTERS.add(filter);
}
default void register(Function<String, String> filter) {
InoperableSpecialMemory.FILTERS.add(new Filter() {
@Override
public @NotNull Channel getChannel() {
return Channel.this;
}
@Override
public @NotNull String run(String context) {
return filter.apply(context);
}
});
}
/**
* Get related associates that are in the same chat channel as this.
*
* @param parent The invasive parent to check.
* @return A set of all mutually known clan associates in this channel.
*/
default Set<Clan.Associate> getAudience(InvasiveEntity parent) {
if (parent instanceof Clan) {
Set<Clan.Associate> set = ((Clan) parent).getMembers().stream().filter(m -> m.getChannel().equals(this)).collect(Collectors.toSet());
for (InvasiveEntity ent : parent.getAsClan().getRelation()) {
if (ent.isClan()) {
set.addAll(ent.getAsClan().getMembers().stream().filter(m -> m.getChannel().equals(this)).collect(Collectors.toSet()));
}
}
return set;
}
if (!(parent instanceof Clan.Associate)) return null;
Set<Clan.Associate> set = ((Clan.Associate) parent).getClan().getMembers().stream().filter(m -> m.getChannel().equals(this)).collect(Collectors.toSet());
for (InvasiveEntity ent : parent.getAsClan().getRelation()) {
if (ent.isClan()) {
set.addAll(ent.getAsClan().getMembers().stream().filter(m -> m.getChannel().equals(this)).collect(Collectors.toSet()));
}
}
return set;
}
/**
* Get all known associates participating within this chat channel.
*
* @return every known associate residing within this chat channel.
* @apiNote Don't use this method unless you want to get every clan associate online
* that is currently in this channel.
*/
@Note("Gets every known associate residing within this chat channel.")
default Set<Clan.Associate> getAudience() {
Set<Clan.Associate> associates = new HashSet<>();
ClansAPI.getInstance().getClanManager().getClans().forEach(c -> c.getMembers().forEach(a -> {
if (a.getChannel().equals(this)) {
associates.add(a);
}
}));
return associates;
}
default Message tryFormat(Clan.Associate associate) {
FancyMessage message = new FancyMessage();
message.then(MessageFormat.format("(" + (LabyrinthProvider.getInstance().isNew() ? new RandomHex().context(getId()).join() : BukkitColor.random().toCode().replace("0", "f") + getId()) + "&r) ", associate.getNickname(), associate.getName(), associate.getClan().getPalette(), associate.getRankFull(), associate.getClan().getName()));
message.then(MessageFormat.format(ClansAPI.getDataInstance().getConfig().getRoot().getString("Formatting.Chat.Channel.ally.highlight"), associate.getNickname(), associate.getName(), associate.getClan().getPalette(), associate.getRankFull(), associate.getClan().getName()));
message.then(MessageFormat.format(ClansAPI.getDataInstance().getConfig().getRoot().getString("Formatting.Chat.Channel.ally.divider") + "%MESSAGE%", associate.getNickname(), associate.getName(), associate.getClan().getPalette(), associate.getRankFull(), associate.getClan().getName()));
message.hover(MessageFormat.format(ClansAPI.getDataInstance().getConfig().getRoot().getString("Formatting.Chat.Channel.ally.hover"), associate.getNickname(), associate.getName(), associate.getClan().getPalette(), associate.getRankFull(), associate.getClan().getName()));
return message;
}
default boolean isDefault() {
return getId().equals(GLOBAL.toString()) || getId().equals(CLAN.toString()) || getId().equals(ALLY.toString());
}
interface Filter {
@NotNull Channel getChannel();
@NotNull String run(String context);
}
}
|
3e183c252cb84ad2b9a0d56babcfbf61368702c4 | 2,177 | java | Java | lambdas-and-fields/javaspec-runner/src/test/java/info/javaspecfeature/CommandLineInterfaceSteps.java | kkrull/javaspec | 1ed4d20cdee5bc5b153c7b1728011e338cb4140b | [
"MIT"
] | 10 | 2015-07-08T15:07:15.000Z | 2022-02-26T05:47:24.000Z | lambdas-and-fields/javaspec-runner/src/test/java/info/javaspecfeature/CommandLineInterfaceSteps.java | kkrull/javaspec | 1ed4d20cdee5bc5b153c7b1728011e338cb4140b | [
"MIT"
] | 12 | 2015-02-07T04:43:07.000Z | 2022-03-16T14:40:32.000Z | lambdas-and-fields/javaspec-runner/src/test/java/info/javaspecfeature/CommandLineInterfaceSteps.java | kkrull/javaspec | 1ed4d20cdee5bc5b153c7b1728011e338cb4140b | [
"MIT"
] | 1 | 2015-10-24T17:20:03.000Z | 2015-10-24T17:20:03.000Z | 38.192982 | 119 | 0.765733 | 10,309 | package info.javaspecfeature;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import info.javaspec.JavaSpec;
import info.javaspec.JavaSpec.ExitHandler;
import org.mockito.Mockito;
import java.io.PrintStream;
import static org.mockito.Mockito.mock;
public class CommandLineInterfaceSteps {
private final PrintStream console = mock(PrintStream.class);
private final ExitHandler exit = mock(ExitHandler.class);
@When("^I run JavaSpec without any arguments$")
public void i_run_JavaSpec_without_any_arguments() throws Exception {
JavaSpec.main(console, exit);
}
@When("^I run JavaSpec with unsupported arguments$")
public void i_run_JavaSpec_with_unsupported_arguments() throws Exception {
JavaSpec.main(console, exit, "--bogus");
}
@When("^I ask the JavaSpec runner for help$")
public void i_ask_the_JavaSpec_runner_for_help() throws Exception {
JavaSpec.main(console, exit, "--help");
}
@When("^I ask the JavaSpec runner for its version$")
public void i_ask_the_JavaSpec_runner_for_its_version() throws Exception {
JavaSpec.main(console, exit, "--version");
}
@Then("^the command line interface should print a usage statement to the console that describes how it may be used$")
public void the_command_line_interface_should_print_a_usage_statement_to_the_console() throws Exception {
Mockito.verify(console).println("Usage: java info.javaspec.JavaSpec --version");
Mockito.verify(console).println("--help: Show this help");
Mockito.verify(console).println("--version: Show the version");
Mockito.verifyNoMoreInteractions(console);
}
@Then("^the command line interface should print its version number to the console$")
public void the_command_line_interface_should_print_its_version_number_to_the_console() throws Exception {
Mockito.verify(console).println("1.0.1");
Mockito.verifyNoMoreInteractions(console);
}
@Then("^the command line interface should exit with status (\\d+)$")
public void the_command_line_interface_should_exit_with_status(int status) throws Exception {
Mockito.verify(exit).exit(status);
Mockito.verifyNoMoreInteractions(exit);
}
}
|
3e183c4a4cd2493fe004c969f399df079c3eb481 | 1,058 | java | Java | de.chdev.artools.sql/src/de/chdev/artools/sql/ui/Messages.java | cheinig/studio-ar-tools | 1931e081211168cec37caaac7f160339cd9529a7 | [
"Apache-2.0"
] | null | null | null | de.chdev.artools.sql/src/de/chdev/artools/sql/ui/Messages.java | cheinig/studio-ar-tools | 1931e081211168cec37caaac7f160339cd9529a7 | [
"Apache-2.0"
] | 1 | 2015-03-14T12:18:01.000Z | 2015-03-14T12:18:48.000Z | de.chdev.artools.sql/src/de/chdev/artools/sql/ui/Messages.java | cheinig/studio-ar-tools | 1931e081211168cec37caaac7f160339cd9529a7 | [
"Apache-2.0"
] | null | null | null | 32.060606 | 93 | 0.736295 | 10,310 | /*
Copyright 2011 Christoph Heinig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.chdev.artools.sql.ui;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
private static final String BUNDLE_NAME = "de.chdev.artools.sql.ui.messages"; //$NON-NLS-1$
public static String ExporterDialog_fileDialogTitle;
public static String ExporterDialog_filenameLabel;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
|
3e183c9f87296242ad98abe99b1400412eacfb9c | 183 | java | Java | src/main/java/com/buliang/util/Constant.java | lian12385/EasyBuy | 6baf9d81d04e646fcea26649120a8b3722e98d9c | [
"Artistic-2.0"
] | null | null | null | src/main/java/com/buliang/util/Constant.java | lian12385/EasyBuy | 6baf9d81d04e646fcea26649120a8b3722e98d9c | [
"Artistic-2.0"
] | null | null | null | src/main/java/com/buliang/util/Constant.java | lian12385/EasyBuy | 6baf9d81d04e646fcea26649120a8b3722e98d9c | [
"Artistic-2.0"
] | null | null | null | 20.333333 | 48 | 0.743169 | 10,311 | package com.buliang.util;
//temporary known how to write
public class Constant {
public static final int USER_TYPE_ADMIN = 1;
public static final int USER_TYP_NORMAL = 0;
}
|
3e183d2b2ad461f578a7918c5fc43151d4657489 | 2,816 | java | Java | com.forgedui.editor/src/com/forgedui/editor/figures/AlertDialogFigure.java | ShoukriKattan/ForgedUI-Eclipse | f8d2a9b90d0c26242115c8aed4978b82e075fc11 | [
"MIT"
] | 1 | 2017-06-29T07:25:41.000Z | 2017-06-29T07:25:41.000Z | com.forgedui.editor/src/com/forgedui/editor/figures/AlertDialogFigure.java | ShoukriKattan/ForgedUI-Eclipse | f8d2a9b90d0c26242115c8aed4978b82e075fc11 | [
"MIT"
] | null | null | null | com.forgedui.editor/src/com/forgedui/editor/figures/AlertDialogFigure.java | ShoukriKattan/ForgedUI-Eclipse | f8d2a9b90d0c26242115c8aed4978b82e075fc11 | [
"MIT"
] | null | null | null | 27.076923 | 91 | 0.71875 | 10,312 | // LICENSE
package com.forgedui.editor.figures;
import org.eclipse.draw2d.FigureUtilities;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import com.forgedui.util.Utils;
/**
* @author Dmitry {dmitry.grimm@gmail.com}
*
*/
public class AlertDialogFigure extends TitaniumTextFigure {
private String explanation;
protected Font titleFont;
private DialogOptionFigure okButton;
public AlertDialogFigure(DialogOptionFigure okButton) {
setTextHorisontalAlign(Alignments.center);
setTextVerticalAlign(Alignments.top);
setMargin(7);
this.okButton = okButton;
}
public void setExplanation(String text) {
if (Utils.safeNotEquals(this.explanation, text)){
this.explanation = text;
setDirty(true);
}
}
public void setOkText(String okText){
if (Utils.safeNotEquals(okButton.getText(), okText)){
okButton.setText(okText);
setDirty(true);
}
}
@Override
protected void paintTitaniumFigure(Graphics graphics) {
titleFont = createTitleFont();
graphics.pushState();
graphics.setFont(titleFont);
paintTitle(graphics);
graphics.popState();
paintLines(graphics, getLines(), getLinesHolderRectangle());
Rectangle expRect = getTextHolderRectangle();
if (explanation != null && explanation.length() > 0){
int titleHeight = getMargin()*2;
if (getText() != null && getText().length() > 0){
titleHeight += FigureUtilities.getStringExtents(getText(), titleFont).height;
}
expRect.height -= titleHeight;
expRect.y += titleHeight;
paintString(graphics, explanation, expRect);
}
if (okButton.getText() != null){
graphics.setFont(okButton.getFont_());
Dimension p = FigureUtilities.getStringExtents(okButton.getText(), okButton.getFont_());
p.expand(20, 4);
p.width = Math.min(p.width, expRect.width);
p.height = 40;
okButton.setBounds(new Rectangle(expRect.getBottomLeft().getTranslated(
(expRect.width - p.width) / 2, -2 - p.height), p));
okButton.paint(graphics);
}
titleFont.dispose();
}
public void paintTitle(Graphics graphics) {
paintString(graphics, getText(), getTextHolderRectangle());
}
protected Rectangle getLinesHolderRectangle(){
Rectangle r = getClientArea();
if (useLocalCoordinates()){
r.setLocation(getBounds().getLocation());
}
if (getText() != null && getText().length() > 0){
Dimension textSize = FigureUtilities.getStringExtents(getText(), titleFont);
r.y += textSize.height + getMargin();
r.height -= textSize.height + getMargin();
}
return r;
}
protected Font createTitleFont(){
FontData fd = getFont_().getFontData()[0];
fd.setHeight(fd.getHeight() + 3);
return new Font(null, fd);
}
}
|
3e183d6ddbc4967aebacbb82d726f79552068e50 | 287 | java | Java | src/main/java/monte/carlo/controller/ControllerInterface.java | zuvladimir/monte_carlo | f87ab6481277d1995567b9ea1d1b49e04bb9cba3 | [
"MIT"
] | null | null | null | src/main/java/monte/carlo/controller/ControllerInterface.java | zuvladimir/monte_carlo | f87ab6481277d1995567b9ea1d1b49e04bb9cba3 | [
"MIT"
] | null | null | null | src/main/java/monte/carlo/controller/ControllerInterface.java | zuvladimir/monte_carlo | f87ab6481277d1995567b9ea1d1b49e04bb9cba3 | [
"MIT"
] | null | null | null | 23.916667 | 49 | 0.770035 | 10,313 | package monte.carlo.controller;
/**
* Интерфейс контроллера
*/
public interface ControllerInterface {
public void calcRiskOfWorkingHoursEncrease();
public void calcRiskOfLackResources();
public void calcRiskOfWorkloadEncrease();
public void makeDecisionAlgorithm();
}
|
3e183d788876ce7c9b91be73b4b33597cdcaeede | 2,085 | java | Java | src/main/java/com/Mrbysco/LoyaltyRewards/registry/actions/ItemAction.java | Mrbysco/LoyaltyRewards | d73a6df75f0e9742b58391fb2decfa14a7b7d46a | [
"MIT"
] | null | null | null | src/main/java/com/Mrbysco/LoyaltyRewards/registry/actions/ItemAction.java | Mrbysco/LoyaltyRewards | d73a6df75f0e9742b58391fb2decfa14a7b7d46a | [
"MIT"
] | 4 | 2020-05-17T04:43:22.000Z | 2022-03-01T09:11:00.000Z | src/main/java/com/Mrbysco/LoyaltyRewards/registry/actions/ItemAction.java | Mrbysco/LoyaltyRewards | d73a6df75f0e9742b58391fb2decfa14a7b7d46a | [
"MIT"
] | null | null | null | 40.882353 | 269 | 0.620624 | 10,314 | package com.mrbysco.loyaltyrewards.registry.actions;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
public class ItemAction extends BaseAction {
private final ItemStack[] stacks;
public ItemAction(ItemStack[] stacks) {
this.stacks = stacks;
}
public ItemAction(ItemStack stack) {
this.stacks = new ItemStack[] {stack};
}
@Override
public void trigger(World worldIn, BlockPos pos, PlayerEntity playerIn) {
if(stacks.length > 0) {
for (ItemStack itemStack : stacks) {
ItemStack stack = itemStack.copy();
if (!stack.isEmpty()) {
if (playerIn.addItem(stack)) {
playerIn.level.playSound((PlayerEntity) null, playerIn.getX(), playerIn.getY(), playerIn.getZ(), SoundEvents.ITEM_PICKUP, SoundCategory.PLAYERS, 0.2F, ((playerIn.getRandom().nextFloat() - playerIn.getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F);
} else {
ITextComponent text = new TranslationTextComponent("loyaltyrewards.inventory.full").withStyle(TextFormatting.YELLOW);
playerIn.sendMessage(text, Util.NIL_UUID);
ItemEntity itemEntity = EntityType.ITEM.create(worldIn);
if(itemEntity != null) {
itemEntity.setItem(stack);
itemEntity.setPos(pos.getX(), pos.getY() + 0.5, pos.getZ());
worldIn.addFreshEntity(itemEntity);
}
}
}
}
}
}
}
|
3e183d98ebacaeed7a467694a936b80335bf66c0 | 2,889 | java | Java | shardingsphere-agent/shardingsphere-agent-plugins/shardingsphere-agent-plugin-tracing/shardingsphere-agent-tracing-opentelemetry/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/advice/CommandExecutorTaskAdvice.java | aniketh-varma/shardingsphere | 6ebef5296b4e726beb06d2947bbc46b27942e425 | [
"Apache-2.0"
] | 5,788 | 2020-04-17T14:09:07.000Z | 2022-03-31T08:12:53.000Z | shardingsphere-agent/shardingsphere-agent-plugins/shardingsphere-agent-plugin-tracing/shardingsphere-agent-tracing-opentelemetry/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/advice/CommandExecutorTaskAdvice.java | aniketh-varma/shardingsphere | 6ebef5296b4e726beb06d2947bbc46b27942e425 | [
"Apache-2.0"
] | 6,488 | 2020-04-17T14:21:54.000Z | 2022-03-31T21:36:33.000Z | shardingsphere-agent/shardingsphere-agent-plugins/shardingsphere-agent-plugin-tracing/shardingsphere-agent-tracing-opentelemetry/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/advice/CommandExecutorTaskAdvice.java | aniketh-varma/shardingsphere | 6ebef5296b4e726beb06d2947bbc46b27942e425 | [
"Apache-2.0"
] | 2,504 | 2020-04-17T14:09:46.000Z | 2022-03-31T12:21:31.000Z | 46.596774 | 142 | 0.77224 | 10,315 | /*
* 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.shardingsphere.agent.plugin.tracing.opentelemetry.advice;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import org.apache.shardingsphere.agent.api.advice.AdviceTargetObject;
import org.apache.shardingsphere.agent.api.advice.InstanceMethodAroundAdvice;
import org.apache.shardingsphere.agent.api.result.MethodInvocationResult;
import org.apache.shardingsphere.agent.plugin.tracing.opentelemetry.constant.OpenTelemetryConstants;
import org.apache.shardingsphere.infra.executor.kernel.model.ExecutorDataMap;
import java.lang.reflect.Method;
/**
* Command executor task advice.
*/
public class CommandExecutorTaskAdvice implements InstanceMethodAroundAdvice {
private static final String OPERATION_NAME = "/ShardingSphere/rootInvoke/";
@Override
public void beforeMethod(final AdviceTargetObject target, final Method method, final Object[] args, final MethodInvocationResult result) {
SpanBuilder spanBuilder = GlobalOpenTelemetry.getTracer("shardingsphere-agent")
.spanBuilder(OPERATION_NAME)
.setAttribute(OpenTelemetryConstants.COMPONENT, OpenTelemetryConstants.COMPONENT_NAME)
.setSpanKind(SpanKind.CLIENT);
Span span = spanBuilder.startSpan();
target.setAttachment(span);
ExecutorDataMap.getValue().put(OpenTelemetryConstants.ROOT_SPAN, span);
}
@Override
public void afterMethod(final AdviceTargetObject target, final Method method, final Object[] args, final MethodInvocationResult result) {
((Span) target.getAttachment()).end();
ExecutorDataMap.getValue().remove(OpenTelemetryConstants.ROOT_SPAN);
}
@Override
public void onThrowing(final AdviceTargetObject target, final Method method, final Object[] args, final Throwable throwable) {
((Span) target.getAttachment()).setStatus(StatusCode.ERROR).recordException(throwable);
}
}
|
3e183da4f3a603a24f3645d8c66813393705b816 | 29,753 | java | Java | src/com/radicaldynamic/groupinform/services/DatabaseService.java | radicaldynamic/gcmobile | dc316b3f29349a9abfa2edbdc5dbcc79c733d6f2 | [
"Apache-2.0"
] | 4 | 2015-03-25T03:36:48.000Z | 2017-01-25T05:07:14.000Z | src/com/radicaldynamic/groupinform/services/DatabaseService.java | mattadams/gcmobile | dc316b3f29349a9abfa2edbdc5dbcc79c733d6f2 | [
"Apache-2.0"
] | null | null | null | src/com/radicaldynamic/groupinform/services/DatabaseService.java | mattadams/gcmobile | dc316b3f29349a9abfa2edbdc5dbcc79c733d6f2 | [
"Apache-2.0"
] | 4 | 2015-08-21T07:58:04.000Z | 2017-01-25T05:07:16.000Z | 41.729313 | 169 | 0.573522 | 10,316 | /*
* Copyright (C) 2009 University of Washington
*
* 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.radicaldynamic.groupinform.services;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.DbAccessException;
import org.ektorp.ReplicationCommand;
import org.ektorp.ReplicationStatus;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.ConditionVariable;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import com.radicaldynamic.gcmobile.android.preferences.PreferencesActivity;
import com.radicaldynamic.groupinform.R;
import com.radicaldynamic.groupinform.application.Collect;
import com.radicaldynamic.groupinform.database.InformCouchDbConnector;
import com.radicaldynamic.groupinform.documents.Generic;
import com.radicaldynamic.groupinform.logic.AccountFolder;
import com.radicaldynamic.groupinform.repositories.FormDefinitionRepo;
import com.radicaldynamic.groupinform.repositories.FormInstanceRepo;
/**
* Database abstraction layer for CouchDB, based on Ektorp.
*
* This does not control the stop/start of the actual DB.
* See com.couchone.couchdb.CouchService for that.
*/
public class DatabaseService extends Service {
private static final String t = "DatabaseService: ";
// Replication modes
public static final int REPLICATE_PUSH = 0;
public static final int REPLICATE_PULL = 1;
// Minutes represented as seconds
private static final int TIME_FIVE_MINUTES = 300;
private static final int TIME_TEN_MINUTES = 600;
// 24 hours (represented as milliseconds)
private static final long TIME_24_HOURS = 86400000;
// Values returned by the Couch service -- we can't connect to the localhost until these are known
private String mLocalHost = null;
private int mLocalPort = 0;
private HttpClient mLocalHttpClient = null;
private CouchDbInstance mLocalDbInstance = null;
private CouchDbConnector mLocalDbConnector = null;
private HttpClient mRemoteHttpClient = null;
private CouchDbInstance mRemoteDbInstance = null;
private CouchDbConnector mRemoteDbConnector = null;
private boolean mInit = false;
private boolean mConnectedToLocal = false;
private boolean mConnectedToRemote = false;
// This is the object that receives interactions from clients.
// See RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
private ConditionVariable mCondition;
// Hash of database-to-last cleanup timestamp (used for controlled purging databases of placeholders)
private Map<String, Long> mDbLastCleanup = new HashMap<String, Long>();
// Hash of database-to-last replication timestamp
private Map<String, Long> mDbLastReplication = new HashMap<String, Long>();
private Runnable mTask = new Runnable()
{
final String tt = t + "mTask: ";
public void run()
{
for (int i = 1; i > 0; ++i) {
if (mInit == false) {
try {
mInit = true;
if (mLocalDbInstance != null) {
performHousekeeping();
synchronizeLocalDBs();
}
} catch (Exception e) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "error automatically connecting to DB: " + e.toString());
} finally {
mInit = false;
}
}
// Retry connection to CouchDB every 5 minutes
if (mCondition.block(TIME_FIVE_MINUTES * 1000))
break;
}
}
};
@SuppressWarnings("serial")
public class DbUnavailableException extends Exception
{
DbUnavailableException()
{
super();
}
}
@SuppressWarnings("serial")
public class DbUnavailableWhileOfflineException extends DbUnavailableException
{
DbUnavailableWhileOfflineException()
{
super();
}
}
@SuppressWarnings("serial")
public class DbUnavailableDueToMetadataException extends DbUnavailableException
{
DbUnavailableDueToMetadataException(String db)
{
super();
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, t + "metadata missing for DB " + db);
}
}
@Override
public void onCreate()
{
Thread persistentConnectionThread = new Thread(null, mTask, "DatabaseService");
mCondition = new ConditionVariable(false);
persistentConnectionThread.start();
}
@Override
public void onDestroy()
{
mCondition.open();
}
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, t + "received start ID " + startId + ": " + intent);
return START_STICKY;
}
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder
{
public DatabaseService getService()
{
return DatabaseService.this;
}
}
// Convenience method (uses currently selected database)
public CouchDbConnector getDb()
{
return getDb(Collect.getInstance().getInformOnlineState().getSelectedDatabase());
}
public CouchDbConnector getDb(String db)
{
final String tt = t + "getDb(): ";
AccountFolder folder = Collect.getInstance().getInformOnlineState().getAccountFolders().get(db);
CouchDbConnector dbConnector;
if (folder.isReplicated()) {
// Local database
try {
open(db);
} catch (DbUnavailableException e) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "unable to connect to local database server: " + e.toString());
}
dbConnector = mLocalDbConnector;
} else {
// Remote database
try {
open(db);
} catch (DbUnavailableException e) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "unable to connect to remote database server: " + e.toString());
}
dbConnector = mRemoteDbConnector;
}
return dbConnector;
}
/*
* Does a database exist on the local CouchDB instance?
*/
public boolean isDbLocal(String db)
{
final String tt = t + "isDbLocal(): ";
boolean result = false;
try {
if (mLocalDbInstance == null)
connectToLocalServer();
if (mLocalDbInstance.getAllDatabases().indexOf("db_" + db) != -1)
result = true;
} catch (DbAccessException e) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + e.toString());
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unhandled exception: " + e.toString());
}
return result;
}
/**
* Open a specific database
*
* @param database Name of database to open
* @return
* @throws DbMetadataUnavailableException
* @throws DbUnavailableException
*/
public void open(String db) throws DbUnavailableException
{
// If database metadata is not yet available then abort here
if (db == null || Collect.getInstance().getInformOnlineState().getAccountFolders().get(db) == null) {
throw new DbUnavailableDueToMetadataException(db);
}
if (!Collect.getInstance().getIoService().isSignedIn() && !Collect.getInstance().getInformOnlineState().getAccountFolders().get(db).isReplicated())
throw new DbUnavailableWhileOfflineException();
boolean dbToOpenIsReplicated = Collect.getInstance().getInformOnlineState().getAccountFolders().get(db).isReplicated();
if (dbToOpenIsReplicated) {
// Local database
if (mConnectedToLocal) {
if (mLocalDbConnector instanceof StdCouchDbConnector && mLocalDbConnector.getDatabaseName().equals("db_" + db)) {
return;
}
} else {
connectToLocalServer();
}
openLocalDb(db);
} else {
// Remote database
if (mConnectedToRemote) {
if (mRemoteDbConnector instanceof StdCouchDbConnector && mRemoteDbConnector.getDatabaseName().equals("db_" + db)) {
return;
}
} else {
connectToRemoteServer();
}
openRemoteDb(db);
}
}
/*
* Similar in purpose to performHousekeeping(), this method is targeted towards any database
*/
public void performHousekeeping(String db) throws DbUnavailableException
{
final String tt = t + "performHousekeeping(String): ";
// Determine if this database needs to be cleaned up
Long lastCleanup = mDbLastCleanup.get(db);
if (lastCleanup == null || System.currentTimeMillis() / 1000 - lastCleanup >= TIME_TEN_MINUTES) {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "beginning cleanup for " + db);
mDbLastCleanup.put(db, new Long(System.currentTimeMillis() / 1000));
removePlaceholders(new FormDefinitionRepo(getDb()).getAllPlaceholders());
removePlaceholders(new FormInstanceRepo(getDb()).getAllPlaceholders());
}
}
synchronized public ReplicationStatus replicate(String db, int mode)
{
final String tt = t + "replicate(): ";
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "about to replicate " + db);
// Will not replicate unless signed in
if (!Collect.getInstance().getIoService().isSignedIn()) {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "aborting replication: not signed in");
return null;
}
if (Collect.getInstance().getInformOnlineState().isOfflineModeEnabled()) {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "aborting replication: offline mode is enabled");
return null;
}
/*
* Lookup master cluster by IP. Do this instead of relying on Erlang's internal resolver
* (and thus Google's public DNS). Our builds of Erlang for Android do not yet use
* Android's native DNS resolver.
*/
String masterClusterIP = null;
try {
InetAddress [] clusterInetAddresses = InetAddress.getAllByName(getString(R.string.tf_default_ionline_server));
masterClusterIP = clusterInetAddresses[new Random().nextInt(clusterInetAddresses.length)].getHostAddress();
} catch (UnknownHostException e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unable to lookup master cluster IP addresses: " + e.toString());
e.printStackTrace();
}
// Create local instance of database
boolean dbCreated = false;
// User may not have connected to local database yet - start up the connection for them
try {
if (mLocalDbInstance == null) {
connectToLocalServer();
}
} catch (DbUnavailableException e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "cannot connect to local database server");
e.printStackTrace();
}
if (mLocalDbInstance.getAllDatabases().indexOf("db_" + db) == -1) {
switch (mode) {
case REPLICATE_PULL:
if (Collect.Log.INFO) Log.i(Collect.LOGTAG, tt + "creating local database " + db);
mLocalDbInstance.createDatabase("db_" + db);
dbCreated = true;
break;
case REPLICATE_PUSH:
// If the database does not exist client side then there is no point in continuing
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "cannot find local database " + db + " to push");
return null;
}
}
// Configure replication direction
String source = null;
String target = null;
String deviceId = Collect.getInstance().getInformOnlineState().getDeviceId();
String deviceKey = Collect.getInstance().getInformOnlineState().getDeviceKey();
String localServer = "http://" + mLocalHost + ":" + mLocalPort + "/db_" + db;
String remoteServer = "http://" + deviceId + ":" + deviceKey + "@" + masterClusterIP + ":5984/db_" + db;
// Should we use encrypted transfers?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
if (settings.getBoolean(PreferencesActivity.KEY_ENCRYPT_SYNCHRONIZATION, true)) {
remoteServer = "https://" + deviceId + ":" + deviceKey + "@" + masterClusterIP + ":6984/db_" + db;
}
switch (mode) {
case REPLICATE_PUSH:
source = localServer;
target = remoteServer;
break;
case REPLICATE_PULL:
source = remoteServer;
target = localServer;
break;
}
ReplicationCommand cmd = new ReplicationCommand.Builder().source(source).target(target).build();
ReplicationStatus status = null;
try {
status = mLocalDbInstance.replicate(cmd);
} catch (Exception e) {
// Remove a recently created DB if the replication failed
if (dbCreated) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, t + "replication exception: " + e.toString());
e.printStackTrace();
mLocalDbInstance.deleteDatabase("db_" + db);
}
}
return status;
}
public void setLocalDatabaseInfo(String host, int port)
{
final String tt = t + "setLocalDatabaseInfo(): ";
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "set host and port to " + host + ":" + port);
mLocalHost = host;
mLocalPort = port;
}
synchronized private void connectToLocalServer() throws DbUnavailableException
{
final String tt = t + "connectToLocalServer(): ";
if (mLocalHost == null || mLocalPort == 0) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "local host information not available; aborting connection");
mConnectedToLocal = false;
return;
}
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "establishing connection to " + mLocalHost + ":" + mLocalPort);
try {
/*
* Socket timeout of 5 minutes is important, otherwise long-running replications
* will fail. It is possible that we will need to extend this in the future if
* it turns out to be insufficient.
*/
mLocalHttpClient = new StdHttpClient.Builder()
.host(mLocalHost)
.port(mLocalPort)
.socketTimeout(TIME_FIVE_MINUTES * 1000)
.build();
mLocalDbInstance = new StdCouchDbInstance(mLocalHttpClient);
mLocalDbInstance.getAllDatabases();
if (mConnectedToLocal == false)
mConnectedToLocal = true;
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "connection to " + mLocalHost + " successful");
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + e.toString());
e.printStackTrace();
mConnectedToLocal = false;
throw new DbUnavailableException();
}
}
synchronized private void connectToRemoteServer() throws DbUnavailableException
{
final String tt = t + "connectToRemoteServer(): ";
String host = getString(R.string.tf_default_ionline_server);
int port = 6984;
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "establishing connection to " + host + ":" + port);
try {
mRemoteHttpClient = new StdHttpClient.Builder()
.enableSSL(true)
.host(host)
.port(port)
.socketTimeout(30 * 1000)
.username(Collect.getInstance().getInformOnlineState().getDeviceId())
.password(Collect.getInstance().getInformOnlineState().getDeviceKey())
.build();
mRemoteDbInstance = new StdCouchDbInstance(mRemoteHttpClient);
mRemoteDbInstance.getAllDatabases();
if (mConnectedToRemote == false)
mConnectedToRemote = true;
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "connection to " + host + " successful");
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "while connecting to server " + port + ": " + e.toString());
e.printStackTrace();
mConnectedToRemote = false;
throw new DbUnavailableException();
}
}
private void openLocalDb(String db) throws DbUnavailableException
{
final String tt = t + "openLocalDb(): ";
try {
/*
* We used to create the database if it did not exist HOWEVER this had unintended side effects.
*
* Since local databases are typically initialized on-demand the first time the user selects
* them for operations, databases that were selected for replication but not yet "switched to"
* would be created as empty databases if the user backed out of the folder selection screen
* without specifically choosing a database.
*
* Because the database then existed, attempts to "switch to" the database via the folder
* selection screen (and have it initialized on-demand as expected) would fail. At least,
* until the system got around to creating and replicating it automatically.
*/
if (mLocalDbInstance.getAllDatabases().indexOf("db_" + db) == -1) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "database does not exist; failing attempt to open");
throw new DbUnavailableException();
}
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "opening database " + db);
mLocalDbConnector = new InformCouchDbConnector("db_" + db, mLocalDbInstance);
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "while opening DB " + db + ": " + e.toString());
e.printStackTrace();
throw new DbUnavailableException();
}
}
private void openRemoteDb(String db) throws DbUnavailableException
{
final String tt = t + "openRemoteDb(): ";
try {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "opening database " + db);
mRemoteDbConnector = new InformCouchDbConnector("db_" + db, mRemoteDbInstance);
/*
* This should trigger any 401:Unauthorized errors when connecting to a remote DB
* (better to know about them now then to experience a crash later because we didn't trap something)
*/
mRemoteDbConnector.getDbInfo();
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "while opening DB " + db + ": " + e.toString());
e.printStackTrace();
throw new DbUnavailableException();
}
}
/*
* Perform any house keeping (e.g., removing of unused DBs, view compaction & cleanup)
*/
private void performHousekeeping()
{
final String tt = t + "performHousekeeping(): ";
try {
List<String> allDatabases = mLocalDbInstance.getAllDatabases();
Iterator<String> dbs = allDatabases.iterator();
while (dbs.hasNext()) {
String db = dbs.next();
// Skip special databases
if (!db.startsWith("_")) {
// Our metadata knows nothing about the db_ prefix
db = db.substring(3);
AccountFolder folder = Collect.getInstance().getInformOnlineState().getAccountFolders().get(db);
if (folder == null) {
// Remove databases that exist locally but for which we have no metadata
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "no metatdata for " + db + " (removing)");
mLocalDbInstance.deleteDatabase("db_" + db);
} else if (isDbLocal(db) && folder.isReplicated() == false) {
// Purge any databases that are local but not on the replication list
try {
ReplicationStatus status = replicate(db, REPLICATE_PUSH);
if (status != null && status.isOk()) {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "final replication push successful, removing " + db);
mLocalDbInstance.deleteDatabase("db_" + db);
}
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "final replication push of " + db + " failed at " + e.toString());
e.printStackTrace();
}
}
}
}
} catch (DbAccessException e) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "database not available " + e.toString());
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unhandled exception " + e.toString());
e.printStackTrace();
}
}
/*
* Evaluate and remove a set of placeholders on the basis of who created it and when it was created
*/
private void removePlaceholders(HashMap<String, JSONObject> placeholders)
{
final String tt = t + "removePlaceholders(): ";
for (Map.Entry<String, JSONObject> entry : placeholders.entrySet()) {
if (entry.getValue().optString("createdBy", null) == null || entry.getValue().optString("dateCreated", null) == null) {
// Remove old style (unowned) placeholders immediately
try {
getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
if (Collect.Log.VERBOSE) Log.v(Collect.LOGTAG, tt + "removed old-style placeholder " + entry.getKey());
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unable to remove old-style placeholder");
e.printStackTrace();
}
} else if (entry.getValue().optString("createdBy").equals(Collect.getInstance().getInformOnlineState().getDeviceId())) {
// Remove placeholders owned by me immediately
try {
getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
if (Collect.Log.VERBOSE) Log.v(Collect.LOGTAG, tt + "removed my placeholder " + entry.getKey());
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unable to remove my placeholder");
e.printStackTrace();
}
} else {
// Remove placeholders owned by other people if they are stale (older than a day)
SimpleDateFormat sdf = new SimpleDateFormat(Generic.DATETIME);
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(entry.getValue().optString("dateCreated")));
if (calendar.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() > TIME_24_HOURS) {
try {
getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
if (Collect.Log.VERBOSE) Log.v(Collect.LOGTAG, tt + "removed stale placeholder " + entry.getKey());
} catch (Exception e) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unable to remove stale placeholder");
e.printStackTrace();
}
}
} catch (ParseException e1) {
if (Collect.Log.ERROR) Log.e(Collect.LOGTAG, tt + "unable to parse dateCreated: " + e1.toString());
e1.printStackTrace();
}
}
}
}
/*
* Trigger a push/pull replication for each locally replicated database
*/
private void synchronizeLocalDBs()
{
final String tt = t + "synchronizeLocalDBs(): ";
// Do we use automatic synchronization?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
// How often should we automatically synchronize databases?
String syncInterval = settings.getString(PreferencesActivity.KEY_SYNCHRONIZATION_INTERVAL, Integer.toString(TIME_FIVE_MINUTES));
if (settings.getBoolean(PreferencesActivity.KEY_AUTOMATIC_SYNCHRONIZATION, true)) {
Set<String> folderSet = Collect.getInstance().getInformOnlineState().getAccountFolders().keySet();
Iterator<String> folderIds = folderSet.iterator();
while (folderIds.hasNext()) {
AccountFolder folder = Collect.getInstance().getInformOnlineState().getAccountFolders().get(folderIds.next());
if (folder.isReplicated()) {
// Determine if this database needs to be replicated
Long lastUpdate = mDbLastReplication.get(folder.getId());
if (lastUpdate == null || System.currentTimeMillis() / 1000 - lastUpdate >= Integer.parseInt(syncInterval)) {
mDbLastReplication.put(folder.getId(), new Long(System.currentTimeMillis() / 1000));
if (Collect.Log.INFO) Log.i(Collect.LOGTAG, tt + "about to begin automatic replication of " + folder.getName());
try {
replicate(folder.getId(), REPLICATE_PULL);
replicate(folder.getId(), REPLICATE_PUSH);
} catch (Exception e) {
if (Collect.Log.WARN) Log.w(Collect.LOGTAG, tt + "problem replicating " + folder.getId() + ": " + e.toString());
e.printStackTrace();
}
} else {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "skipping automatic replication of " + folder.getName() + ": last synchronization too recent");
}
}
}
} else {
if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, tt + "skipping (automatic synchronization disabled)");
}
}
} |
3e183e46053caad0095af950818c245b44e7c0f7 | 1,857 | java | Java | app/src/main/java/com/hills/mcs_02/utils/SqliteTimeUtil.java | Alozavander/CrowdOS_WeSense_CompetitionVersion | bdb69a500df391400fc403898fb05f690c209b2a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hills/mcs_02/utils/SqliteTimeUtil.java | Alozavander/CrowdOS_WeSense_CompetitionVersion | bdb69a500df391400fc403898fb05f690c209b2a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hills/mcs_02/utils/SqliteTimeUtil.java | Alozavander/CrowdOS_WeSense_CompetitionVersion | bdb69a500df391400fc403898fb05f690c209b2a | [
"Apache-2.0"
] | null | null | null | 31.474576 | 80 | 0.529348 | 10,317 | package com.hills.mcs_02.utils;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class SqliteTimeUtil {
public static String[] getStartAndEndTime(){
//get the specific pattern current time.
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
//补足0
String endTime = "";
String startTime = year + "-";
month++;
if (month <10) startTime += "0"+month +"-";
else startTime+= month +"-";
if (day <10) startTime += "0"+day + " ";
else startTime += day + " ";
endTime = startTime;
hour--;
if (hour<10) startTime += "0"+hour+":";
else startTime += hour+":";
hour++;
if (hour<10) endTime += "0"+hour+":";
else endTime += hour+":";
if (minute<10) {
startTime+="0"+minute+":";
endTime+="0"+minute+":";
}
else {
startTime+=minute+":";
endTime+=minute+":";
}
if (second<10) {
endTime+="0"+second;
startTime+="0"+second;
}
else {
startTime+=second;
endTime+=second;
}
return new String[]{startTime,endTime};
}
public static String getCurrentTimeNoSpaceAndColon(){
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat lFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
return lFormat.format(date);
}
}
|
3e183e75ce0b64f14b460b1122ad27cbfbfceb8b | 1,178 | java | Java | core-test/src/main/java/org/openstack4j/api/network/SubnetTests.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 204 | 2016-05-14T12:06:15.000Z | 2022-03-07T09:45:52.000Z | core-test/src/main/java/org/openstack4j/api/network/SubnetTests.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 721 | 2016-05-13T06:51:32.000Z | 2022-01-13T17:44:40.000Z | core-test/src/main/java/org/openstack4j/api/network/SubnetTests.java | octetnest/openstack4j | 9bd9f66d61f17662d70fd22deb65ebd03cf4b353 | [
"Apache-2.0"
] | 291 | 2016-05-13T05:58:13.000Z | 2022-03-07T09:43:36.000Z | 28.731707 | 81 | 0.754669 | 10,318 | package org.openstack4j.api.network;
import static org.testng.Assert.assertEquals;
import org.openstack4j.api.AbstractTest;
import org.openstack4j.model.network.Ipv6AddressMode;
import org.openstack4j.model.network.Ipv6RaMode;
import org.openstack4j.model.network.Subnet;
import org.testng.annotations.Test;
/**
* Tests the Neutron -> Subnet API against the mock webserver and spec based
* json responses
*
* @author Taemin
*/
@Test(suiteName = "subnet")
public class SubnetTests extends AbstractTest {
private static final String JSON_GET_SUBNET = "/network/subnet_ipv6.json";
private static final String SUBNET_NAME = "sub1";
private static final String SUBNET_ID = "3b80198d-4f7b-4f77-9ef5-774d54e17126";
@Test
public void getSubnetIpV6() throws Exception {
respondWith(JSON_GET_SUBNET);
Subnet n = osv3().networking().subnet().get(SUBNET_ID);
server.takeRequest();
assertEquals(n.getName(), SUBNET_NAME);
assertEquals(n.getIpv6AddressMode(), Ipv6AddressMode.DHCPV6_STATEFUL);
assertEquals(n.getIpv6RaMode(), Ipv6RaMode.DHCPV6_STATEFUL);
}
@Override
protected Service service() {
return Service.NETWORK;
}
}
|
3e183e8b988db2703b4e37867a0dcfc1dc311e7a | 2,470 | java | Java | src/java/de/softwareforge/pgpsigner/commands/MailServerCommand.java | hgschmie/pgpsigner | e9f93832962e850b947cbeda54d6b07d06c44ddc | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2015-11-05T12:23:58.000Z | 2015-11-05T12:23:58.000Z | src/java/de/softwareforge/pgpsigner/commands/MailServerCommand.java | hgschmie/pgpsigner | e9f93832962e850b947cbeda54d6b07d06c44ddc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/java/de/softwareforge/pgpsigner/commands/MailServerCommand.java | hgschmie/pgpsigner | e9f93832962e850b947cbeda54d6b07d06c44ddc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 27.853933 | 123 | 0.670835 | 10,319 | package de.softwareforge.pgpsigner.commands;
/*
* Copyright (C) 2007 Henning P. Schmiedehausen
*
* See the NOTICE file distributed with this work for additional
* information
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
import org.apache.commons.cli.Option;
import de.softwareforge.pgpsigner.key.PublicKey;
import de.softwareforge.pgpsigner.util.DisplayHelpers;
/**
* The "mailserver" command.
*
* @author <a href="mailto:dycjh@example.com">Henning P. Schmiedehausen</a>
* @version $Id$
*/
public class MailServerCommand extends AbstractCommand implements Command
{
public String getName()
{
return "mailserver";
}
public String getHelp()
{
return "sets the mailserver for mailing keys";
}
@Override
public Option getCommandLineOption()
{
Option option = super.getCommandLineOption();
option.setArgs(1);
option.setArgName("hostname");
return option;
}
@Override
public boolean prerequisiteInteractiveCommand(final String[] args)
{
if (args.length < 2)
{
System.out.println("Current mail server is " + DisplayHelpers.showNullValue(getContext().getMailServerHost()));
return false;
}
return true;
}
@Override
public void executeInteractiveCommand(final String[] args)
{
String mailServerHost = args[1];
String mailServerPort = "25";
int colonIndex = mailServerHost.indexOf(':');
if (colonIndex > -1) {
mailServerPort = mailServerHost.substring(colonIndex +1);
mailServerHost = mailServerHost.substring(0, colonIndex);
}
getContext().setMailServerHost(mailServerHost);
getContext().setMailServerPort(Integer.parseInt(mailServerPort));
for (PublicKey key : getContext().getPartyRing().getVisibleKeys().values())
{
key.setUploaded(false);
}
}
}
|
3e183eb4255f656699bea2bc9e4165e5eabdd574 | 1,673 | java | Java | plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/marketing/relations/segmentGroup/command/role/AddSegmentGroupRole.java | ArcticReal/eCommerce | ea4c82442acdc9e663571e2d07e1f1ddc844f135 | [
"Apache-2.0"
] | 1 | 2020-09-28T08:23:11.000Z | 2020-09-28T08:23:11.000Z | plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/marketing/relations/segmentGroup/command/role/AddSegmentGroupRole.java | ArcticReal/eCommerce | ea4c82442acdc9e663571e2d07e1f1ddc844f135 | [
"Apache-2.0"
] | null | null | null | plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/marketing/relations/segmentGroup/command/role/AddSegmentGroupRole.java | ArcticReal/eCommerce | ea4c82442acdc9e663571e2d07e1f1ddc844f135 | [
"Apache-2.0"
] | null | null | null | 38.022727 | 104 | 0.841602 | 10,320 | package com.skytala.eCommerce.domain.marketing.relations.segmentGroup.command.role;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.DelegatorFactory;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import com.skytala.eCommerce.domain.marketing.relations.segmentGroup.event.role.SegmentGroupRoleAdded;
import com.skytala.eCommerce.domain.marketing.relations.segmentGroup.mapper.role.SegmentGroupRoleMapper;
import com.skytala.eCommerce.domain.marketing.relations.segmentGroup.model.role.SegmentGroupRole;
import com.skytala.eCommerce.framework.pubsub.Broker;
import com.skytala.eCommerce.framework.pubsub.Command;
import com.skytala.eCommerce.framework.pubsub.Event;
import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
public class AddSegmentGroupRole extends Command {
private SegmentGroupRole elementToBeAdded;
public AddSegmentGroupRole(SegmentGroupRole elementToBeAdded){
this.elementToBeAdded = elementToBeAdded;
}
@Override
public Event execute(){
Delegator delegator = DelegatorFactory.getDelegator("default");
SegmentGroupRole addedElement = null;
boolean success = false;
try {
elementToBeAdded.setRoleTypeId(delegator.getNextSeqId("SegmentGroupRole"));
GenericValue newValue = delegator.makeValue("SegmentGroupRole", elementToBeAdded.mapAttributeField());
addedElement = SegmentGroupRoleMapper.map(delegator.create(newValue));
success = true;
} catch(GenericEntityException e) {
e.printStackTrace();
addedElement = null;
}
Event resultingEvent = new SegmentGroupRoleAdded(addedElement, success);
Broker.instance().publish(resultingEvent);
return resultingEvent;
}
}
|
3e184120d42b660f39b67308b38811958897905e | 2,692 | java | Java | framework/src/main/java/com/quickdevandroid/framework/net/HttpInfoEntity.java | RichCodersAndMe/QuickDevAndroid | 42fb2a4aac7f80683c03cbf1cc082d357626bfdb | [
"MIT"
] | 2 | 2018-04-27T06:41:26.000Z | 2018-08-07T06:53:34.000Z | framework/src/main/java/com/quickdevandroid/framework/net/HttpInfoEntity.java | RichCodersAndMe/QuickDevAndroid | 42fb2a4aac7f80683c03cbf1cc082d357626bfdb | [
"MIT"
] | null | null | null | framework/src/main/java/com/quickdevandroid/framework/net/HttpInfoEntity.java | RichCodersAndMe/QuickDevAndroid | 42fb2a4aac7f80683c03cbf1cc082d357626bfdb | [
"MIT"
] | null | null | null | 31.302326 | 100 | 0.544205 | 10,321 | package com.quickdevandroid.framework.net;
import okhttp3.Headers;
/**
* 承载Http信息实体
* Created by linxiao on 2017/1/19.
*/
public class HttpInfoEntity {
/**Http协议*/
public String protocol;
/**请求方式*/
public String method;
/**请求地址*/
public String url;
/**请求耗时*/
public long tookMills = 0;
/*---------------request params----------------*/
public Headers requestHeaders;
public String requestContentType;
public long requestContentLength;
public String requestBody;
/*---------------response params----------------*/
public Headers responseHeaders;
public int responseCode;
public String responseMessage;
public long responseContentLength;
public String responseBody;
// public void logOut() {
// Logger.LogPrinter logPrinter = Logger.createLogPrinter(Logger.INFO).tag("HttpInfo Logout")
// .appendLine("url: " + url)
// .appendLine("protocol: %s, method: %s", protocol, method)
// .appendLine("request took time: %d ms", tookMills)
// .appendLine("response code: %d, message: %s", responseCode, responseMessage)
// .appendLine("----------request-----------")
// .appendLine("Headers:");
// for (String headerName : requestHeaders.names()) {
// logPrinter.appendLine("%s : %s", headerName, requestHeaders.get(headerName));
// }
// logPrinter.appendLine("Body:")
// .appendLine(requestBody)
// .appendLine("----------response----------")
// .appendLine("Headers:");
// for (String headerName : responseHeaders.names()) {
// logPrinter.appendLine("%s : %s", headerName, responseHeaders.get(headerName));
// }
// logPrinter.appendLine("Body:")
// .appendLine(responseBody);
//
// logPrinter.print();
// }
@Override
public String toString() {
return "HttpInfoEntity{" +
"protocol='" + protocol + '\'' +
", method='" + method + '\'' +
", url='" + url + '\'' +
", tookMills=" + tookMills +
", requestHeaders=" + requestHeaders +
", requestContentType='" + requestContentType + '\'' +
", requestContentLength=" + requestContentLength +
", requestBody='" + requestBody + '\'' +
", responseHeaders=" + responseHeaders +
", responseCode=" + responseCode +
", responseMessage='" + responseMessage + '\'' +
", responseContentLength=" + responseContentLength +
", responseBody='" + responseBody + '\'' +
'}';
}
}
|
3e184179bd4b520a201b68d8ff0042ce957cebc0 | 2,222 | java | Java | day02/src/main/java/eu/marrat/advent2018/day02/Day02.java | mratzer/adventofcode2018 | 2a01d923531fdb198e44c09b16a442767b78e55b | [
"Apache-2.0"
] | null | null | null | day02/src/main/java/eu/marrat/advent2018/day02/Day02.java | mratzer/adventofcode2018 | 2a01d923531fdb198e44c09b16a442767b78e55b | [
"Apache-2.0"
] | null | null | null | day02/src/main/java/eu/marrat/advent2018/day02/Day02.java | mratzer/adventofcode2018 | 2a01d923531fdb198e44c09b16a442767b78e55b | [
"Apache-2.0"
] | null | null | null | 23.145833 | 75 | 0.687219 | 10,322 | /*
* Copyright 2018 Markus Ratzer
*
* 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 eu.marrat.advent2018.day02;
import eu.marrat.advent2018.common.ClasspathFileUtils;
import org.apache.commons.text.similarity.LevenshteinDistance;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Day02 {
public static void main(String[] args) {
List<Id> ids = ClasspathFileUtils.getLines("input")
.map(Id::new)
.filter(Id::hasAnything)
.collect(Collectors.toList());
long twos = ids.stream()
.filter(Id::hasTwo)
.count();
long threes = ids.stream()
.filter(Id::hasThree)
.count();
System.out.println(twos * threes);
Set<Set<String>> stringGroupsWithDistanceOne = new HashSet<>();
for (Id id1 : ids) {
for (Id id2 : ids) {
if (LevenshteinDistance.getDefaultInstance()
.apply(id1.string, id2.string) == 1) {
stringGroupsWithDistanceOne.add(Set.of(id1.string, id2.string));
}
}
}
System.out.println(stringGroupsWithDistanceOne);
}
static class Id {
private final String string;
private final boolean hasTwo;
private final boolean hasThree;
Id(String string) {
Set<Long> twosAndThrees = string.chars()
.boxed()
.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
.values().stream()
.filter(l -> l == 2 || l == 3)
.collect(Collectors.toSet());
this.string = string;
hasTwo = twosAndThrees.contains(2L);
hasThree = twosAndThrees.contains(3L);
}
boolean hasTwo() {
return hasTwo;
}
boolean hasThree() {
return hasThree;
}
boolean hasAnything() {
return hasTwo || hasThree;
}
}
}
|
3e1841e1811c112f43a4d4845f113cb4ad1d820a | 203 | java | Java | Module_1-Basics/m1-w3d4-polymorphism-lecture/src/main/java/com/techelevator/farm/Tractor.java | treytomlin/TechElevatorExercises | b00c6f15ecc93100a12bb70c0687f8e09fa085e3 | [
"MIT"
] | null | null | null | Module_1-Basics/m1-w3d4-polymorphism-lecture/src/main/java/com/techelevator/farm/Tractor.java | treytomlin/TechElevatorExercises | b00c6f15ecc93100a12bb70c0687f8e09fa085e3 | [
"MIT"
] | null | null | null | Module_1-Basics/m1-w3d4-polymorphism-lecture/src/main/java/com/techelevator/farm/Tractor.java | treytomlin/TechElevatorExercises | b00c6f15ecc93100a12bb70c0687f8e09fa085e3 | [
"MIT"
] | null | null | null | 11.941176 | 42 | 0.699507 | 10,323 | package com.techelevator.farm;
public class Tractor implements Singable {
@Override
public String getName() {
return "Tractor";
}
@Override
public String getSound() {
return "Rumble";
}
}
|
3e184347251a8cc7b65beeec3f6f1212b2323add | 1,157 | java | Java | mantiss-tests/src/test/java/ru/stqa/pft/mantis/appmanager/RegistrationHelper.java | Salarus14488/java_ptf | eea3f46876923792c1653a84cfb16980f825fcd9 | [
"Apache-2.0"
] | null | null | null | mantiss-tests/src/test/java/ru/stqa/pft/mantis/appmanager/RegistrationHelper.java | Salarus14488/java_ptf | eea3f46876923792c1653a84cfb16980f825fcd9 | [
"Apache-2.0"
] | null | null | null | mantiss-tests/src/test/java/ru/stqa/pft/mantis/appmanager/RegistrationHelper.java | Salarus14488/java_ptf | eea3f46876923792c1653a84cfb16980f825fcd9 | [
"Apache-2.0"
] | null | null | null | 27.547619 | 66 | 0.638721 | 10,324 | package ru.stqa.pft.mantis.appmanager;
import org.openqa.selenium.By;
public class RegistrationHelper extends HelperBase {
public RegistrationHelper(ApplicationManager app) {
super(app);
}
public void start (String username, String email) {
wd.get(app.getProperty("web.baseUrl") + "/signup_page.php");
type(By.name("username"), username);
type(By.name("email"), email);
click(By.cssSelector("input[value='Signup']"));
}
public void finish(String confirmationLink, String password) {
wd.get(confirmationLink);
type(By.name("password"), password);
type(By.name("password_confirm"), password);
click(By.cssSelector("input[value='Update User']"));
}
public void login (String username, String password) {
wd.get(app.getProperty("web.baseUrl"));
type(By.name("username"), username);
type(By.name("password"), password);
click(By.cssSelector("input[value='Login']"));
}
public void goToManage() {
click(By.linkText("Manage"));
}
public void goToManageUsers() {
click(By.linkText("Manage Users"));
}
}
|
3e184366dd784e35b375996f1328f844572688dd | 10,905 | java | Java | src/main/java/com/jfireframework/jfireel/expression/node/impl/DynamicCompileMethodNode.java | linbin-eric/jfireEL | b38116452fc328b46c91f8d2a3eca997f18431c5 | [
"AFL-3.0"
] | null | null | null | src/main/java/com/jfireframework/jfireel/expression/node/impl/DynamicCompileMethodNode.java | linbin-eric/jfireEL | b38116452fc328b46c91f8d2a3eca997f18431c5 | [
"AFL-3.0"
] | 2 | 2021-12-10T01:31:16.000Z | 2021-12-14T21:39:48.000Z | src/main/java/com/jfireframework/jfireel/expression/node/impl/DynamicCompileMethodNode.java | linbin-eric/jfireEL | b38116452fc328b46c91f8d2a3eca997f18431c5 | [
"AFL-3.0"
] | null | null | null | 40.842697 | 171 | 0.437047 | 10,325 | package com.jfireframework.jfireel.expression.node.impl;
import com.jfireframework.baseutil.smc.SmcHelper;
import com.jfireframework.baseutil.smc.compiler.CompileHelper;
import com.jfireframework.baseutil.smc.model.ClassModel;
import com.jfireframework.baseutil.smc.model.MethodModel;
import com.jfireframework.baseutil.smc.model.MethodModel.AccessLevel;
import com.jfireframework.jfireel.expression.node.CalculateNode;
import com.jfireframework.jfireel.expression.node.MethodNode;
import com.jfireframework.jfireel.expression.token.Token;
import com.jfireframework.jfireel.expression.token.TokenType;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class DynamicCompileMethodNode implements MethodNode
{
public static interface Invoker
{
Object invoke(Object host, Object[] params);
}
private static final CompileHelper COMPILER = new CompileHelper();
private static final AtomicInteger counter = new AtomicInteger(0);
private final CalculateNode beanNode;
private final String methodName;
private volatile Invoker invoker;
private volatile Class<?> beanType;
protected boolean recognizeEveryTime = true;
private CalculateNode[] argsNodes;
private ConvertType[] convertTypes;
private Token type;
public DynamicCompileMethodNode(String literals, CalculateNode beanNode)
{
methodName = literals;
type = Token.METHOD;
this.beanNode = beanNode;
}
@Override
public Object calculate(Map<String, Object> variables)
{
Object value = beanNode.calculate(variables);
if (value == null)
{
return value;
}
Object[] args = new Object[argsNodes.length];
try
{
for (int i = 0; i < args.length; i++)
{
args[i] = argsNodes[i].calculate(variables);
}
Invoker invoke = getMethod(value, args);
MethodNodeUtil.convertArgs(args, convertTypes);
return invoke.invoke(value, args);
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public TokenType type()
{
return type;
}
private Invoker getMethod(Object value, Object[] args)
{
if (recognizeEveryTime)
{
Invoker invoker = this.invoker;
if (invoker == null || beanType.isAssignableFrom(value.getClass()) == false)
{
synchronized (this)
{
if ((invoker = this.invoker) == null || beanType.isAssignableFrom(value.getClass()) == false)
{
nextmethod:
//
for (Method each : value.getClass().getMethods())
{
if (each.getName().equals(methodName) && each.getParameterTypes().length == args.length)
{
Class<?>[] parameterTypes = each.getParameterTypes();
for (int i = 0; i < args.length; i++)
{
if (parameterTypes[i].isPrimitive())
{
if (args[i] == null || MethodNodeUtil.isWrapType(parameterTypes[i], args[i].getClass()) == false)
{
continue nextmethod;
}
}
else
{
if (args[i] != null && parameterTypes[i].isAssignableFrom(args[i].getClass()) == false)
{
continue nextmethod;
}
}
}
convertTypes = MethodNodeUtil.buildConvertTypes(parameterTypes);
beanType = value.getClass();
invoker = buildInvoker(args, each, parameterTypes);
this.invoker = invoker;
return invoker;
}
}
throw new NullPointerException();
}
}
}
return invoker;
}
else
{
if (invoker == null)
{
synchronized (this)
{
if (invoker == null)
{
Class<?> ckass = value.getClass();
nextmethod:
//
for (Method each : ckass.getMethods())
{
if (each.getName().equals(methodName) && each.getParameterTypes().length == args.length)
{
Class<?>[] parameterTypes = each.getParameterTypes();
for (int i = 0; i < args.length; i++)
{
if (parameterTypes[i].isPrimitive())
{
if (args[i] == null || MethodNodeUtil.isWrapType(parameterTypes[i], args[i].getClass()) == false)
{
continue nextmethod;
}
}
else if (args[i] != null && parameterTypes[i].isAssignableFrom(args[i].getClass()) == false)
{
continue nextmethod;
}
}
convertTypes = MethodNodeUtil.buildConvertTypes(parameterTypes);
each.setAccessible(true);
invoker = buildInvoker(args, each, parameterTypes);
return invoker;
}
}
throw new NullPointerException();
}
}
}
return invoker;
}
}
private Invoker buildInvoker(Object[] args, Method method, Class<?>[] parameterTypes)
{
try
{
ClassModel classModel = new ClassModel("Invoke_" + method.getName() + "_" + counter.incrementAndGet(), Object.class, Invoker.class);
MethodModel methodModel = new MethodModel(classModel);
methodModel.setAccessLevel(AccessLevel.PUBLIC);
methodModel.setMethodName("invoke");
methodModel.setParamterTypes(Object.class, Object[].class);
methodModel.setReturnType(Object.class);
StringBuilder body = new StringBuilder("{ return ((" + SmcHelper.getReferenceName(method.getDeclaringClass(), classModel) + ")$0)." + method.getName() + "(");
for (int i = 0; i < args.length; i++)
{
switch (convertTypes[i])
{
case INT:
body.append("(java.lang.Integer)$1[").append(i).append(']').append(',');
break;
case LONG:
body.append("(java.lang.Long)$1[").append(i).append(']').append(',');
break;
case SHORT:
body.append("(java.lang.Short)$1[").append(i).append(']').append(',');
break;
case FLOAT:
body.append("(java.lang.Float)$1[").append(i).append(']').append(',');
break;
case DOUBLE:
body.append("(java.lang.Double)$1[").append(i).append(']').append(',');
break;
case BYTE:
body.append("(java.lang.Byte)$1[").append(i).append(']').append(',');
break;
case BOOLEAN:
body.append("(java.lang.Boolean)$1[").append(i).append(']').append(',');
break;
case CHARACTER:
body.append("(java.lang.Character)$1[").append(i).append(']').append(',');
break;
case OTHER:
body.append('(').append(SmcHelper.getReferenceName(parameterTypes[i], classModel)).append(')').append("$1[").append(i).append(']').append(',');
break;
default:
break;
}
}
if (body.charAt(body.length() - 1) == ',')
{
body.setLength(body.length() - 1);
}
body.append(");}");
methodModel.setBody(body.toString());
classModel.putMethodModel(methodModel);
Class<?> compile = COMPILER.compile(classModel);
return (Invoker) compile.newInstance();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public void setArgsNodes(CalculateNode[] argsNodes)
{
this.argsNodes = argsNodes;
type = Token.METHOD_RESULT;
}
@Override
public void check()
{
// TODO Auto-generated method stub
}
@Override
public String literals()
{
StringBuilder cache = new StringBuilder();
cache.append(beanNode.literals()).append('.').append(methodName).append('(');
if (argsNodes != null)
{
for (CalculateNode each : argsNodes)
{
cache.append(each.literals()).append(',');
}
if (cache.charAt(cache.length() - 1) == ',')
{
cache.setLength(cache.length() - 1);
}
}
cache.append(')');
return cache.toString();
}
@Override
public String toString()
{
return literals();
}
}
|
3e184558e3c35a9682b850857d546826c82c1186 | 751 | java | Java | app/OrganizerHut/app/src/main/java/by/hut/flat/calendar/dialog/floating/select/cleanings/CleaningList.java | syrel/hut.by-Organizer | aa1c7dce4a962330938cc65ae4ceafb5b467e7ca | [
"MIT"
] | null | null | null | app/OrganizerHut/app/src/main/java/by/hut/flat/calendar/dialog/floating/select/cleanings/CleaningList.java | syrel/hut.by-Organizer | aa1c7dce4a962330938cc65ae4ceafb5b467e7ca | [
"MIT"
] | null | null | null | app/OrganizerHut/app/src/main/java/by/hut/flat/calendar/dialog/floating/select/cleanings/CleaningList.java | syrel/hut.by-Organizer | aa1c7dce4a962330938cc65ae4ceafb5b467e7ca | [
"MIT"
] | null | null | null | 28.884615 | 134 | 0.77763 | 10,326 | package by.hut.flat.calendar.dialog.floating.select.cleanings;
import android.content.Context;
import by.hut.flat.calendar.R;
import by.hut.flat.calendar.utils.Utils;
import by.hut.flat.calendar.widget.list.simple.List;
public class CleaningList extends List{
private Context context;
public CleaningList(Context context) {
super(context);
this.context = context;
this.initList();
}
@Override
protected void initList() {
CleaningEntry add = new CleaningEntry(context,Utils.getString(context, R.string.menu_flat_cleaning_add),R.id.cleaning_add);
CleaningEntry delete = new CleaningEntry(context,Utils.getString(context, R.string.menu_flat_cleaning_delete),R.id.cleaning_delete);
delete.hideLine();
add(add);
add(delete);
}
}
|
3e18497d590c38b7d3aad2fdd530948b223eaada | 5,860 | java | Java | oak-security-spi/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/token/CompositeTokenProviderTest.java | stjepanB/jackrabbit-oak | c3a6624bc1d06b1a2166e908758585c5d3ef1f35 | [
"Apache-2.0"
] | 288 | 2015-01-11T04:09:03.000Z | 2022-03-28T22:20:09.000Z | oak-security-spi/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/token/CompositeTokenProviderTest.java | stjepanB/jackrabbit-oak | c3a6624bc1d06b1a2166e908758585c5d3ef1f35 | [
"Apache-2.0"
] | 154 | 2016-10-30T11:31:04.000Z | 2022-03-31T14:20:52.000Z | oak-security-spi/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/token/CompositeTokenProviderTest.java | stjepanB/jackrabbit-oak | c3a6624bc1d06b1a2166e908758585c5d3ef1f35 | [
"Apache-2.0"
] | 405 | 2015-01-15T16:15:56.000Z | 2022-03-24T08:27:08.000Z | 32.921348 | 124 | 0.680375 | 10,327 | /*
* 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.jackrabbit.oak.spi.security.authentication.token;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Before;
import org.junit.Test;
import javax.jcr.Credentials;
import javax.jcr.GuestCredentials;
import javax.jcr.SimpleCredentials;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CompositeTokenProviderTest {
private static final String TOKEN = "t";
private static final String USERID = "userId";
private TokenInfo info;
private TokenProvider composite;
@Before
public void before() {
info = mock(TokenInfo.class);
when(info.getToken()).thenReturn(TOKEN);
TokenProvider tp1 = mock(TokenProvider.class);
TokenProvider tp2 = new TestTokenProvider();
composite = CompositeTokenProvider.newInstance(tp1, tp2);
}
@Test
public void testNullProvider() {
TokenProvider tp = CompositeTokenProvider.newInstance();
assertSame(tp, CompositeTokenProvider.newInstance(ImmutableList.<TokenProvider>of()));
Credentials creds = new Credentials() {};
assertFalse(tp.doCreateToken(null));
assertFalse(tp.doCreateToken(creds));
assertNull(tp.createToken(null, null));
assertNull(tp.createToken(USERID, ImmutableMap.<String, String>of()));
assertNull(tp.createToken(null));
assertNull(tp.createToken(creds));
assertNull(tp.getTokenInfo(null));
assertNull(tp.getTokenInfo("anyString"));
}
@Test
public void testSingleProvider() {
TokenProvider base = mock(TokenProvider.class);
TokenProvider tp = CompositeTokenProvider.newInstance(base);
assertSame(base, tp);
assertSame(base, CompositeTokenProvider.newInstance(ImmutableList.of(base)));
}
@Test
public void testCreateCompositeProvider() {
assertTrue(composite instanceof CompositeTokenProvider);
}
@Test
public void testCreateCompositeProviderFromList() {
TokenProvider base = mock(TokenProvider.class);
TokenProvider tp = CompositeTokenProvider.newInstance(ImmutableList.of(base, base));
assertTrue(tp instanceof CompositeTokenProvider);
}
@Test
public void testDoCreateToken() {
assertTrue(composite.doCreateToken(new SimpleCredentials(USERID, new char[0])));
assertFalse(composite.doCreateToken(new GuestCredentials()));
assertFalse(composite.doCreateToken(new Credentials() {}));
}
@Test
public void testCreateTokenFromCredentials() {
assertSame(info, composite.createToken(new SimpleCredentials(USERID, new char[0])));
assertNull(composite.createToken(new GuestCredentials()));
assertNull(composite.createToken(new Credentials() {
}));
}
@Test
public void testCreateTokenFromId() {
assertSame(info, composite.createToken(USERID, ImmutableMap.of()));
}
@Test
public void testCreateTokenFromUnknownId() {
assertNull(composite.createToken("unknown", ImmutableMap.of()));
}
@Test
public void testCreateTokenFromIdFirstWins() {
TokenInfo ti = mock(TokenInfo.class);
TokenProvider tp1 = when(mock(TokenProvider.class).createToken(USERID, ImmutableMap.of())).thenReturn(ti).getMock();
TokenProvider tp2 = new TestTokenProvider();
TokenProvider ctp = CompositeTokenProvider.newInstance(tp1, tp2);
assertSame(ti, ctp.createToken(USERID, ImmutableMap.of()));
}
@Test
public void testGetTokenInfo() {
assertSame(info, composite.getTokenInfo(TOKEN));
assertNull(composite.getTokenInfo("any"));
}
private final class TestTokenProvider implements TokenProvider {
@Override
public boolean doCreateToken(@NotNull Credentials credentials) {
return credentials instanceof SimpleCredentials;
}
@Nullable
@Override
public TokenInfo createToken(@NotNull Credentials credentials) {
if (credentials instanceof SimpleCredentials) {
return info;
} else {
return null;
}
}
@Nullable
@Override
public TokenInfo createToken(@NotNull String userId, @NotNull Map<String, ?> attributes) {
if (USERID.equals(userId)) {
return info;
} else {
return null;
}
}
@Nullable
@Override
public TokenInfo getTokenInfo(@NotNull String token) {
if (TOKEN.equals(token)) {
return info;
} else {
return null;
}
}
};
}
|
3e184b0d03321b0cfb9b3b140dd3d95a5c508d8c | 150 | java | Java | src/main/java/edu/columbia/main/language_id/com/detectLanguage/responses/DetectResponse.java | e-spaulding/Babler | 5f99cb180ba9ed0f8c79f3ae3efdf81441527a84 | [
"Apache-2.0"
] | 26 | 2017-05-31T19:14:14.000Z | 2021-03-26T08:28:08.000Z | src/main/java/edu/columbia/main/language_id/com/detectLanguage/responses/DetectResponse.java | e-spaulding/Babler | 5f99cb180ba9ed0f8c79f3ae3efdf81441527a84 | [
"Apache-2.0"
] | 5 | 2021-03-14T04:05:50.000Z | 2021-12-10T07:42:27.000Z | src/main/java/edu/columbia/main/language_id/com/detectLanguage/responses/DetectResponse.java | e-spaulding/Babler | 5f99cb180ba9ed0f8c79f3ae3efdf81441527a84 | [
"Apache-2.0"
] | 14 | 2017-05-29T16:15:57.000Z | 2021-04-20T01:26:56.000Z | 25 | 67 | 0.82 | 10,328 | package edu.columbia.main.language_id.com.detectLanguage.responses;
public class DetectResponse extends Response {
public DetectionsData data;
}
|
3e184b35b9be76ba3ef63cc7d9eb310d8d776f2c | 1,743 | java | Java | Mage.Sets/src/mage/cards/s/SavvyHunter.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/s/SavvyHunter.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/s/SavvyHunter.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 32.886792 | 113 | 0.735513 | 10,329 | package mage.cards.s;
import mage.MageInt;
import mage.abilities.common.AttacksOrBlocksTriggeredAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.common.FilterControlledPermanent;
import mage.game.permanent.token.FoodToken;
import mage.target.common.TargetControlledPermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class SavvyHunter extends CardImpl {
private static final FilterControlledPermanent filter = new FilterControlledPermanent(SubType.FOOD, "Foods");
public SavvyHunter(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{G}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Whenever Savvy Hunter attacks or blocks, create a Food token.
this.addAbility(new AttacksOrBlocksTriggeredAbility(new CreateTokenEffect(new FoodToken()), false));
// Sacrifice two Foods: Draw a card.
this.addAbility(new SimpleActivatedAbility(
new DrawCardSourceControllerEffect(1),
new SacrificeTargetCost(new TargetControlledPermanent(2, filter))
));
}
private SavvyHunter(final SavvyHunter card) {
super(card);
}
@Override
public SavvyHunter copy() {
return new SavvyHunter(this);
}
}
|
3e184bdc51d178994ec54732093ab058c7203cfc | 2,377 | java | Java | modules/base/diff-impl/src/main/java/com/intellij/diff/actions/NavigationContextChecker.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 634 | 2015-01-01T19:14:25.000Z | 2022-03-22T11:42:50.000Z | modules/base/diff-impl/src/main/java/com/intellij/diff/actions/NavigationContextChecker.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 410 | 2015-01-19T09:57:51.000Z | 2022-03-22T16:24:59.000Z | modules/base/diff-impl/src/main/java/com/intellij/diff/actions/NavigationContextChecker.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 50 | 2015-03-10T04:14:49.000Z | 2022-03-22T07:08:45.000Z | 36.015152 | 123 | 0.720236 | 10,330 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.diff.actions;
import com.intellij.openapi.diff.DiffNavigationContext;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import javax.annotation.Nonnull;
import java.util.Iterator;
public class NavigationContextChecker {
@Nonnull
private final Iterator<Pair<Integer, CharSequence>> myChangedLinesIterator;
@Nonnull
private final DiffNavigationContext myContext;
public NavigationContextChecker(@Nonnull Iterator<Pair<Integer, CharSequence>> changedLinesIterator,
@Nonnull DiffNavigationContext context) {
myChangedLinesIterator = changedLinesIterator;
myContext = context;
}
public int contextMatchCheck() {
// we ignore spaces.. at least at start/end, since some version controls could ignore their changes when doing annotate
Iterator<? extends CharSequence> iterator = myContext.getPreviousLinesIterable().iterator();
if (iterator.hasNext()) {
CharSequence contextLine = iterator.next();
while (myChangedLinesIterator.hasNext()) {
Pair<Integer, ? extends CharSequence> pair = myChangedLinesIterator.next();
if (StringUtil.equalsTrimWhitespaces(pair.getSecond(), contextLine)) {
if (!iterator.hasNext()) break;
contextLine = iterator.next();
}
}
}
if (iterator.hasNext()) return -1;
if (!myChangedLinesIterator.hasNext()) return -1;
CharSequence targetLine = myContext.getTargetString();
while (myChangedLinesIterator.hasNext()) {
Pair<Integer, ? extends CharSequence> pair = myChangedLinesIterator.next();
if (StringUtil.equalsTrimWhitespaces(pair.getSecond(), targetLine)) {
return pair.getFirst();
}
}
return -1;
}
}
|
3e184cec4a9144c92d56c821b8fa0905dcb07816 | 447 | java | Java | src/com/tspeiz/modules/common/dao/release2/IDoctorSceneEwmDao.java | guoxiangran/main | 3c9b80611230f4f0c85070be0394286d7afd65b5 | [
"MIT"
] | null | null | null | src/com/tspeiz/modules/common/dao/release2/IDoctorSceneEwmDao.java | guoxiangran/main | 3c9b80611230f4f0c85070be0394286d7afd65b5 | [
"MIT"
] | null | null | null | src/com/tspeiz/modules/common/dao/release2/IDoctorSceneEwmDao.java | guoxiangran/main | 3c9b80611230f4f0c85070be0394286d7afd65b5 | [
"MIT"
] | null | null | null | 37.25 | 113 | 0.847875 | 10,331 | package com.tspeiz.modules.common.dao.release2;
import java.util.List;
import com.tspeiz.modules.common.dao.base.BaseDao;
import com.tspeiz.modules.common.entity.release2.DoctorSceneEwm;
public interface IDoctorSceneEwmDao extends BaseDao<DoctorSceneEwm>{
public DoctorSceneEwm queryDoctorSceneEwmByDoctorId(Integer doctorId);
public List<DoctorSceneEwm> queryDoctorSceneEwms_doc(String hosid,String depid,String startDate,String endDate);
}
|
3e184dac8ca5350e9ff40a33a7bce48db97a505d | 1,031 | java | Java | soluciones/MundoAnimal-DCR/src/es/daniel/models/Animal.java | AlvaroMingoCastillo/Programacion-05-Ejercicios-2021-2022 | cf7d34085ccd3fc84cd42eab875f0ba7be942b11 | [
"MIT"
] | 6 | 2022-02-14T09:15:28.000Z | 2022-03-07T19:59:12.000Z | soluciones/MundoAnimal-DCR/src/es/daniel/models/Animal.java | AlvaroMingoCastillo/Programacion-05-Ejercicios-2021-2022 | cf7d34085ccd3fc84cd42eab875f0ba7be942b11 | [
"MIT"
] | 1 | 2022-02-21T17:26:55.000Z | 2022-02-21T17:26:55.000Z | soluciones/MundoAnimal-DCR/src/es/daniel/models/Animal.java | AlvaroMingoCastillo/Programacion-05-Ejercicios-2021-2022 | cf7d34085ccd3fc84cd42eab875f0ba7be942b11 | [
"MIT"
] | 7 | 2022-02-18T14:34:52.000Z | 2022-03-07T20:43:35.000Z | 19.45283 | 57 | 0.588749 | 10,332 | package es.daniel.models;
public abstract class Animal {
private String name;
private String raza;
private float peso;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRaza() {
return raza;
}
public void setRaza(String raza) {
this.raza = raza;
}
public float getPeso() {
return peso;
}
public void setPeso(float peso) {
this.peso = peso;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void vacunar(){
System.out.println("Animal lo estan vacunando.");
}
public void comer(){
System.out.println("El animal esta comiendo");
}
public void dormir(){
System.out.println("El animal esta durmiendo.");
}
public abstract void hacerRuido();
public abstract boolean hacerCaso();
}
|
3e184dd6da21ddd250f3d0233a56e3d980bfbc02 | 5,259 | java | Java | src/main/java/com/jsh/erp/controller/AccountController.java | wanglaozhe/erp | 617684a78ac15a8cef89ed7bfe497088bfa48b58 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jsh/erp/controller/AccountController.java | wanglaozhe/erp | 617684a78ac15a8cef89ed7bfe497088bfa48b58 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jsh/erp/controller/AccountController.java | wanglaozhe/erp | 617684a78ac15a8cef89ed7bfe497088bfa48b58 | [
"Apache-2.0"
] | null | null | null | 37.035211 | 175 | 0.568739 | 10,333 | package com.jsh.erp.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.datasource.entities.Account;
import com.jsh.erp.datasource.vo.AccountVo4InOutList;
import com.jsh.erp.service.account.AccountService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.ErpInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;
/**
* @author jishenghua 75271*8920
*/
@RestController
@RequestMapping(value = "/account")
public class AccountController {
private Logger logger = LoggerFactory.getLogger(AccountController.class);
@Resource
private AccountService accountService;
/**
* 查找结算账户信息-下拉框
* @param request
* @return
*/
@GetMapping(value = "/findBySelect")
public String findBySelect(HttpServletRequest request) {
String res = null;
try {
List<Account> dataList = accountService.findBySelect();
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (Account account : dataList) {
JSONObject item = new JSONObject();
item.put("Id", account.getId());
//结算账户名称
item.put("AccountName", account.getName());
dataArray.add(item);
}
}
res = dataArray.toJSONString();
} catch(Exception e){
e.printStackTrace();
res = "获取数据失败";
}
return res;
}
/**
* 获取所有结算账户
* @param request
* @return
*/
@GetMapping(value = "/getAccount")
public BaseResponseInfo getAccount(HttpServletRequest request) {
BaseResponseInfo res = new BaseResponseInfo();
Map<String, Object> map = new HashMap<String, Object>();
try {
List<Account> accountList = accountService.getAccount();
map.put("accountList", accountList);
res.code = 200;
res.data = map;
} catch(Exception e){
e.printStackTrace();
res.code = 500;
res.data = "获取数据失败";
}
return res;
}
/**
* 账户流水信息
* @param currentPage
* @param pageSize
* @param accountId
* @param initialAmount
* @param request
* @return
*/
@GetMapping(value = "/findAccountInOutList")
public BaseResponseInfo findAccountInOutList(@RequestParam("currentPage") Integer currentPage,
@RequestParam("pageSize") Integer pageSize,
@RequestParam("accountId") Long accountId,
@RequestParam("initialAmount") Double initialAmount,
HttpServletRequest request) {
BaseResponseInfo res = new BaseResponseInfo();
Map<String, Object> map = new HashMap<String, Object>();
try {
List<AccountVo4InOutList> dataList = accountService.findAccountInOutList(accountId, (currentPage-1)*pageSize, pageSize);
int total = accountService.findAccountInOutListCount(accountId);
map.put("total", total);
//存放数据json数组
JSONArray dataArray = new JSONArray();
if (null != dataList) {
for (AccountVo4InOutList aEx : dataList) {
String timeStr = aEx.getOperTime().toString();
Double balance = accountService.getAccountSum(accountId, timeStr, "date") + accountService.getAccountSumByHead(accountId, timeStr, "date")
+ accountService.getAccountSumByDetail(accountId, timeStr, "date") + accountService.getManyAccountSum(accountId, timeStr, "date") + initialAmount;
aEx.setBalance(balance);
dataArray.add(aEx);
}
}
map.put("rows", dataArray);
res.code = 200;
res.data = map;
} catch(Exception e){
e.printStackTrace();
res.code = 500;
res.data = "获取数据失败";
}
return res;
}
@PostMapping(value = "/updateAmountIsDefault")
public String updateAmountIsDefault(@RequestParam("isDefault") Boolean isDefault,
@RequestParam("accountId") Long accountId,
HttpServletRequest request) {
Map<String, Object> objectMap = new HashMap<String, Object>();
int res = accountService.updateAmountIsDefault(isDefault, accountId);
if(res > 0) {
return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
} else {
return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
}
}
}
|
3e184e7267ddeeaeef622dff7841617b8f83f24e | 7,075 | java | Java | SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/android/sdk/internal/api/FragmentAPI.java | sensorsdata/sa-sdk-tv | 202414bb01e3580ecac1272ca669a22adb39f39e | [
"Apache-2.0"
] | 1,103 | 2015-11-06T06:09:43.000Z | 2022-03-30T11:41:39.000Z | SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/android/sdk/internal/api/FragmentAPI.java | MrZJ/sa-sdk-android | 37530296bb25059d8036275bb0936757f6e88ba1 | [
"Apache-2.0"
] | 93 | 2016-06-17T03:31:52.000Z | 2022-03-15T07:05:10.000Z | SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/android/sdk/internal/api/FragmentAPI.java | MrZJ/sa-sdk-android | 37530296bb25059d8036275bb0936757f6e88ba1 | [
"Apache-2.0"
] | 381 | 2016-03-17T07:22:36.000Z | 2022-03-30T11:41:32.000Z | 33.215962 | 126 | 0.584876 | 10,334 | /*
* Created by dengshiwei on 2020/11/26.
* Copyright 2015-2021 Sensors Data 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.sensorsdata.analytics.android.sdk.internal.api;
import android.text.TextUtils;
import com.sensorsdata.analytics.android.sdk.SALog;
import com.sensorsdata.analytics.android.sdk.SensorsDataAPI;
import com.sensorsdata.analytics.android.sdk.SensorsDataIgnoreTrackAppViewScreen;
import com.sensorsdata.analytics.android.sdk.SensorsDataIgnoreTrackAppViewScreenAndAppClick;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public class FragmentAPI implements IFragmentAPI {
private static final String TAG = "FragmentAPI";
/* $AppViewScreen 事件是否支持 Fragment*/
private boolean mTrackFragmentAppViewScreen;
private Set<Integer> mAutoTrackFragments;
private Set<Integer> mAutoTrackIgnoredFragments;
public FragmentAPI() {
}
@Override
public void trackFragmentAppViewScreen() {
this.mTrackFragmentAppViewScreen = true;
}
@Override
public boolean isTrackFragmentAppViewScreenEnabled() {
return this.mTrackFragmentAppViewScreen;
}
@Override
public void enableAutoTrackFragment(Class<?> fragment) {
try {
if (fragment == null) {
return;
}
if (mAutoTrackFragments == null) {
mAutoTrackFragments = new CopyOnWriteArraySet<>();
}
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
mAutoTrackFragments.add(canonicalName.hashCode());
}
} catch (Exception ex) {
SALog.printStackTrace(ex);
}
}
@Override
public void enableAutoTrackFragments(List<Class<?>> fragmentsList) {
if (fragmentsList == null || fragmentsList.size() == 0) {
return;
}
if (mAutoTrackFragments == null) {
mAutoTrackFragments = new CopyOnWriteArraySet<>();
}
try {
String canonicalName;
for (Class fragment : fragmentsList) {
canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
mAutoTrackFragments.add(canonicalName.hashCode());
}
}
} catch (Exception e) {
SALog.printStackTrace(e);
}
}
@Override
public boolean isFragmentAutoTrackAppViewScreen(Class<?> fragment) {
if (fragment == null) {
return false;
}
try {
if (SensorsDataAPI.sharedInstance().isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType.APP_VIEW_SCREEN)
|| !mTrackFragmentAppViewScreen) {
return false;
}
if (mAutoTrackFragments != null && mAutoTrackFragments.size() > 0) {
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
return mAutoTrackFragments.contains(canonicalName.hashCode());
}
}
if (fragment.getAnnotation(SensorsDataIgnoreTrackAppViewScreen.class) != null) {
return false;
}
if (fragment.getAnnotation(SensorsDataIgnoreTrackAppViewScreenAndAppClick.class) != null) {
return false;
}
if (mAutoTrackIgnoredFragments != null && mAutoTrackIgnoredFragments.size() > 0) {
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
return !mAutoTrackIgnoredFragments.contains(canonicalName.hashCode());
}
}
} catch (Exception e) {
SALog.printStackTrace(e);
}
return true;
}
@Override
public void ignoreAutoTrackFragments(List<Class<?>> fragmentList) {
try {
if (fragmentList == null || fragmentList.size() == 0) {
return;
}
if (mAutoTrackIgnoredFragments == null) {
mAutoTrackIgnoredFragments = new CopyOnWriteArraySet<>();
}
for (Class<?> fragment : fragmentList) {
if (fragment != null) {
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
mAutoTrackIgnoredFragments.add(canonicalName.hashCode());
}
}
}
} catch (Exception ex) {
SALog.printStackTrace(ex);
}
}
@Override
public void ignoreAutoTrackFragment(Class<?> fragment) {
try {
if (fragment == null) {
return;
}
if (mAutoTrackIgnoredFragments == null) {
mAutoTrackIgnoredFragments = new CopyOnWriteArraySet<>();
}
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
mAutoTrackIgnoredFragments.add(canonicalName.hashCode());
}
} catch (Exception ex) {
SALog.printStackTrace(ex);
}
}
@Override
public void resumeIgnoredAutoTrackFragments(List<Class<?>> fragmentList) {
try {
if (fragmentList == null || fragmentList.size() == 0 ||
mAutoTrackIgnoredFragments == null) {
return;
}
for (Class fragment : fragmentList) {
if (fragment != null) {
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
mAutoTrackIgnoredFragments.remove(canonicalName.hashCode());
}
}
}
} catch (Exception ex) {
SALog.printStackTrace(ex);
}
}
@Override
public void resumeIgnoredAutoTrackFragment(Class<?> fragment) {
try {
if (fragment == null || mAutoTrackIgnoredFragments == null) {
return;
}
String canonicalName = fragment.getCanonicalName();
if (!TextUtils.isEmpty(canonicalName)) {
mAutoTrackIgnoredFragments.remove(canonicalName.hashCode());
}
} catch (Exception ex) {
SALog.printStackTrace(ex);
}
}
}
|
3e185089803c18384b4b1a4e1873fb1e303f1fa3 | 722 | java | Java | src/main/java/gd/rf/ninjaphenix/cursedchests/block/WoodVerticalChestBlock.java | shedaniel/CursedChests | c7a5efb3d3bba8974a4a120a0f2db302b5b6f5fa | [
"MIT"
] | null | null | null | src/main/java/gd/rf/ninjaphenix/cursedchests/block/WoodVerticalChestBlock.java | shedaniel/CursedChests | c7a5efb3d3bba8974a4a120a0f2db302b5b6f5fa | [
"MIT"
] | null | null | null | src/main/java/gd/rf/ninjaphenix/cursedchests/block/WoodVerticalChestBlock.java | shedaniel/CursedChests | c7a5efb3d3bba8974a4a120a0f2db302b5b6f5fa | [
"MIT"
] | 1 | 2020-04-22T09:02:29.000Z | 2020-04-22T09:02:29.000Z | 36.1 | 103 | 0.810249 | 10,335 | package gd.rf.ninjaphenix.cursedchests.block;
import gd.rf.ninjaphenix.cursedchests.api.block.VerticalChestBlock;
import gd.rf.ninjaphenix.cursedchests.block.entity.WoodVerticalChestBlockEntity;
import net.fabricmc.fabric.api.block.FabricBlockSettings;
import net.minecraft.block.Blocks;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.world.BlockView;
public class WoodVerticalChestBlock extends VerticalChestBlock
{
WoodVerticalChestBlock() { super(FabricBlockSettings.copy(Blocks.OAK_PLANKS).build()); }
@Override
public BlockEntity createBlockEntity(BlockView view) { return new WoodVerticalChestBlockEntity(); }
@Override
public String getName() { return "wood_chest"; }
}
|
3e1850e777455137e972b8cd0befb836a81ba825 | 457 | java | Java | chapter-11/search/vo/feature/DistrictFeature.java | zyx-team/zyx-study | a35c3b714a540c8b7eb39d59741dc17c1c5baeb4 | [
"Apache-2.0"
] | null | null | null | chapter-11/search/vo/feature/DistrictFeature.java | zyx-team/zyx-study | a35c3b714a540c8b7eb39d59741dc17c1c5baeb4 | [
"Apache-2.0"
] | null | null | null | chapter-11/search/vo/feature/DistrictFeature.java | zyx-team/zyx-study | a35c3b714a540c8b7eb39d59741dc17c1c5baeb4 | [
"Apache-2.0"
] | null | null | null | 16.321429 | 44 | 0.730853 | 10,336 | package com.imooc.ad.search.vo.feature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DistrictFeature {
private List<ProvinceAndCity> districts;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class ProvinceAndCity {
private String province;
private String city;
}
}
|
3e18516e5f25a1d4b14b07d7aa2564713d7198a1 | 1,373 | java | Java | src/main/java/org/zlatko/testing/spring/azsptest/services/api/Metadata.java | zlatko-ms/kafkatests | 43c5a700ed8c2f58f0474bfe965fae2d8f6b814a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/zlatko/testing/spring/azsptest/services/api/Metadata.java | zlatko-ms/kafkatests | 43c5a700ed8c2f58f0474bfe965fae2d8f6b814a | [
"Apache-2.0"
] | 10 | 2022-01-18T07:59:00.000Z | 2022-01-21T18:27:55.000Z | src/main/java/org/zlatko/testing/spring/azsptest/services/api/Metadata.java | zlatko-ms/kafkatests | 43c5a700ed8c2f58f0474bfe965fae2d8f6b814a | [
"Apache-2.0"
] | null | null | null | 29.847826 | 75 | 0.737072 | 10,337 | package org.zlatko.testing.spring.azsptest.services.api;
import java.util.List;
import java.util.Optional;
/** Contains definitions for the metadata fetching service and elements */
public final class Metadata {
/** Describes a consumer group */
public interface ConsumerGroup extends MetadataStringDescriptible {
public String getName();
public Optional<Boolean> isInternal();
public Optional<Boolean> isSimple();
public Optional<String> getTopic();
public Optional<String> getId();
}
/** Describes a cluster node */
public interface Node extends MetadataStringDescriptible {
public String getName();
public Optional<String> getRack();
}
/** Describes a topic */
public interface Topic extends MetadataStringDescriptible {
public String getName();
public Optional<String> getId();
public Optional<Integer> getReplicaCount();
public int getPartitionCount();
}
/** Human readable form of a Description */
public interface MetadataStringDescriptible {
public String getDescription();
}
/** Metadata fetching service interface */
public interface FetcherService extends Service.ConfigurableService {
Optional<List<Node>> getNodesDescriptionDescLines();
Optional<List<Topic>> getTopicsDescriptionDescLines();
Optional<List<ConsumerGroup>> getConsumerGroupDescLines();
}
}
|
3e1851f380eb830da60fa99dca4ca4e2ee4b236c | 702 | java | Java | src/main/java/com/lctech/swm/service/GroupRoleService.java | quanblackhat/swmportal | ecb7f211d87d8c54d350e9359387634d1fa8c6a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lctech/swm/service/GroupRoleService.java | quanblackhat/swmportal | ecb7f211d87d8c54d350e9359387634d1fa8c6a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lctech/swm/service/GroupRoleService.java | quanblackhat/swmportal | ecb7f211d87d8c54d350e9359387634d1fa8c6a3 | [
"Apache-2.0"
] | null | null | null | 24.206897 | 62 | 0.797721 | 10,338 | package com.lctech.swm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lctech.swm.domain.GroupRole;
import com.lctech.swm.repository.GroupRoleRepository;
@Service
public class GroupRoleService {
@Autowired
GroupRoleRepository grouproleRepository;
public List<GroupRole> findAll(){
return (List<GroupRole>) grouproleRepository.findAll();
}
public void save(GroupRole gr){
grouproleRepository.save(gr) ;
}
public GroupRole findByName(String name){
return grouproleRepository.findByName(name);
}
public GroupRole findById(Long id){
return grouproleRepository.findById(id);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.