repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
dmascenik/cloudlbs
platform/services/src/main/java/com/cloudlbs/platform/web/DeviceRegistrationController.java
2897
package com.cloudlbs.platform.web; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.cloudlbs.core.utils.protocol.NoopMessageConverter; import com.cloudlbs.core.utils.service.GenericService; import com.cloudlbs.core.utils.web.GenericController; import com.cloudlbs.sls.protocol.DeviceConnectionProto.DeviceConnectionMessage; /** * This web controller only supports GET where the GUID is the unique ID of the * device. If the device does not exist in the system, a new record and XMPP * account will be created.<br/> * <br/> * Currently, it is assumed that an upstream load balancer is evenly * distributing calls to processor instances, so this call will always return * the XMPP handle of this processor instance for the device to chat with. More * sophisticated load balancing of XMPP connections may be required in the * future. * * @author Dan Mascenik * */ @Controller @RequestMapping("/device/connection") public class DeviceRegistrationController extends GenericController<DeviceConnectionMessage, DeviceConnectionMessage> { /** * @param deviceConnectionService */ @Autowired public DeviceRegistrationController( GenericService<DeviceConnectionMessage> deviceRegistrationService) { super(deviceRegistrationService, new NoopMessageConverter<DeviceConnectionMessage>( DeviceConnectionMessage.class), null); } @Override public void deleteResource(String stub, HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } @Override public void getQuery(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } @Override public void postResource(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } @Override public void postQuery(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } @Override public void putResource(String stub, HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } /** * This controller may not need authentication at all, but being public, it * should complain about attempts to claim pre-authentication. */ @Override protected boolean isPreauthenticationAllowed() { return false; } }
mit
acbrauns/Quote_Capture
ListViewTrial1/src/com/copycat/listviewtrial1/MyTabsListener.java
1188
package com.copycat.listviewtrial1; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.FragmentTransaction; import android.content.Context; import android.support.v4.app.Fragment; import android.widget.Toast; class MyTabsListener implements TabListener { public android.app.Fragment mFragment; public Context mContext; public MyTabsListener(android.app.Fragment fragment, Context context) { mFragment = fragment; mContext = context; } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { Toast.makeText(mContext, "Reselected!", Toast.LENGTH_SHORT).show(); } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { Toast.makeText(mContext, "Selected!", Toast.LENGTH_SHORT).show(); ft.replace(R.id.fragmentContainer, mFragment); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { Toast.makeText(mContext, "Unselected!", Toast.LENGTH_SHORT).show(); ft.remove(mFragment); } }
mit
Mrbennjerry/Infinem
src/main/java/com/mod/infinem/item/ItemBase.java
568
package com.mod.infinem.item; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import com.mod.infinem.Infinem; /* * Items jason */ public class ItemBase extends Item { protected String name; public ItemBase(String name) { this.name = name; setUnlocalizedName(name); setRegistryName(name); } public void registerItemModel() { Infinem.proxy.registerItemRenderer(this, 0, name); } @Override public ItemBase setCreativeTab(CreativeTabs tab) { super.setCreativeTab(tab); return this; } }
mit
huji0624/LuckyPuzzle
proj.android/src/org/cocos2dx/cpp/LHLeaderBoardActivity.java
5771
package org.cocos2dx.cpp; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.lhgame.luckypuzzle.R; public class LHLeaderBoardActivity { private TextView mMyValue; private ListView mListView; private AlertDialog mAlert; private Context mContext; public LHLeaderBoardActivity(Context context) { mContext = context; } public void popSetUser(){ String message = null; String ok = null; String cancel = null; if (isChinese()) { message = "设置您的排行榜用户名"; ok = "确定"; cancel = "取消"; }else{ message = "Set your user name in LeaderBoard"; ok = "ok"; cancel = "cancel"; } final EditText et = new EditText(mContext); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage(message) .setView(et) .setPositiveButton(ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final String username = et.getText().toString(); if (username.length() == 0) { return; } String url = LHRequest.urlWithGetPair(LHRequest.LHLDURL, LHRequest.SETUSER,username,LHRequest.DEVICE,LHRequest.getDeviceID(mContext)); LHRequest request = new LHRequest(url); request.requestWitUrl(new LHRequestHandler() { @Override public void response(int requestcode, JSONObject obj) { // TODO Auto-generated method stub if (requestcode == LHRequestHandler.REQUEST_OK) { try { if (obj.getString("res").equals("ok")) { setUser(username); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } }) .setNegativeButton(cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } public void setUser(String user){ SharedPreferences sp = mContext.getSharedPreferences("lhgame", Context.MODE_WORLD_READABLE); Editor ed = sp.edit(); ed.putString("user", user); ed.commit(); } public void showLeaderBoard() { // TODO Auto-generated method stub View view=LayoutInflater.from(mContext).inflate(R.layout.lhleaderboard, null); mMyValue = (TextView) view.findViewById(R.id.myrank); mListView = (ListView) view.findViewById(R.id.toprank); String url = LHRequest.urlWithGetPair(LHRequest.LHLDURL, LHRequest.DEVICE, LHRequest.getDeviceID(mContext), LHRequest.USER, LHRequest.getUser(mContext),LHRequest.GAME,LHRequest.getGame(mContext)); LHRequest request = new LHRequest(url); request.requestWitUrl(new LHRequestHandler() { @Override public void response(int requestcode, JSONObject obj) { // TODO Auto-generated method stub if (requestcode == LHRequestHandler.REQUEST_OK) { try { JSONObject my = obj.getJSONObject("my"); String myhigh = my.getString("high"); String myrank = my.getString("rank"); if (myhigh.equals("null")) { mMyValue.setText("--"); }else{ String mystring = null; if (isChinese()) { mystring = formatHigh("我", myhigh, myrank); } else { mystring = formatHigh("Me", myhigh, myrank); } mMyValue.setText(mystring); } // allrank JSONArray list = obj.getJSONArray("list"); ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < list.length(); i++) { JSONObject tmpobj = list.getJSONObject(i); String tmpuser = tmpobj.getString(LHRequest.USER); String tmphigh = tmpobj.getString(LHRequest.HIGH); String tmprank = "" + (i+1); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("text", formatHigh(tmpuser, tmphigh, tmprank)); listItem.add(map); } SimpleAdapter adp = new SimpleAdapter( mContext, listItem, R.layout.lhld_item, new String[] { "text" }, new int[] { R.id.lhld }); mListView.setAdapter(adp); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setView(view); AlertDialog alert = builder.create(); alert.show(); mAlert = alert; } public boolean isShow(){ return mAlert.isShowing(); } public void dismiss(){ mAlert.dismiss(); } private String formatHigh(String user, String high, String rank) { StringBuilder sb = new StringBuilder(); sb.append(user); if (isChinese()) { sb.append(" 排名: "); sb.append(rank); sb.append(" , 成绩: "); sb.append(high); } else { sb.append(" rank: "); sb.append(rank); sb.append(" result: "); sb.append(high); } return sb.toString(); } private boolean isChinese() { return getLan().endsWith("zh"); } private String getLan() { Locale locale = mContext.getResources().getConfiguration().locale; String language = locale.getLanguage(); return language; } }
mit
NucleusPowered/Nucleus
nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/core/scaffold/command/control/CommandControl.java
18333
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.core.scaffold.command.control; import io.github.nucleuspowered.nucleus.api.util.NoExceptionAutoClosable; import io.github.nucleuspowered.nucleus.core.Registry; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandExecutor; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandResult; import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.Command; import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.CommandModifier; import io.github.nucleuspowered.nucleus.core.scaffold.command.config.CommandModifiersConfig; import io.github.nucleuspowered.nucleus.core.scaffold.command.impl.CommandContextImpl; import io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.ICommandModifier; import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection; import io.github.nucleuspowered.nucleus.core.services.interfaces.IReloadableService; import io.github.nucleuspowered.nucleus.core.util.PrettyPrinter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandCause; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.exception.CommandException; import org.spongepowered.api.command.exception.CommandPermissionException; import org.spongepowered.api.command.parameter.CommandContext; import org.spongepowered.api.command.parameter.Parameter; import org.spongepowered.api.command.parameter.managed.Flag; import org.spongepowered.api.service.context.Context; import org.spongepowered.api.service.permission.Subject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; public final class CommandControl { private static final String CONTEXT_KEY = "nucleus_command"; private final INucleusServiceCollection serviceCollection; private final List<String> basicPermission; private final CommandMetadata metadata; @Nullable private final ICommandExecutor executor; private final Map<CommandControl, List<String>> subcommands = new HashMap<>(); private final Map<String, CommandControl> primarySubcommands = new HashMap<>(); private final String commandKey; private final Context context; private final List<String> aliases; private final Map<CommandModifier, ICommandModifier> modifiers; private final CommandModifiersConfig commandModifiersConfig = new CommandModifiersConfig(); private final String command; private boolean acceptingRegistration = true; public CommandControl( @Nullable final ICommandExecutor executor, @Nullable final CommandControl parent, final CommandMetadata meta, final INucleusServiceCollection serviceCollection) { this.executor = meta.getCommandAnnotation().hasExecutor() ? executor : null; this.metadata = meta; this.commandKey = meta.getCommandKey(); this.context = new Context(CONTEXT_KEY, this.commandKey.replace(".", " ")); this.basicPermission = Collections.unmodifiableList(Arrays.asList(meta.getCommandAnnotation().basePermission())); this.serviceCollection = serviceCollection; this.aliases = Collections.unmodifiableList(Arrays.asList(meta.getAliases())); if (parent != null) { this.command = parent.command + " " + meta.getAliases()[0]; } else { this.command = meta.getAliases()[0]; } // this must be last. this.modifiers = CommandControl.validateModifiers(this, serviceCollection.logger(), meta.getCommandAnnotation()); } public void attach(final String alias, final CommandControl commandControl) { if (!this.acceptingRegistration) { throw new IllegalStateException("Registration is complete."); } this.subcommands.computeIfAbsent(commandControl, x -> new ArrayList<>()).add(alias.toLowerCase()); this.primarySubcommands.putIfAbsent( commandControl.getCommandKey().substring(commandControl.getCommandKey().lastIndexOf(".") + 1), commandControl); } public void completeRegistration(final INucleusServiceCollection serviceCollection) { if (!this.acceptingRegistration) { throw new IllegalStateException("Registration is complete."); } this.acceptingRegistration = false; if (this.executor instanceof IReloadableService.Reloadable) { final IReloadableService.Reloadable reloadable = (IReloadableService.Reloadable) this.executor; serviceCollection.reloadableService().registerReloadable(reloadable); reloadable.onReload(serviceCollection); } } @Nullable public ICommandExecutor getExecutor() { return this.executor; } public org.spongepowered.api.command.Command.Parameterized createCommand() { final org.spongepowered.api.command.Command.Builder b = org.spongepowered.api.command.Command.builder(); if (this.executor != null) { b.executor(this::process); for (final Parameter parameter : this.executor.parameters(this.serviceCollection)) { b.addParameter(parameter); } for (final Flag flag : this.executor.flags(this.serviceCollection)) { b.addFlag(flag); } } b.executionRequirements(re -> { for (final String perm : this.getPermission()) { if (!this.serviceCollection.permissionService().hasPermission(re, perm)) { return false; } } return true; }); b.shortDescription(this::getShortDescription).extendedDescription(this::getExtendedDescription); for (final Map.Entry<CommandControl, List<String>> control : this.subcommands.entrySet()) { b.addChild(control.getKey().createCommand(), control.getValue()); } return b.build(); } @NonNull public CommandResult process(@NonNull final CommandContext context) throws CommandException { if (this.executor == null) { throw new CommandException(Component.text("This should not be executed")); } // Create the ICommandContext final Map<CommandModifier, ICommandModifier> modifiers = this.selectAppropriateModifiers(context); final ICommandContext contextSource = new CommandContextImpl( context.cause(), context, this.serviceCollection, this, context.cause().subject().equals(Sponge.systemSubject()), modifiers ); try (final NoExceptionAutoClosable ignored = this.serviceCollection.permissionService().setContextTemporarily(context, this.context)) { // Do we have permission? if (!this.testPermission(context)) { throw new CommandPermissionException(contextSource.getMessage("permissions.nopermission")); } // Can we run this command? Exception will be thrown if not. for (final Map.Entry<CommandModifier, ICommandModifier> x : modifiers.entrySet()) { final Optional<? extends Component> req = x.getValue().testRequirement(contextSource, this, this.serviceCollection, x.getKey()); if (req.isPresent()) { // Nope, we're out throw new CommandException(req.get()); } } try { // execution Optional<ICommandResult> result = this.executor.preExecute(contextSource); if (result.isPresent()) { // STOP. this.onResult(contextSource, result.get()); return result.get().getResult(contextSource); } // Modifiers might have something to say about it. for (final Map.Entry<CommandModifier, ICommandModifier> modifier : contextSource.modifiers().entrySet()) { if (modifier.getKey().onExecute()) { result = modifier.getValue().preExecute(contextSource, this, this.serviceCollection, modifier.getKey()); if (result.isPresent()) { // STOP. this.onResult(contextSource, result.get()); return result.get().getResult(contextSource); } } } return this.execute(contextSource).getResult(contextSource); } catch (final Exception ex) { // Run any fail actions. this.runFailActions(contextSource); throw ex; } } } public Component getSubcommandTexts() { return this.getSubcommandTexts(null); } public Component getSubcommandTexts(@Nullable final CommandContext source) { return Component.join(Component.text(", "), this.primarySubcommands.entrySet() .stream() .filter(x -> source == null || x.getValue().testPermission(source)) .map(x -> Component.text(x.getKey())) .collect(Collectors.toList())); } private void runFailActions(final ICommandContext contextSource) { contextSource.failActions().forEach(x -> x.accept(contextSource)); } // Entry point for warmups. public void startExecute(@NonNull final ICommandContext contextSource) { try { this.execute(contextSource); } catch (final CommandException ex) { // If we are here, then we're handling the command ourselves. final Component message = ex.componentMessage() == null ? Component.text("Unknown error!", NamedTextColor.RED) : ex.componentMessage(); this.onFail(contextSource, message); this.serviceCollection.logger().warn("Error executing command {}", this.command, ex); } } private ICommandResult execute(@NonNull final ICommandContext context) throws CommandException { if (this.executor == null) { throw new IllegalStateException("Executor is missing."); } final ICommandResult result; // Anything else to go here? result = this.executor.execute(context); this.onResult(context, result); return result; } private void onResult(final ICommandContext contextSource, final ICommandResult result) throws CommandException { if (result.isSuccess()) { this.onSuccess(contextSource); } else if (!result.isWillContinue()) { // This occurs when no exception is thrown, so the error in the command result // will be returned. this.onFail(contextSource, null); } // The command will continue later. Don't do anything. } private void onSuccess(final ICommandContext source) throws CommandException { for (final Map.Entry<CommandModifier, ICommandModifier> x : source.modifiers().entrySet()) { if (x.getKey().onCompletion()) { x.getValue().onCompletion(source, this, this.serviceCollection, x.getKey()); } } } public void onFail(final ICommandContext source, @Nullable final Component errorMessage) { // Run any fail actions. this.runFailActions(source); if (errorMessage != null) { source.sendMessageText(errorMessage); } } private Map<CommandModifier, ICommandModifier> selectAppropriateModifiers(final CommandContext source) { return this.modifiers .entrySet() .stream() .filter(x -> x.getKey().target().isInstance(source.cause().root())) .filter(x -> { try { return x.getValue().canExecuteModifier(this.serviceCollection, source); } catch (final CommandException e) { e.printStackTrace(); return false; } }) .filter(x -> x.getKey().exemptPermission().isEmpty() || !this.serviceCollection.permissionService().hasPermission(source, x.getKey().exemptPermission())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } public Optional<Component> getShortDescription(@NonNull final CommandCause source) { return Optional.of(this.serviceCollection .messageProvider() .getMessageFor(source.audience(), this.metadata.getCommandAnnotation().commandDescriptionKey() + ".desc")); } public Optional<Component> getExtendedDescription(@NonNull final CommandCause source) { try { return Optional.ofNullable( this.serviceCollection .messageProvider() .getMessageFor(source.audience(), this.metadata.getCommandAnnotation().commandDescriptionKey() + ".extended") ); } catch (final Exception e) { return Optional.empty(); } } public Collection<String> getPermission() { return this.basicPermission; } public boolean testPermission(@NonNull final Subject source) { return this.basicPermission.stream().allMatch(x -> this.serviceCollection.permissionService().hasPermission(source, x)); } public CommandModifiersConfig getCommandModifiersConfig() { return this.commandModifiersConfig; } public String getCommand() { return this.command; } public String getModifierKey() { return this.metadata.getMetadataKey(); } public boolean isModifierKeyRedirected() { return this.metadata.isModifierKeyRedirect(); } public CommandMetadata getMetadata() { return this.metadata; } boolean hasExecutor() { return this.executor != null; } public String getCommandKey() { return this.commandKey; } public Context getContext() { return this.context; } public Map<CommandModifier, ICommandModifier> getCommandModifiers() { return this.modifiers; } public int getCooldown() { return this.commandModifiersConfig.getCooldown(); } public int getCooldown(final Subject subject) { return this.serviceCollection.permissionService() .getIntOptionFromSubject(subject, String.format("nucleus.%s.cooldown", this.command.replace(" ", "."))) .orElseGet(this::getCooldown); } public int getWarmup() { return this.commandModifiersConfig.getWarmup(); } public int getWarmup(final Subject subject) { return this.serviceCollection.permissionService() .getIntOptionFromSubject(subject, String.format("nucleus.%s.warmup", this.command.replace(" ", "."))) .orElseGet(this::getWarmup); } public double getCost() { return this.commandModifiersConfig.getCost(); } public double getCost(final Subject subject) { return this.serviceCollection.permissionService() .getDoubleOptionFromSubject(subject, String.format("nucleus.%s.cost", this.command.replace(" ", "."))) .orElseGet(this::getCost); } Collection<String> getAliases() { return this.aliases; } private static Map<CommandModifier, ICommandModifier> validateModifiers(final CommandControl control, final Logger logger, final Command command) { if (command.modifiers().length == 0) { return Collections.emptyMap(); } final Map<CommandModifier, ICommandModifier> modifiers = new LinkedHashMap<>(); for (final CommandModifier modifier : command.modifiers()) { try { // Get the registry entry. final ICommandModifier commandModifier = Sponge.game().registry(Registry.Types.COMMAND_MODIFIER_FACTORY) .findValue(ResourceKey.resolve(modifier.value())) .map(x -> x.apply(control)) .orElseThrow(() -> new IllegalArgumentException("Could not get registry entry for \"" + modifier.value() + "\"")); commandModifier.validate(modifier); modifiers.put(modifier, commandModifier); } catch (final IllegalArgumentException ex) { // could not validate final PrettyPrinter printer = new PrettyPrinter(); // Sponge can't find an item type... printer.add("Could not add modifier to command!").centre().hr(); printer.add("Command Description Key: "); printer.add(" " + command.commandDescriptionKey()); printer.add("Modifier: "); printer.add(" " + modifier.value()); printer.hr(); printer.add("Message:"); printer.add(ex.getMessage()); printer.hr(); printer.add("Stack trace:"); printer.add(ex); printer.log(logger, Level.ERROR); } } return Collections.unmodifiableMap(modifiers); } public Component getUsage(final ICommandContext context) { return Component.empty(); } }
mit
jstanier/tweet-scheduler
src/main/java/com/jstanier/tweetscheduler/ranking/RankedTimesOfWeek.java
475
package com.jstanier.tweetscheduler.ranking; import com.google.common.collect.ImmutableList; import java.util.List; import org.springframework.stereotype.Component; @Component public class RankedTimesOfWeek { private final List<Integer> rankedTimesOfWeek; public RankedTimesOfWeek() { rankedTimesOfWeek = ImmutableList.of(14,20,21,17,9,8,15,23,0); } public List<Integer> getRankedTimesOfWeek() { return rankedTimesOfWeek; } }
mit
xmomen/dms-webapp
src/main/java/com/xmomen/module/order/mapper/OrderMapper.java
481
package com.xmomen.module.order.mapper; /** * Created by Jeng on 16/4/13. */ public interface OrderMapper { public static final String ORDER_MAPPER_NAMESPACE = "com.xmomen.module.order.mapper.OrderMapper."; public static final String ORDER_PAY_RELATION_CODE = "ORDER_PAY_RELATION"; public static final String ORDER_PACKING_RELATION_CODE = "ORDER_PACKING_RELATION"; public static final String ORDER_PACKING_TASK_RELATION_CODE = "ORDER_PACKING_TASK_RELATION"; }
mit
ProfLuz/Karus-Commons
src/test/java/com/karuslabs/commons/animation/particles/MaterialParticlesTest.java
2619
/* * The MIT License * * Copyright 2017 Karus Labs. * * 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 com.karuslabs.commons.animation.particles; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.material.MaterialData; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*; public class MaterialParticlesTest { private MaterialData data = new MaterialData(Material.ACACIA_DOOR, (byte) 2); private MaterialParticles particles = spy(Particles.material().particle(Particle.CLOUD).offsetX(1).offsetY(2).offsetZ(3).speed(4).data(data).build()); private World world = mock(World.class); private Location location = when(mock(Location.class).getWorld()).thenReturn(world).getMock(); private Player player = when(mock(Player.class).getLocation()).thenReturn(location).getMock(); @Test public void render_Player() { particles.render(player, location); verify(player).spawnParticle(Particle.CLOUD, location, 0, 1, 2, 3, 4, data); } @Test public void render() { particles.render(location); verify(world).spawnParticle(Particle.CLOUD, location, 0, 1, 2, 3, 4, data); } @Test public void get() { assertEquals(1, particles.getOffsetX()); assertEquals(2, particles.getOffsetY()); assertEquals(3, particles.getOffsetZ()); assertEquals(4, particles.getSpeed()); assertEquals(data, particles.getData()); } }
mit
voxbone/voxapi-client-java
APIv3SandboxLib/src/com/voxbone/sandbox/models/TrunkListModel.java
740
/* * APIv3SandboxLib * * This file was automatically generated by APIMATIC BETA v2.0 on 03/10/2015 */ package com.voxbone.sandbox.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; public class TrunkListModel implements java.io.Serializable { private List<TrunkModel> trunks; /** GETTER * The list of trunks */ @JsonGetter("trunks") public List<TrunkModel> getTrunks ( ) { return this.trunks; } /** SETTER * The list of trunks */ @JsonSetter("trunks") public void setTrunks (List<TrunkModel> value) { this.trunks = value; } }
mit
AlexOreshkevich/iFramework
iframework-core/iframework-gwtpx/src/main/java/pro/redsoft/iframework/client/rebind/package-info.java
1202
/* The MIT License (MIT) Copyright (c) 2013 - 2014 REDSOFT.PRO 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-info. * * @author Alex N. Oreshkevich * */ package pro.redsoft.iframework.client.rebind;
mit
xiuzhuo/MyAndroidLib
AngelsLibrary/src/angel/zhuoxiu/library/pusher/websocket/WebSocketConnection.java
7500
/* * Copyright (C) 2011 Roderick Baier * * 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. */ /* * 09/02/2011 - Emory Myers - printing stacktraces for debugging purposes * added some logging * implemented isConnected method * modified send method */ package angel.zhuoxiu.library.pusher.websocket; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import android.util.Log; public class WebSocketConnection implements WebSocket { private URI url = null; private WebSocketEventHandler eventHandler = null; private volatile boolean connected = false; private Socket socket = null; private InputStream input = null; private PrintStream output = null; private WebSocketReceiver receiver = null; private WebSocketHandshake handshake = null; public WebSocketConnection(URI url) throws WebSocketException { this(url, null); } public WebSocketConnection(URI url, String protocol) throws WebSocketException { this.url = url; handshake = new WebSocketHandshake(url, protocol); } @Override public void setEventHandler(WebSocketEventHandler eventHandler) { this.eventHandler = eventHandler; } @Override public WebSocketEventHandler getEventHandler() { return this.eventHandler; } @Override public void connect() throws WebSocketException { try { if (connected) { throw new WebSocketException("already connected"); } socket = createSocket(); input = socket.getInputStream(); output = new PrintStream(socket.getOutputStream()); output.write(handshake.getHandshake()); boolean handshakeComplete = false; boolean header = true; int len = 1000; byte[] buffer = new byte[len]; int pos = 0; ArrayList<String> handshakeLines = new ArrayList<String>(); byte[] serverResponse = new byte[16]; while (!handshakeComplete) { int b = input.read(); buffer[pos] = (byte) b; pos += 1; if (!header) { serverResponse[pos - 1] = (byte) b; if (pos == 16) { handshakeComplete = true; } } else if (buffer[pos - 1] == 0x0A && buffer[pos - 2] == 0x0D) { String line = new String(buffer, "UTF-8"); if (line.trim().equals("")) { header = false; } else { handshakeLines.add(line.trim()); } buffer = new byte[len]; pos = 0; } } handshake.verifyServerStatusLine(handshakeLines.get(0)); handshake.verifyServerResponse(serverResponse); handshakeLines.remove(0); HashMap<String, String> headers = new HashMap<String, String>(); for (String line : handshakeLines) { String[] keyValue = line.split(": ", 2); headers.put(keyValue[0], keyValue[1]); } handshake.verifyServerHandshakeHeaders(headers); receiver = new WebSocketReceiver(input, this); receiver.start(); connected = true; eventHandler.onOpen(); } catch (WebSocketException wse) { wse.printStackTrace(); throw wse; } catch (IOException ioe) { ioe.printStackTrace(); throw new WebSocketException("error while connecting: " + ioe.getMessage(), ioe); } } @Override public synchronized void send(String data) throws WebSocketException { if (!connected) { throw new WebSocketException( "error while sending text data: not connected"); } try { output.write(0x00); output.write(data.getBytes(("UTF-8"))); output.write(0xff); // output.write("\r\n".getBytes()); Log.d("Output", "Wrote to Output"); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); throw new WebSocketException( "error while sending text data: unsupported encoding", uee); } catch (IOException ioe) { ioe.printStackTrace(); throw new WebSocketException("error while sending text data", ioe); } } // public synchronized void send(byte[] data) // throws WebSocketException // { // if (!connected) { // throw new // WebSocketException("error while sending binary data: not connected"); // } // // try { // output.write(0x80); // output.write(data.length); // output.write(data); // output.write("\r\n".getBytes()); // } // catch (IOException ioe) { // throw new WebSocketException("error while sending binary data: ", ioe); // } // } public void handleReceiverError() { try { if (connected) { close(); } } catch (WebSocketException wse) { wse.printStackTrace(); } } @Override public synchronized void close() throws WebSocketException { Log.d("Close", "WebSocket closed"); if (!connected) { return; } sendCloseHandshake(); if (receiver.isRunning()) { receiver.stopit(); } closeStreams(); eventHandler.onClose(); } private synchronized void sendCloseHandshake() throws WebSocketException { if (!connected) { throw new WebSocketException( "error while sending close handshake: not connected"); } try { output.write(0xff00); output.write("\r\n".getBytes()); } catch (IOException ioe) { ioe.printStackTrace(); throw new WebSocketException("error while sending close handshake", ioe); } connected = false; } private Socket createSocket() throws WebSocketException { String scheme = url.getScheme(); String host = url.getHost(); int port = url.getPort(); Socket socket = null; if (scheme != null && scheme.equals("ws")) { if (port == -1) { port = 80; } try { socket = new Socket(host, port); socket.setKeepAlive(true); socket.setSoTimeout(0); } catch (UnknownHostException uhe) { uhe.printStackTrace(); throw new WebSocketException("unknown host: " + host, uhe); } catch (IOException ioe) { ioe.printStackTrace(); throw new WebSocketException("error while creating socket to " + url, ioe); } } else if (scheme != null && scheme.equals("wss")) { if (port == -1) { port = 443; } try { SocketFactory factory = SSLSocketFactory.getDefault(); socket = factory.createSocket(host, port); } catch (UnknownHostException uhe) { uhe.printStackTrace(); throw new WebSocketException("unknown host: " + host, uhe); } catch (IOException ioe) { ioe.printStackTrace(); throw new WebSocketException( "error while creating secure socket to " + url, ioe); } } else { throw new WebSocketException("unsupported protocol: " + scheme); } return socket; } private void closeStreams() throws WebSocketException { Log.d("ClosedStreams", "closeStreams"); try { input.close(); output.close(); socket.close(); } catch (IOException ioe) { ioe.printStackTrace(); throw new WebSocketException( "error while closing websocket connection: ", ioe); } } @Override public boolean isConnected() { return connected; } }
mit
EnSoftCorp/loop-comprehension-toolbox
com.kcsl.loop/src/com/kcsl/loop/util/MethodSignatures.java
18130
package com.kcsl.loop.util; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * List of String method signatures, to be used with MethodSignatureMatcher * * @author gsanthan * @author Payas Awadhutkar * */ public interface MethodSignatures { /** * Master list of string constants representing method signatures to be detected for termination pattern discovery */ // java.util.Iterator public static final String SIGNATURE_ITERATOR_CONSTRUCTION = "java.util.Iterator iterator()"; public static final String SIGNATURE_LISTITERATOR_CONSTRUCTION = "java.util.ListIterator listIterator()"; public static final String SIGNATURE_LISTITERATOR_PARAMETERIZED_CONSTRUCTION = "java.util.ListIterator listIterator(int)"; public static final String SIGNATURE_ITERATOR_HAS_NEXT = "boolean hasNext()"; public static final String SIGNATURE_ITERATOR_NEXT = "java.lang.Object next()"; public static final String SIGNATURE_ITERATOR_REMOVE = "void remove()"; // java.util.Enumeration public static final String SIGNATURE_ENUMERATION_NEXTELEMENT = "java.lang.Object nextElement()"; public static final String SIGNATURE_ENUMERATION_HASMORELEMENTS = "boolean hasMoreElements()"; // java.lang.String public static final String SIGNATURE_STRING_CONCAT = "java.lang.String concat(java.lang.String)"; // java.util.StringTokenizer public static final String SIGNATURE_STRING_NEXT_TOKEN = "java.lang.String nextToken()"; public static final String SIGNATURE_HAS_NEXT_TOKEN = "boolean hasMoreTokens()"; // IO public static final String SIGNATURE_READLINE = "java.lang.String readLine()"; // java.util.List public static final String SIGNATURE_LIST_ADD = "boolean add(java.lang.Object)"; public static final String SIGNATURE_LIST_ADDALL = "boolean addAll(java.util.Collection)"; public static final String SIGNATURE_LIST_SET = "java.lang.Object set(int, java.lang.Object)"; public static final String SIGNATURE_LIST_REMOVE = "java.lang.Object remove(int)"; public static final String SIGNATURE_LIST_REMOVEALL = "boolean removeAll(java.util.Collection)"; public static final String SIGNATURE_LIST_CLEAR = "void clear()"; public static final String LIST_RETAINALL = "boolean retainAll(java.util.Collection)"; // java.util.Stack public static final String SIGNATURE_STACK_PUSH = "java.lang.Object push(java.lang.Object)"; public static final String SIGNATURE_STACK_POP = "java.lang.Object pop()"; public static final String SIGNATURE_STACK_PEEK = "java.lang.Object peek()"; // java.util.Map public static final String MAP_CLEAR = "void clear()"; public static final String MAP_PUTALL = "void putAll(java.util.Map)"; public static final String MAP_PUT = "java.lang.Object put(java.lang.Object, java.lang.Object)"; public static final String MAP_REMOVE = "java.lang.Object remove(java.lang.Object)"; // java.util.Set public static final String SET_ADDALL = "boolean addAll(java.util.Collection)"; public static final String SET_REMOVEALL = "boolean removeAll(java.util.Collection)"; public static final String SET_ADD = "boolean add(java.lang.Object)"; public static final String SET_REMOVE = "boolean remove(java.lang.Object)"; public static final String SET_CLEAR = "void clear()"; public static final String SET_RETAINALL = "boolean retainAll(java.util.Collection)"; // java.util.Vector public static final String VECTOR_REMOVE = "java.lang.Object remove(int)"; public static final String VECTOR_ADDALL = "boolean addAll(int, java.util.Collection)"; public static final String VECTOR_REMOVEALL = "boolean removeAll(java.util.Collection)"; public static final String VECTOR_CLEAR = "void clear()"; public static final String VECTOR_ADDELEMENT = "void addElement(java.lang.Object)"; public static final String VECTOR_REMOVEALLELEMENTS = "void removeAllElements()"; public static final String VECTOR_REMOVEELEMENT = "boolean removeElement(java.lang.Object)"; public static final String VECTOR_INSERTELEMENTAT = "void insertElementAt(java.lang.Object, int)"; public static final String VECTOR_REMOVERANGE = "void removeRange(int, int)"; public static final String VECTOR_ADD = "boolean add(java.lang.Object)"; public static final String VECTOR_REMOVEELEMENTAT = "void removeElementAt(int)"; public static final String VECTOR_GROW = "void grow(int)"; public static final String VECTOR_ADD2 = "void add(int, java.lang.Object)"; public static final String VECTOR_REMOVE2 = "boolean remove(java.lang.Object)"; public static final String VECTOR_RETAINALL = "boolean retainAll(java.util.Collection)"; public static final String VECTOR_ADDALL2 = "boolean addAll(java.util.Collection)"; // java.util.Collection public static final String COLLECTION_REMOVEALL = "boolean removeAll(java.util.Collection)"; public static final String COLLECTION_ADDALL = "boolean addAll(java.util.Collection)"; public static final String COLLECTION_ADD = "boolean add(java.lang.Object)"; public static final String COLLECTION_REMOVE = "boolean remove(java.lang.Object), void clear()"; public static final String COLLECTION_RETAINALL = "boolean retainAll(java.util.Collection)"; // java.util.Queue public static final String QUEUE_ADD = "boolean add(java.lang.Object)"; public static final String QUEUE_OFFER = "boolean offer(java.lang.Object)"; public static final String QUEUE_POLL = "java.lang.Object poll()"; public static final String QUEUE_REMOVE = "java.lang.Object remove()"; // java.util.Deque public static final String DEQUE_ADDFIRST = "void addFirst(java.lang.Object)"; public static final String DEQUE_OFFERFIRST = "boolean offerFirst(java.lang.Object)"; public static final String DEQUE_REMOVEFIRST = "java.lang.Object removeFirst()"; public static final String DEQUE_REMOVELAST = "java.lang.Object removeLast()"; public static final String DEQUE_REMOVELASTOCCURENCE = "boolean removeLastOccurrence(java.lang.Object)"; public static final String DEQUE_POP = "java.lang.Object pop()"; public static final String DEQUE_OFFERLAST = "boolean offerLast(java.lang.Object)"; public static final String DEQUE_POLLFIRST = "java.lang.Object pollFirst()"; public static final String DEQUE_OFFER = "boolean offer(java.lang.Object)"; public static final String DEQUE_REMOVE = "boolean remove(java.lang.Object)"; public static final String DEQUE_PUSH = "void push(java.lang.Object)"; public static final String DEQUE_POLLLAST = "java.lang.Object pollLast()"; public static final String DEQUE_POLL = "java.lang.Object poll()"; public static final String DEQUE_ADD = "boolean add(java.lang.Object)"; public static final String DEQUE_ADDLAST = "void addLast(java.lang.Object)"; public static final String DEQUE_REMOVE2 = "java.lang.Object remove()"; // java.util.WeakHashMap public static final String WEAKHASHMAP_REMOVE = "java.lang.Object remove(java.lang.Object)"; public static final String WEAKHASHMAP_PUT = "java.lang.Object put(java.lang.Object, java.lang.Object)"; public static final String WEAKHASHMAP_CLEAR = "void clear()"; public static final String WEAKHASHMAP_PUTALL = "void putAll(java.util.Map)"; // java.util.HashTable public static final String HASHTABLE_PUTALL = "void putAll(java.util.Map)"; public static final String HASHTABLE_REMOVE = "java.lang.Object remove(java.lang.Object)"; public static final String HASHTABLE_PUT = "java.lang.Object put(java.lang.Object, java.lang.Object)"; public static final String HASHTABLE_CLEAR = "void clear()"; //java.io READ public static final String IO_CANREAD = "boolean canRead()"; public static final String IO_READBOOLEAN = "boolean readBoolean()"; public static final String IO_READBYTE = "byte readByte()"; public static final String IO_READCHAR = "char readChar()"; public static final String IO_READLINE1 = "char[] readline(boolean)"; public static final String IO_READPASSWORD1 = "char[] readPassword()"; public static final String IO_READPASSWORD = "char[] readPassword(java.lang.String, java.lang.Object[])"; public static final String IO_READDOUBLE = "double readDouble()"; public static final String IO_READFLOAT = "float readFloat()"; public static final String IO_READ8 = "int read()"; public static final String IO_READ2 = "int read(byte[])"; public static final String IO_READ3 = "int read(byte[], int, int)"; public static final String IO_READ4 = "int read(byte[], int, int, boolean)"; public static final String IO_READ5 = "int read(char[])"; public static final String IO_READ6 = "int read(char[], int, int)"; public static final String IO_READ7 = "int read(java.nio.CharBuffer)"; public static final String IO_READ0 = "int read0()"; public static final String IO_READ11 = "int read1(byte[], int, int)"; public static final String IO_READ1 = "int read1(char[], int, int)"; public static final String IO_READBLOCKHEADER = "int readBlockHeader(boolean)"; public static final String IO_READBYTES = "int readBytes(byte[], int, int)"; public static final String IO_READBYTES0 = "int readBytes0(byte[], int, int)"; public static final String IO_READINT = "int readInt()"; public static final String IO_READUNSIGNEDBYTE = "int readUnsignedByte()"; public static final String IO_READUNSIGNEDSHORT = "int readUnsignedShort()"; public static final String IO_READUTFCHAR = "int readUTFChar(java.lang.StringBuilder, long)"; public static final String IO_READCLASS = "java.lang.Class readClass(boolean)"; public static final String IO_READENUM = "java.lang.Enum readEnum(boolean)"; public static final String IO_READARRAY = "java.lang.Object readArray(boolean)"; public static final String IO_READHANDLE = "java.lang.Object readHandle(boolean)"; public static final String IO_READNULL = "java.lang.Object readNull()"; public static final String IO_READOBJECT1 = "java.lang.Object readObject()"; public static final String IO_READOBJECT0 = "java.lang.Object readObject0(boolean)"; public static final String IO_READOBJECTOVERRIDE = "java.lang.Object readObjectOverride()"; public static final String IO_READORDINARYOBJECT = "java.lang.Object readOrdinaryObject(boolean)"; public static final String IO_READUNSHARED = "java.lang.Object readUnshared()"; public static final String IO_READLINE4 = "java.lang.String readLine()"; public static final String IO_READLINE2 = "java.lang.String readLine(boolean)"; public static final String IO_READLINE3 = "java.lang.String readLine(java.lang.String, java.lang.Object[])"; public static final String IO_READLONGUTF = "java.lang.String readLongUTF()"; public static final String IO_READSTRING = "java.lang.String readString(boolean)"; public static final String IO_READTYPESTRING = "java.lang.String readTypeString()"; public static final String IO_READUTF1 = "java.lang.String readUTF()"; public static final String IO_READUTF = "java.lang.String readUTF(java.io.DataInput)"; public static final String IO_READUTFBODY = "java.lang.String readUTFBody(long)"; public static final String IO_READLONG = "long readLong()"; public static final String IO_READUTFSPAN = "long readUTFSpan(java.lang.StringBuilder, long)"; public static final String IO_READSHORT = "short readShort()"; public static final String IO_READBOOLEANS = "void readBooleans(boolean[], int, int)"; public static final String IO_READCHARS = "void readChars(char[], int, int)"; public static final String IO_READDOUBLES = "void readDoubles(double[], int, int)"; public static final String IO_READEXTERNALDATA = "void readExternalData(java.io.Externalizable, java.io.ObjectStreamClass)"; public static final String IO_READFIELDS = "void readFields()"; public static final String IO_READFLOATS = "void readFloats(float[], int, int)"; public static final String IO_READFULLY1 = "void readFully(byte[])"; public static final String IO_READFULLY2 = "void readFully(byte[], int, int)"; public static final String IO_READFULLY = "void readFully(byte[], int, int, boolean)"; public static final String IO_READINTS = "void readInts(int[], int, int)"; public static final String IO_READLONGS = "void readLongs(long[], int, int)"; public static final String IO_READOBJECT = "void readObject(java.io.ObjectInputStream)"; public static final String IO_READSERIALDATA = "void readSerialData(java.lang.Object, java.io.ObjectStreamClass)"; public static final String IO_READSHORTS = "void readShorts(short[], int, int)"; public static final String IO_READSTREAMHEADER = "void readStreamHeader()"; // Ignore the following APIs for now - revisit later public static final String IO_UNREAD1 = "void unread(byte[])"; public static final String IO_UNREAD2 = "void unread(byte[], int, int)"; public static final String IO_UNREAD3 = "void unread(char[])"; public static final String IO_UNREAD4 = "void unread(char[], int, int)"; public static final String IO_UNREAD = "void unread(int)"; /** * Procedure to add new Patterns and corresponding API signature: * 1. Add all APIs in the pattern to master list of signatures (above) * 2. Add each API to INCREMENT_APIs, DECREMENT_APIs, or IO_APIs as applicable * 3. If it is iterator pattern, add entry to the map in IteratorPatternSignatures and to the enum */ public static final Set<String> ITERATOR_APIs = new HashSet<>(Arrays.asList(new String[] { SIGNATURE_ENUMERATION_HASMORELEMENTS, SIGNATURE_ENUMERATION_NEXTELEMENT, SIGNATURE_ITERATOR_HAS_NEXT, SIGNATURE_ITERATOR_NEXT, SIGNATURE_ITERATOR_REMOVE })); public static final Set<String> COLLECTION_APIs = new HashSet<>(Arrays.asList(new String[] { SIGNATURE_LIST_ADD, SIGNATURE_LIST_ADDALL, SIGNATURE_LIST_SET, SIGNATURE_LIST_REMOVE, SIGNATURE_LIST_REMOVEALL, SIGNATURE_LIST_CLEAR, LIST_RETAINALL, SIGNATURE_STACK_PUSH, SIGNATURE_STACK_POP, SIGNATURE_STACK_PEEK, MAP_CLEAR, MAP_PUTALL, MAP_PUT, MAP_REMOVE, SET_ADDALL, SET_REMOVEALL, SET_ADD, SET_REMOVE, SET_CLEAR, SET_RETAINALL, VECTOR_REMOVE, VECTOR_ADDALL, VECTOR_REMOVEALL, VECTOR_CLEAR, VECTOR_ADDELEMENT, VECTOR_REMOVEALLELEMENTS, VECTOR_REMOVEELEMENT, VECTOR_INSERTELEMENTAT, VECTOR_REMOVERANGE, VECTOR_ADD, VECTOR_REMOVEELEMENTAT, VECTOR_GROW, VECTOR_ADD2, VECTOR_REMOVE2, VECTOR_RETAINALL, VECTOR_ADDALL2, COLLECTION_REMOVEALL, COLLECTION_ADDALL, COLLECTION_ADD, COLLECTION_REMOVE, COLLECTION_RETAINALL, QUEUE_ADD, QUEUE_OFFER, QUEUE_POLL, QUEUE_REMOVE, DEQUE_ADDFIRST, DEQUE_OFFERFIRST, DEQUE_REMOVEFIRST, DEQUE_REMOVELAST, DEQUE_REMOVELASTOCCURENCE, DEQUE_POP, DEQUE_OFFERLAST, DEQUE_POLLFIRST, DEQUE_OFFER, DEQUE_REMOVE, DEQUE_PUSH, DEQUE_POLLLAST, DEQUE_POLL, DEQUE_ADD, DEQUE_ADDLAST, DEQUE_REMOVE2, WEAKHASHMAP_REMOVE, WEAKHASHMAP_PUT, WEAKHASHMAP_CLEAR, WEAKHASHMAP_PUTALL, HASHTABLE_PUTALL, HASHTABLE_REMOVE, HASHTABLE_PUT, HASHTABLE_CLEAR })); /** * Add APIs that represent "increment" behavior for monotonicity analysis */ public static final Set<String> INCREMENT_APIs = new HashSet<>(Arrays.asList(new String[] { SIGNATURE_ITERATOR_NEXT, SIGNATURE_ENUMERATION_NEXTELEMENT, SIGNATURE_STRING_NEXT_TOKEN, SIGNATURE_LIST_ADD, SIGNATURE_LIST_ADDALL, SIGNATURE_STACK_PUSH, MAP_PUTALL, MAP_PUT, SET_ADDALL, SET_ADD, VECTOR_ADDALL, VECTOR_ADDELEMENT, VECTOR_INSERTELEMENTAT, VECTOR_ADD, VECTOR_GROW, VECTOR_ADD2, VECTOR_ADDALL2, COLLECTION_ADDALL, COLLECTION_ADD, QUEUE_ADD, QUEUE_OFFER, DEQUE_ADDFIRST, DEQUE_OFFERFIRST, DEQUE_OFFERLAST, DEQUE_OFFER, DEQUE_PUSH, DEQUE_ADD, DEQUE_ADDLAST, WEAKHASHMAP_PUT, WEAKHASHMAP_PUTALL, HASHTABLE_PUTALL, HASHTABLE_PUT })); /** * Add APIs that represent "decrement" behavior for monotonicity analysis */ public static final Set<String> DECREMENT_APIs = new HashSet<>(Arrays.asList(new String[] { SIGNATURE_ITERATOR_REMOVE, SIGNATURE_LIST_REMOVE, SIGNATURE_LIST_REMOVEALL, SIGNATURE_LIST_CLEAR, SIGNATURE_STACK_POP, MAP_CLEAR, MAP_REMOVE, SET_REMOVEALL, SET_REMOVE, SET_CLEAR, SET_RETAINALL, VECTOR_REMOVE, VECTOR_REMOVEALL, VECTOR_CLEAR, VECTOR_REMOVEALLELEMENTS, VECTOR_REMOVEELEMENT, VECTOR_REMOVERANGE, VECTOR_REMOVEELEMENTAT, VECTOR_REMOVE2, VECTOR_RETAINALL, COLLECTION_REMOVEALL, COLLECTION_REMOVE, COLLECTION_RETAINALL, QUEUE_POLL, QUEUE_REMOVE, DEQUE_REMOVEFIRST, DEQUE_REMOVELAST, DEQUE_REMOVELASTOCCURENCE, DEQUE_POP, DEQUE_POLLFIRST, DEQUE_REMOVE, DEQUE_POLLLAST, DEQUE_POLL, DEQUE_REMOVE2, WEAKHASHMAP_REMOVE, WEAKHASHMAP_CLEAR, HASHTABLE_REMOVE, HASHTABLE_CLEAR })); /** * Add APIs that represent "IO" behavior for monotonicity analysis */ public static final Set<String> IO_APIs = new HashSet<>(Arrays.asList(new String[] { SIGNATURE_READLINE, IO_CANREAD, IO_READBOOLEAN, IO_READBYTE, IO_READCHAR, IO_READLINE1, IO_READPASSWORD1, IO_READPASSWORD, IO_READDOUBLE, IO_READFLOAT, IO_READ8, IO_READ2, IO_READ3, IO_READ4, IO_READ5, IO_READ6, IO_READ7, IO_READ0, IO_READ11, IO_READ1, IO_READBLOCKHEADER, IO_READBYTES, IO_READBYTES0, IO_READINT, IO_READUNSIGNEDBYTE, IO_READUNSIGNEDSHORT, IO_READUTFCHAR, IO_READCLASS, IO_READENUM, IO_READARRAY, IO_READHANDLE, IO_READNULL, IO_READOBJECT1, IO_READOBJECT0, IO_READOBJECTOVERRIDE, IO_READORDINARYOBJECT, IO_READUNSHARED, IO_READLINE4, IO_READLINE2, IO_READLINE3, IO_READLONGUTF, IO_READSTRING, IO_READTYPESTRING, IO_READUTF1, IO_READUTF, IO_READUTFBODY, IO_READLONG, IO_READUTFSPAN, IO_READSHORT, IO_READBOOLEANS, IO_READCHARS, IO_READDOUBLES, IO_READEXTERNALDATA, IO_READFIELDS, IO_READFLOATS, IO_READFULLY1, IO_READFULLY2, IO_READFULLY, IO_READINTS, IO_READLONGS, IO_READOBJECT, IO_READSERIALDATA, IO_READSHORTS, IO_READSTREAMHEADER })); }
mit
shalk/TIJ4Code
operators/solution/Ex13.java
234
package operators.solution; public class Ex13 { public static void main(String[] args){ char a = 'w'; System.out.println(Integer.toBinaryString(a)); a = 'A'; System.out.println(Integer.toBinaryString(a)); } }
mit
DoFabien/OsmGo
android/capacitor/src/main/java/com/getcapacitor/PluginInvocationException.java
277
package com.getcapacitor; class PluginInvocationException extends Exception { public PluginInvocationException(String s) { super(s); } public PluginInvocationException(Throwable t) { super(t); } public PluginInvocationException(String s, Throwable t) { super(s, t); } }
mit
8enet/AppOpsX
opsxlib/src/main/java/com/zzzmode/appopsx/common/PackageOps.java
2001
package com.zzzmode.appopsx.common; import android.os.Parcel; import android.os.Parcelable; import android.util.SparseArray; import java.util.ArrayList; import java.util.List; public class PackageOps implements Parcelable { private final String mPackageName; private final int mUid; private final List<OpEntry> mEntries; private SparseArray<OpEntry> mSparseEntries = null; public PackageOps(String packageName, int uid, List<OpEntry> entries) { mPackageName = packageName; mUid = uid; mEntries = entries; } public String getPackageName() { return mPackageName; } public int getUid() { return mUid; } public List<OpEntry> getOps() { return mEntries; } public boolean hasOp(int op) { if (mSparseEntries == null) { mSparseEntries = new SparseArray<>(); if (mEntries != null) { for (OpEntry entry : mEntries) { mSparseEntries.put(entry.getOp(), entry); } } } return mSparseEntries.indexOfKey(op) >= 0; } @Override public String toString() { return "PackageOps{" + "mPackageName='" + mPackageName + '\'' + ", mUid=" + mUid + ", mEntries=" + mEntries + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.mPackageName); dest.writeInt(this.mUid); dest.writeList(this.mEntries); } protected PackageOps(Parcel in) { this.mPackageName = in.readString(); this.mUid = in.readInt(); this.mEntries = new ArrayList<OpEntry>(); in.readList(this.mEntries, OpEntry.class.getClassLoader()); } public static final Parcelable.Creator<PackageOps> CREATOR = new Parcelable.Creator<PackageOps>() { @Override public PackageOps createFromParcel(Parcel source) { return new PackageOps(source); } @Override public PackageOps[] newArray(int size) { return new PackageOps[size]; } }; }
mit
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.nosql.s13e.entitydifferentiation.examples/test/es/um/nosql/s13e/test/morphia/datamanagement/StackOverflowDataManagement.java
9895
package es.um.nosql.s13e.test.morphia.datamanagement; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; import org.mongodb.morphia.ValidationExtension; import org.mongodb.morphia.query.FindOptions; import es.um.nosql.s13e.db.adapters.mongodb.MongoDbAdapter; import es.um.nosql.s13e.db.adapters.mongodb.MongoDbClient; import es.um.nosql.s13e.stackoverflow.Badges; import es.um.nosql.s13e.stackoverflow.Postlinks; import es.um.nosql.s13e.stackoverflow.Posts; import es.um.nosql.s13e.stackoverflow.Tags; import es.um.nosql.s13e.stackoverflow.Votes; public class StackOverflowDataManagement { private Morphia morphia; private MongoDbClient client; private Datastore datastore; private String dbName; public StackOverflowDataManagement(String ip, String dbName) { this.dbName = dbName; this.morphia = new Morphia(); this.morphia = morphia.mapPackage("es.um.nosql.s13e." + this.dbName); new ValidationExtension(this.morphia); this.client = MongoDbAdapter.getMongoDbClient(ip); this.datastore = this.morphia.createDatastore(this.client, this.dbName); this.datastore.ensureIndexes(); } public void startDemo() { /** * First test: Check how many distinct PostTypeIds, VoteTypeIds and LinkTypeIds (could have been done with the distinct Morphia operator) */ distinctValues(); /** * Second test: Check which months generated the top 25% posts in this StackOverflow subdataset. */ topMonthsOfActivity(); /** * Third test: Check which are the top 25% most commonly used tags in this StackOverflow subdataset. */ mostPopularTags(); /** * Fourth test: Check the average close question post time from posts closed in less than a year. */ avgTimeToCloseQuestion(); /** * Fifth test: For each badge check the recent date in which some User earned it. */ mostRecentBadges(); this.client.close(); } private void distinctValues() { System.out.print("PostTypeIds: " + String.join(" ", getDistinctPostTypeIds())); System.out.print("VoteTypeIds: " + String.join(" ", getDistinctVoteTypeIds())); System.out.print("LinkTypeIds: " + String.join(" ", getDistinctPostlinksIds())); } private List<String> getDistinctPostTypeIds() { SortedSet<Integer> sPostTypeIds = new TreeSet<Integer>(); datastore.createQuery(Posts.class).project("PostTypeId", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(post -> { if (post.getPostTypeId() != null) sPostTypeIds.add(post.getPostTypeId()); }); return sPostTypeIds.stream().map(n -> n.toString()).collect(Collectors.toList()); } private List<String> getDistinctVoteTypeIds() { SortedSet<Integer> sVoteTypeIds = new TreeSet<Integer>(); datastore.createQuery(Votes.class).project("VoteTypeId", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(vote -> { if (vote.getVoteTypeId() != null) sVoteTypeIds.add(vote.getVoteTypeId()); }); return sVoteTypeIds.stream().map(n -> n.toString()).collect(Collectors.toList()); } private List<String> getDistinctPostlinksIds() { SortedSet<Integer> sPostlinksIds = new TreeSet<Integer>(); datastore.createQuery(Postlinks.class).project("LinkTypeId", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(postlink -> { if (postlink.getLinkTypeId() != null) sPostlinksIds.add(postlink.getLinkTypeId()); }); return sPostlinksIds.stream().map(n -> n.toString()).collect(Collectors.toList()); } private Map<String, Integer> getPostsByYear() { SortedMap<String, Integer> result = new TreeMap<String, Integer>(); datastore.createQuery(Posts.class).project("CreationDate", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(post -> { String year = post.getCreationDate().substring(0, post.getCreationDate().lastIndexOf("-")); if (result.containsKey(year)) result.put(year, result.get(year) + 1); else result.put(year, 0); }); return result; } private void topMonthsOfActivity() { Map<String, Integer> mPostsByYear = getPostsByYear(); List<Entry<String, Integer>> lPosts = new ArrayList<Entry<String, Integer>>(mPostsByYear.entrySet()); Collections.sort(lPosts, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) { return e2.getValue().compareTo(e1.getValue()); } }); System.out.println("Top twenty-five percent months of activity: "); int sumPosts = mPostsByYear.values().stream().reduce((x,y) -> {return x + y;}).get(); int percPosts = (sumPosts * 25) / 100; int aux = 0; for (Entry<String, Integer> entry : lPosts) { aux += entry.getValue(); System.out.println(entry.getKey() + ": " + entry.getValue()); if (aux >= percPosts) break; } } // Take into account that "Count" is stored as strings in the SOF dataset, so ordering/limiting // the number of responses by using the Morphia API is not useful. We have to query each object and map them to our POJO. private void mostPopularTags() { Map<String, Integer> mTagsByCount = new HashMap<String, Integer>(); datastore.createQuery(Tags.class).project("Count", true).project("TagName", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(tag -> { mTagsByCount.put(tag.getTagName(), tag.getCount()); }); List<Entry<String, Integer>> lTags = new ArrayList<Entry<String, Integer>>(mTagsByCount.entrySet()); Collections.sort(lTags, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) { return e2.getValue().compareTo(e1.getValue()); } }); System.out.println("Top twenty-five percent most commonly used tags: "); int sumTags = mTagsByCount.values().stream().reduce((x, y) -> {return x + y;}).get(); int percPosts = (sumTags * 25) / 100; int aux = 0; for (Entry<String, Integer> entry : lTags) { aux += entry.getValue(); System.out.println(entry.getKey() + ": " + entry.getValue()); if (aux >= percPosts) break; } } private void avgTimeToCloseQuestion() { List<Long> diffLongs = new ArrayList<Long>(); long avgTime = 0; int TOO_LONG_FILTER = 365; // We're going to remove posts not closed in a year since creation... DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); datastore.createQuery(Posts.class).filter("CreationDate exists", true).filter("ClosedDate exists", true) .project("CreationDate", true).project("ClosedDate", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(post -> { try { Date creationDate = dFormat.parse(post.getCreationDate()); Date closedDate = dFormat.parse(post.getClosedDate()); long diffInMillies = closedDate.getTime() - creationDate.getTime(); if (TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS) <= TOO_LONG_FILTER) diffLongs.add(TimeUnit.SECONDS.convert(diffInMillies, TimeUnit.MILLISECONDS)); } catch (ParseException e) { e.printStackTrace(); } }); for (int i = 0; i < diffLongs.size(); i++) avgTime = ((avgTime * i) + diffLongs.get(i)) / (i + 1); System.out.println("Average time in seconds: " + avgTime); System.out.println("(Minutes: " + TimeUnit.MINUTES.convert(avgTime, TimeUnit.SECONDS) + ")"); System.out.println("(Hours: " + TimeUnit.HOURS.convert(avgTime, TimeUnit.SECONDS) + ")"); System.out.println("(Days: " + TimeUnit.DAYS.convert(avgTime, TimeUnit.SECONDS) + ")"); } private void mostRecentBadges() { SortedMap<String, Date> mEarliestBadge = new TreeMap<String, Date>(); DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // Since we are working with a small dataset, some badge users won't be on the database... datastore.createQuery(Badges.class).filter("UserId <", "2000000").project("Name", true).project("UserId", true) .fetch(new FindOptions().batchSize(25000)).iterator() .forEachRemaining(badge -> { try { if (!Character.isUpperCase(badge.getName().charAt(0))) return; Date theDate = dFormat.parse(badge.getUserId().getCreationDate()); if (!mEarliestBadge.containsKey(badge.getName())) mEarliestBadge.put(badge.getName(), theDate); else if (mEarliestBadge.get(badge.getName()).before(theDate)) mEarliestBadge.put(badge.getName(), theDate); } catch(Exception e) { e.printStackTrace(); } }); for (String badge : mEarliestBadge.keySet()) System.out.println(badge + ": " + mEarliestBadge.get(badge)); } public static void main(String[] args) { StackOverflowDataManagement manager = new StackOverflowDataManagement("localhost", "stackoverflow"); manager.startDemo(); } }
mit
jchudb93/DP1WMS
DP1WMS/src/main/java/com/dp1wms/model/Rack.java
2058
package com.dp1wms.model; import javafx.geometry.Point2D; import org.postgresql.geometric.PGpoint; import java.util.ArrayList; import java.util.List; public class Rack { private int idRack; private int idArea; private Point2D posicionInicial; private Point2D posicionFinal; private int altura; private int longitudCajon; private List<Cajon> listaCajones = new ArrayList<Cajon>(); private String codigo; public Rack(){ } public int getIdRack() { return idRack; } public void setIdRack(int idRack) { this.idRack = idRack; } public int getIdArea() { return idArea; } public void setIdArea(int idArea) { this.idArea = idArea; } public Point2D getPosicionInicial() { return posicionInicial; } public void setPosicionInicial(Point2D posicionInicial) { this.posicionInicial = posicionInicial; } public void setPosicionInicial(PGpoint posicionInicial) { this.posicionInicial = new Point2D(posicionInicial.x, posicionInicial.y); } public Point2D getPosicionFinal() { return posicionFinal; } public void setPosicionFinal(Point2D posicionFinal) { this.posicionFinal = posicionFinal; } public void setPosicionFinal(PGpoint posicionFinal) { this.posicionFinal = new Point2D(posicionFinal.x, posicionFinal.y); } public int getAltura() { return altura; } public void setAltura(int altura) { this.altura = altura; } public int getLongitudCajon() { return longitudCajon; } public void setLongitudCajon(int longitudCajon) { this.longitudCajon = longitudCajon; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public List<Cajon> getListaCajones() { return listaCajones; } public void setListaCajones(List<Cajon> listaCajones) { this.listaCajones = listaCajones; } }
mit
ohjay/Thoughtful.jar
Thoughtful/TextBundle.java
586
package Thoughtful; /** * A POJO containing a line (String) and a few formatting flags (booleans). * @author Owen Jow */ public class TextBundle { String text; boolean centered, scroll; /** * Constructs a TextBundle, acting under the assumption * that there are no special formatting options to be set. */ public TextBundle(String text) { this.text = text; } public TextBundle(String text, boolean centered, boolean scroll) { this.text = text; this.centered = centered; this.scroll = scroll; } }
mit
kamcio96/SpongeCommon
src/main/java/org/spongepowered/common/world/gen/SpongeGenerationPopulator.java
6613
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.world.gen; import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.GenericMath; import com.flowpowered.math.vector.Vector3i; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.world.extent.ImmutableBiomeArea; import org.spongepowered.api.world.extent.MutableBlockVolume; import org.spongepowered.api.world.gen.GenerationPopulator; /** * Generator populator that wraps a Minecraft {@link IChunkProvider}. */ public final class SpongeGenerationPopulator implements GenerationPopulator { private final IChunkProvider chunkGenerator; private final World world; /** * Gets the {@link GenerationPopulator} from the given * {@link IChunkProvider}. If the chunk provider wraps a * {@link GenerationPopulator}, that populator is returned, otherwise the * chunk provider is wrapped. * * @param world The world the chunk generator is bound to. * @param chunkGenerator The chunk generator. * @return The generator populator. */ public static GenerationPopulator of(World world, IChunkProvider chunkGenerator) { if (chunkGenerator instanceof GenerationPopulator) { return (GenerationPopulator) chunkGenerator; } if (chunkGenerator instanceof SpongeChunkProvider) { return ((SpongeChunkProvider) chunkGenerator).getBaseGenerationPopulator(); } return new SpongeGenerationPopulator(world, chunkGenerator); } private SpongeGenerationPopulator(World world, IChunkProvider chunkGenerator) { this.world = checkNotNull(world, "world"); this.chunkGenerator = checkNotNull(chunkGenerator, "chunkGenerator"); } @Override public void populate(org.spongepowered.api.world.World world, MutableBlockVolume buffer, ImmutableBiomeArea biomes) { Vector3i min = buffer.getBlockMin(); Vector3i max = buffer.getBlockMax(); // The block buffer can be of any size. We generate all chunks that // have at least part of the chunk in the given area, and copy the // needed blocks into the buffer int minChunkX = GenericMath.floor(min.getX() / 16.0); int minChunkZ = GenericMath.floor(min.getZ() / 16.0); int maxChunkX = GenericMath.floor(max.getX() / 16.0); int maxChunkZ = GenericMath.floor(max.getZ() / 16.0); for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { final Chunk generated = this.chunkGenerator.provideChunk(chunkX, chunkZ); placeChunkInBuffer(generated, buffer, chunkX, chunkZ); } } } private void placeChunkInBuffer(Chunk chunk, MutableBlockVolume buffer, int chunkX, int chunkZ) { // Calculate bounds int xOffset = chunkX * 16; int zOffset = chunkZ * 16; Vector3i minBound = buffer.getBlockMin(); Vector3i maxBound = buffer.getBlockMax(); int xInChunkStart = Math.max(0, minBound.getX() - xOffset); int yStart = Math.max(0, minBound.getY()); int zInChunkStart = Math.max(0, minBound.getZ() - zOffset); int xInChunkEnd = Math.min(15, maxBound.getX() - xOffset); int yEnd = Math.min(255, maxBound.getY()); int zInChunkEnd = Math.min(15, maxBound.getZ() - zOffset); // Copy the right blocks in ExtendedBlockStorage[] blockStorage = chunk.getBlockStorageArray(); for (ExtendedBlockStorage miniChunk : blockStorage) { if (miniChunk == null) { continue; } int yOffset = miniChunk.getYLocation(); int yInChunkStart = Math.max(0, yStart); int yInChunkEnd = Math.min(15, yEnd); for (int xInChunk = xInChunkStart; xInChunk <= xInChunkEnd; xInChunk++) { for (int yInChunk = yInChunkStart; yInChunk <= yInChunkEnd; yInChunk++) { for (int zInChunk = zInChunkStart; zInChunk <= zInChunkEnd; zInChunk++) { buffer.setBlock(xOffset + xInChunk, yOffset + yInChunk, zOffset + zInChunk, (BlockState) miniChunk.get(xInChunk, yInChunk, zInChunk)); } } } } } /** * Gets the chunk provider, if the target world matches the world this chunk * provider was bound to. * * @param targetWorld The target world. * @return The chunk provider. * @throws IllegalArgumentException If the target world is not the world * this chunk provider is bound to.` */ public IChunkProvider getHandle(World targetWorld) { if (!this.world.equals(targetWorld)) { throw new IllegalArgumentException("Cannot reassign internal generator from world " + getWorldName(this.world) + " to world " + getWorldName(targetWorld)); } return this.chunkGenerator; } private static String getWorldName(World world) { return ((org.spongepowered.api.world.World) world).getName(); } }
mit
lolopasdugato/MCWarClan
MCWarClan/src/com/github/lolopasdugato/mcwarclan/Settings.java
7784
package com.github.lolopasdugato.mcwarclan; import org.bukkit.configuration.Configuration; import java.util.Iterator; import java.util.Set; /** * Created by Loïc on 11/04/2014. */ public class Settings { public static int maxNumberOfTeam; public static int initialTeamSize; public static boolean friendlyFire; public static boolean seeInvisibleTeamMates; public static int initialRadius; public static int radiusHQBonus; public static int barbariansSpawnDistance; public static int baseMinHQDistanceToOthers; public static int uncensoredItemsAmount; public static String classicWorldName; public static boolean debugMode; public static boolean randomBarbarianSpawn; public static Cost BLUEteamJoiningTribute; public static Cost REDteamJoiningTribute; public static Cost DEFAULTteamJoiningTribute; public static Cost teamCreatingTribute; public static Cost baseInitialCost; public static boolean matesNeededIgnore; public static int matesNeededValue; public static boolean matesNeededIsPercentage; public static boolean obsidianBreakable; public static int secureBarbarianDistance; public static boolean allowCreeperDestroyFields; public static int destroyFlagPercentage; public static Cost baseCreationCostSystematicIncrease; public static int numberOfBaseForVariant; public static Cost baseVariantIncrease; public static int[] radiusCost; public static int moneyloss; public static int waitingTime; public static int emeraldPerTeamMember; private Configuration _cfg; ////////////////////////////////////////////////////////////////////////////// //------------------------------- Constructors ------------------------------- ////////////////////////////////////////////////////////////////////////////// /** * Classic Settings constructor. * * @param cfg */ public Settings(Configuration cfg) { _cfg = cfg; } ////////////////////////////////////////////////////////////////////////////// //--------------------------------- Functions -------------------------------- ////////////////////////////////////////////////////////////////////////////// /** * Use to load config.yml * * @return if the loadConfig failed, return false. */ public boolean loadConfig() { maxNumberOfTeam = secureValue(_cfg.getInt("teamSettings.maxNumberOfTeam"), 4, TeamManager.MAXTEAMSIZE); initialTeamSize = secureValue(_cfg.getInt("teamSettings.initialTeamSize"), 2, -1); friendlyFire = _cfg.getBoolean("teamSettings.friendlyFire"); seeInvisibleTeamMates = _cfg.getBoolean("teamSettings.transparentMates"); matesNeededIgnore = _cfg.getBoolean("teamSettings.matesNeeded.ignore"); matesNeededIsPercentage = _cfg.getBoolean("teamSettings.matesNeeded.percentage"); if(matesNeededIsPercentage) matesNeededValue = secureValue(_cfg.getInt("teamSettings.matesNeeded.value"), 0, 100); else matesNeededValue = secureValue(_cfg.getInt("teamSettings.matesNeeded.value"), 0, -1); emeraldPerTeamMember = secureValue(_cfg.getInt("teamSettings.emeraldPerTeamMembers"), 0, -1); initialRadius = secureValue(_cfg.getInt("baseSettings.initialRadius"), 5, -1); radiusHQBonus = secureValue(_cfg.getInt("baseSettings.radiusHQBonus"), 5, -1); barbariansSpawnDistance = secureValue(_cfg.getInt("baseSettings.barbariansSpawnDistance"), 100, -1); baseMinHQDistanceToOthers = secureValue(_cfg.getInt("baseSettings.baseMinHQDistanceToOthers"), 0, -1); secureBarbarianDistance = secureValue(_cfg.getInt("baseSettings.secureBarbarianDistance"), 0, -1); destroyFlagPercentage = secureValue(_cfg.getInt("baseSettings.destroyFlagPercentage"), 25, 100); numberOfBaseForVariant = secureValue(_cfg.getInt("baseSettings.numberOfBaseForVariant"), 1, -1); radiusCost = new int[4]; radiusCost[0] = secureValue(_cfg.getInt("baseSettings.radiusCostPerLevel.LEVEL_2"), 0, -1); radiusCost[1] = secureValue(_cfg.getInt("baseSettings.radiusCostPerLevel.LEVEL_3"), radiusCost[0], -1); radiusCost[2] = secureValue(_cfg.getInt("baseSettings.radiusCostPerLevel.LEVEL_4"), radiusCost[1], -1); radiusCost[3] = secureValue(_cfg.getInt("baseSettings.radiusCostPerLevel.LEVEL_5"), radiusCost[2], -1); moneyloss = secureValue(_cfg.getInt("baseSettings.moneyloss"), 10, 50); uncensoredItemsAmount = secureValue(_cfg.getInt("otherSettings.uncensoredItemsAmount"), 1, -1); classicWorldName = _cfg.getString("otherSettings.classicWorldName"); debugMode = _cfg.getBoolean("otherSettings.debugMode"); randomBarbarianSpawn = _cfg.getBoolean("otherSettings.randomBarbarianSpawn"); obsidianBreakable = _cfg.getBoolean("otherSettings.obsidianBreakable"); allowCreeperDestroyFields = _cfg.getBoolean("otherSettings.allowCreeperDestroyFields"); waitingTime = secureValue(_cfg.getInt("otherSettings.waitingTime"), 1, -1); // Initializing blue entry cost BLUEteamJoiningTribute = fillCost(BLUEteamJoiningTribute, "teamSettings.teamJoiningTribute.BLUE"); if (BLUEteamJoiningTribute == null) return false; // Initializing red entry cost REDteamJoiningTribute = fillCost(REDteamJoiningTribute, "teamSettings.teamJoiningTribute.RED"); if (REDteamJoiningTribute == null) return false; // Initializing default team entry cost DEFAULTteamJoiningTribute = fillCost(DEFAULTteamJoiningTribute, "teamSettings.teamJoiningTribute.DEFAULT"); if (DEFAULTteamJoiningTribute == null) return false; // Initializing team creation cost teamCreatingTribute = fillCost(teamCreatingTribute, "teamSettings.teamCreatingTribute"); if (teamCreatingTribute == null) return false; // Initializing base cost baseInitialCost = fillCost(baseInitialCost, "baseSettings.baseInitialCost"); if (baseInitialCost == null) return false; // Initialize base cost increase baseCreationCostSystematicIncrease = fillCost(baseCreationCostSystematicIncrease, "baseSettings.baseCreationCostSystematicIncrease"); if (baseCreationCostSystematicIncrease == null) return false; baseVariantIncrease = fillCost(baseVariantIncrease, "baseSettings.baseVariantIncrease"); if (baseVariantIncrease == null) return false; return true; } /** * Used to fill a cost. * * @param toFill, is the cost to fill. * @param path used to find values in config.yml. * @return Return a cost that has been filled up or null if error while reading file. */ public Cost fillCost(Cost toFill, String path) { toFill = new Cost(); Set<String> keys = _cfg.getConfigurationSection(path).getKeys(false); Iterator it = keys.iterator(); while (it.hasNext()) { String matName = (String) it.next(); int matNumber = secureValue(_cfg.getInt(path + "." + matName), 0, -1); if (!toFill.addValue(matName, matNumber)) Messages.sendMessage("Material '" + matName + "' unrecognized in config.yml, ignoring it...", Messages.messageType.ALERT, null); } return toFill; } private int secureValue(int valueToSecure, int minValue, int maxValue){ if (valueToSecure > maxValue && maxValue != -1) valueToSecure = maxValue; if (valueToSecure < minValue && minValue != -1) valueToSecure = minValue; return valueToSecure; } }
mit
danidemi/jlubricant
jlubricant-utils/src/main/java/com/danidemi/jlubricant/utils/classes/ClassCollector.java
554
package com.danidemi.jlubricant.utils.classes; import java.util.LinkedHashSet; import java.util.Set; /** A {@link Visitor} that just stores found classes. */ public class ClassCollector implements Visitor { LinkedHashSet<Class> foundClasses; public ClassCollector() { foundClasses = new LinkedHashSet<>(0); } @Override public void onFoundClass(Class foundClass) { foundClasses.add(foundClass); } @Override public void onError(String className) { // nothing to do } public Set<Class> getClasses() { return foundClasses; } }
mit
HerrB92/obp
OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/cache/RegionFactory.java
1268
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.cache; /** * @author Steve Ebersole * * @deprecated Moved, but still need this definition for ehcache */ @Deprecated public interface RegionFactory extends org.hibernate.cache.spi.RegionFactory { }
mit
SCIP-Interfaces/JSCIPOpt
java/jscip/SWIGTYPE_p_p_SCIP_VAR.java
756
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package jscip; public class SWIGTYPE_p_p_SCIP_VAR { private transient long swigCPtr; protected SWIGTYPE_p_p_SCIP_VAR(long cPtr, @SuppressWarnings("unused") boolean futureUse) { swigCPtr = cPtr; } protected SWIGTYPE_p_p_SCIP_VAR() { swigCPtr = 0; } protected static long getCPtr(SWIGTYPE_p_p_SCIP_VAR obj) { return (obj == null) ? 0 : obj.swigCPtr; } }
mit
adelinacaramet/refactoring-workshop
user-service/java/src/main/java/userservice/domain/model/UserBuilder.java
2263
package userservice.domain.model; public class UserBuilder { private long id; private String username; private String password; private String email; private String firstName; private String lastName; private String phone; private String streetName; private String streetNumber; private String postalCode; private String city; private String country; private boolean enabled; public User build() { final User user = new User(); user.setId(id); user.setUsername(username); user.setPassword(password); user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); user.setPhone(phone); user.setStreetName(streetName); user.setStreetNumber(streetNumber); user.setPostalCode(postalCode); user.setCity(city); user.setCountry(country); user.setEnabled(enabled); return user; } public UserBuilder withId(final long id) { this.id = id; return this; } public UserBuilder withUsername(final String username) { this.username = username; return this; } public UserBuilder withPassword(final String password) { this.password = password; return this; } public UserBuilder withEmail(final String email) { this.email = email; return this; } public UserBuilder withFirstName(final String firstName) { this.firstName = firstName; return this; } public UserBuilder withLastName(final String lastName) { this.lastName = lastName; return this; } public UserBuilder withPhone(final String phone) { this.phone = phone; return this; } public UserBuilder withEnabled(final boolean enabled) { this.enabled = enabled; return this; } public UserBuilder withAddress(final String streetName, final String streetNumber, final String postCode, final String city, final String country) { this.streetName = streetName; this.streetNumber = streetNumber; this.postalCode = postCode; this.city = city; this.country = country; return this; } }
mit
Hu3bl/statsbot
statsbot-parent/statsbot-module.messages.model/src/main/java/MessagesModel/impl/TeamScoredMessageImpl.java
6413
/** */ package MessagesModel.impl; import MessagesModel.ModelPackage; import MessagesModel.TeamScoredMessage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Team Scored Message</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link MessagesModel.impl.TeamScoredMessageImpl#getTeam <em>Team</em>}</li> * <li>{@link MessagesModel.impl.TeamScoredMessageImpl#getScore <em>Score</em>}</li> * <li>{@link MessagesModel.impl.TeamScoredMessageImpl#getPlayers <em>Players</em>}</li> * </ul> * * @generated */ public class TeamScoredMessageImpl extends MessageImpl implements TeamScoredMessage { /** * The default value of the '{@link #getTeam() <em>Team</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTeam() * @generated * @ordered */ protected static final String TEAM_EDEFAULT = null; /** * The cached value of the '{@link #getTeam() <em>Team</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTeam() * @generated * @ordered */ protected String team = TEAM_EDEFAULT; /** * The default value of the '{@link #getScore() <em>Score</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getScore() * @generated * @ordered */ protected static final String SCORE_EDEFAULT = null; /** * The cached value of the '{@link #getScore() <em>Score</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getScore() * @generated * @ordered */ protected String score = SCORE_EDEFAULT; /** * The default value of the '{@link #getPlayers() <em>Players</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPlayers() * @generated * @ordered */ protected static final String PLAYERS_EDEFAULT = null; /** * The cached value of the '{@link #getPlayers() <em>Players</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPlayers() * @generated * @ordered */ protected String players = PLAYERS_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TeamScoredMessageImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ModelPackage.Literals.TEAM_SCORED_MESSAGE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getTeam() { return team; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTeam(String newTeam) { String oldTeam = team; team = newTeam; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.TEAM_SCORED_MESSAGE__TEAM, oldTeam, team)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getScore() { return score; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setScore(String newScore) { String oldScore = score; score = newScore; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.TEAM_SCORED_MESSAGE__SCORE, oldScore, score)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getPlayers() { return players; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPlayers(String newPlayers) { String oldPlayers = players; players = newPlayers; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.TEAM_SCORED_MESSAGE__PLAYERS, oldPlayers, players)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ModelPackage.TEAM_SCORED_MESSAGE__TEAM: return getTeam(); case ModelPackage.TEAM_SCORED_MESSAGE__SCORE: return getScore(); case ModelPackage.TEAM_SCORED_MESSAGE__PLAYERS: return getPlayers(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ModelPackage.TEAM_SCORED_MESSAGE__TEAM: setTeam((String)newValue); return; case ModelPackage.TEAM_SCORED_MESSAGE__SCORE: setScore((String)newValue); return; case ModelPackage.TEAM_SCORED_MESSAGE__PLAYERS: setPlayers((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ModelPackage.TEAM_SCORED_MESSAGE__TEAM: setTeam(TEAM_EDEFAULT); return; case ModelPackage.TEAM_SCORED_MESSAGE__SCORE: setScore(SCORE_EDEFAULT); return; case ModelPackage.TEAM_SCORED_MESSAGE__PLAYERS: setPlayers(PLAYERS_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ModelPackage.TEAM_SCORED_MESSAGE__TEAM: return TEAM_EDEFAULT == null ? team != null : !TEAM_EDEFAULT.equals(team); case ModelPackage.TEAM_SCORED_MESSAGE__SCORE: return SCORE_EDEFAULT == null ? score != null : !SCORE_EDEFAULT.equals(score); case ModelPackage.TEAM_SCORED_MESSAGE__PLAYERS: return PLAYERS_EDEFAULT == null ? players != null : !PLAYERS_EDEFAULT.equals(players); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (team: "); result.append(team); result.append(", score: "); result.append(score); result.append(", players: "); result.append(players); result.append(')'); return result.toString(); } } //TeamScoredMessageImpl
mit
pwall567/javautil
src/main/java/net/pwall/util/package-info.java
1325
/* * @(#) net.pwall.util.package-info.java * * javautil Java Utility Library * Copyright (c) 2013, 2014, 2015, 2016, 2017 Peter Wall * * 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. */ /** * Utility classes. * * @author Peter Wall */ package net.pwall.util;
mit
relson/nfscan
02-Sourcecode/nfscan-server/src/main/java/cc/nfscan/server/service/s3/S3Retrieve.java
1794
package cc.nfscan.server.service.s3; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; import org.springframework.beans.factory.annotation.Autowired; import java.io.BufferedInputStream; /** * Class that integrates with AWS S3 service. * This service is in charge of retrieve objects from a bucket * * @author Paulo Miguel Almeida <a href="http://github.com/PauloMigAlmeida">@PauloMigAlmeida</a> */ abstract class S3Retrieve { /** * BasicAWSCredentials instance */ @Autowired private BasicAWSCredentials awsCredentials; /** * Gets the input stream containing the contents of this object. * <p/> * <p> * <b>Note</b>: The method is a simple getter and does not actually create a * stream. If you retrieve an S3Object, you should close this input stream * as soon as possible, because the object contents aren't buffered in * memory and stream directly from Amazon S3. Further, failure to close this * stream can cause the request pool to become blocked. * </p> * * @param bucketName bucket name * @param key object key * @return An input stream containing the contents of this object. */ protected BufferedInputStream startDownload(String bucketName, String key) { AmazonS3 s3 = new AmazonS3Client(awsCredentials); S3Object object = s3.getObject(bucketName, key); S3ObjectInputStream inputStream = object.getObjectContent(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); return bufferedInputStream; } }
mit
tmikov/c99
java/c99j/src/c99/parser/ast/AstN.java
388
package c99.parser.ast; public class AstN extends Ast { private final Ast ch[]; public AstN ( final String name, final Ast... ch ) { super( name ); this.ch = ch; } @Override public int childCount () { return ch.length; } @Override public Ast child ( final int n ) { return ch[n]; } @Override public void setChild ( final int n, final Ast v ) { this.ch[n] = v; } } // class
mit
PyroclastIO/pyroclast-java
src/main/java/io/pyroclast/pyroclastjava/v1/topic/TopicRecord.java
1257
package io.pyroclast.pyroclastjava.v1.topic; import io.pyroclast.pyroclastjava.v1.topic.deserializers.TopicRecordDeserializer; import java.util.Map; import org.codehaus.jackson.map.annotate.JsonDeserialize; @JsonDeserialize(using = TopicRecordDeserializer.class) public class TopicRecord { private final String topic; private final String key; private final long partition; private final long offset; private final long timestamp; private final Map<Object, Object> value; public TopicRecord(String topic, String key, long partition, long offset, long timestamp, Map<Object, Object> value) { this.topic = topic; this.key = key; this.partition = partition; this.offset = offset; this.timestamp = timestamp; this.value = value; } public String getTopic() { return this.topic; } public String getKey() { return this.key; } public long getPartition() { return this.partition; } public long getOffset() { return this.offset; } public long getTimestamp() { return this.timestamp; } public Map<Object, Object> getValue() { return this.value; } }
mit
TeamWizardry/TMT-Refraction
src/main/java/com/teamwizardry/refraction/api/lib/LibOreDict.java
518
package com.teamwizardry.refraction.api.lib; /** * @author WireSegal * Created at 11:28 AM on 1/4/17. */ public final class LibOreDict { public static final String REFLECTIVE_ALLOY = "ingotReflectiveAlloy"; public static final String REFLECTIVE_ALLOY_BLOCK = "blockReflectiveAlloy"; public static final String LENS = "lensGlass"; public static final String OPTIC_FIBER = "opticFiber"; public static final String TRANSLOCATOR = "laserTranslocator"; private LibOreDict() { // NOT CONSTRUCTABLE } }
mit
comp500/SimpleProcessors
src/main/java/link/infra/simpleprocessors/blocks/programmer/ProgrammerTileEntity.java
6557
package link.infra.simpleprocessors.blocks.programmer; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import link.infra.simpleprocessors.items.Processor; import link.infra.simpleprocessors.network.PacketHandler; import link.infra.simpleprocessors.network.PacketProgrammerAction.ProgrammerAction; import link.infra.simpleprocessors.network.PacketUpCode; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ProgrammerTileEntity extends TileEntity { public static final String TEST_DIR = "E:/test"; public boolean canInteractWith(EntityPlayer playerIn) { // If we are too far away from this tile entity you cannot use it return !isInvalid() && playerIn.getDistanceSq(pos.add(0.5D, 0.5D, 0.5D)) <= 64D; } private NBTTagCompound storageMap; public String getFile(String file) { return storageMap.getString(file); } public HashMap<String, Integer> getFileList() { if (storageMap == null || storageMap.hasNoTags()) { return new HashMap<String, Integer>(); } else { HashMap<String, Integer> tempMap = new HashMap<String, Integer>(); for (String s : storageMap.getKeySet()) { tempMap.put(s, storageMap.getString(s).length()); } return tempMap; } } public void setFile(String file, String data) { this.storageMap.setString(file, data); markDirty(); if (world != null) { IBlockState state = world.getBlockState(getPos()); world.notifyBlockUpdate(getPos(), state, state, 3); } } @Override public NBTTagCompound getUpdateTag() { // getUpdateTag() is called whenever the chunkdata is sent to the // client. In contrast getUpdatePacket() is called when the tile entity // itself wants to sync to the client. In many cases you want to send // over the same information in getUpdateTag() as in getUpdatePacket(). NBTTagCompound nbtTag = new NBTTagCompound(); this.writeToNBT(nbtTag); return writeToNBT(new NBTTagCompound()); } @Override public SPacketUpdateTileEntity getUpdatePacket() { // Prepare a packet for syncing our TE to the client. Since we only have to sync the stack // and that's all we have we just write our entire NBT here. If you have a complex // tile entity that doesn't need to have all information on the client you can write // a more optimal NBT here. NBTTagCompound nbtTag = new NBTTagCompound(); this.writeToNBT(nbtTag); return new SPacketUpdateTileEntity(getPos(), 1, nbtTag); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) { // Here we get the packet from the server and read it into our client side tile entity this.readFromNBT(packet.getNbtCompound()); } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); if (compound.hasKey("storage")) { storageMap = compound.getCompoundTag("storage"); } else { storageMap = new NBTTagCompound(); } } @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { super.writeToNBT(compound); if (!storageMap.hasNoTags()) { compound.setTag("storage", storageMap); } return compound; } @SideOnly(Side.CLIENT) public void openLocal() { for (String s : storageMap.getKeySet()) { try { // TODO: Create required folders, and check for ..\ String[] fileArray = storageMap.getString(s).split("\n"); List<String> fileArrayList = Arrays.asList(fileArray); Files.write(Paths.get(TEST_DIR, s), fileArrayList, StandardCharsets.UTF_8); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidPathException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @SideOnly(Side.CLIENT) public void readLocal() { Path p = Paths.get(TEST_DIR); ProgrammerFileVisitor fv = new ProgrammerFileVisitor(); try { EnumSet<FileVisitOption> opts = EnumSet.noneOf(FileVisitOption.class); Files.walkFileTree(p, opts, 100, fv); } catch (IOException e) { e.printStackTrace(); } if (fv.pendingMap.size() > 0) { storageMap = new NBTTagCompound(); for (String name : fv.pendingMap.keySet()) { storageMap.setString(name, fv.pendingMap.get(name)); System.out.println(name); } // send files to server, as NBT can't be updated on client // TODO: Split into small packets for files that can't fit in one PacketHandler.INSTANCE.sendToServer(new PacketUpCode(storageMap, pos)); } } public void setStorageMap(NBTTagCompound map) { // TODO: Check size, to prevent breaking stuff on server storageMap = map; markDirty(); if (world != null) { IBlockState state = world.getBlockState(getPos()); world.notifyBlockUpdate(getPos(), state, state, 3); } } public void serverAction(ProgrammerAction action, Container openContainer) { ItemStack stack = openContainer.getSlot(0).getStack(); if (stack == ItemStack.EMPTY) return; switch (action) { case FLASH_PROCESSOR: // TODO Check size < processor size if (!stack.isEmpty() && stack.getItem() instanceof Processor) { // ensure it's still a processor if (!storageMap.hasNoTags()) { // if it don't got no tags ((Processor) stack.getItem()).flashStack(stack, storageMap); // flash it } } break; case WIPE_PROCESSOR: if (!stack.isEmpty() && stack.getItem() instanceof Processor) { // ensure it's still a processor ((Processor) stack.getItem()).wipeStack(stack); // wipe it } break; } } }
mit
Shahriar07/ExpenseTracker
app/src/main/java/com/shahriar/hasan/monthlyexpenserecorder/contorller/AddBudgetController.java
1130
package com.shahriar.hasan.monthlyexpenserecorder.contorller; import com.shahriar.hasan.monthlyexpenserecorder.data.BudgetData; import com.shahriar.hasan.monthlyexpenserecorder.data.CategoryData; import com.shahriar.hasan.monthlyexpenserecorder.enums.CategoryTypeEnum; import com.shahriar.hasan.monthlyexpenserecorder.services.BudgetService; import com.shahriar.hasan.monthlyexpenserecorder.services.CategoryService; import java.util.ArrayList; /** * Created by H. M. Shahriar on 10/12/2017. */ public class AddBudgetController { CategoryService categoryService; BudgetService budgetService; public AddBudgetController(){ categoryService = new CategoryService(); budgetService = new BudgetService(); } public ArrayList<CategoryData> getIncomeCategoryList(){ return categoryService.getAllCategory(CategoryTypeEnum.INCOME_CATEGORY); } public ArrayList<CategoryData> getExpenseCategoryList(){ return categoryService.getAllCategory(CategoryTypeEnum.EXPENSE_CATEGORY); } public void addBudget(BudgetData data){ budgetService.addBudget(data); } }
mit
normalian/ApplicationInsights-Java
core/src/test/java/com/microsoft/applicationinsights/internal/config/TelemetryConfigurationFactoryTest.java
18228
/* * ApplicationInsights-Java * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * 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 com.microsoft.applicationinsights.internal.config; import java.lang.reflect.Field; import java.util.*; import com.microsoft.applicationinsights.TelemetryConfiguration; import com.microsoft.applicationinsights.channel.concrete.inprocess.InProcessTelemetryChannel; import com.microsoft.applicationinsights.extensibility.TelemetryModule; import com.microsoft.applicationinsights.internal.channel.stdout.StdOutChannel; import com.microsoft.applicationinsights.internal.annotation.PerformanceModule; import com.microsoft.applicationinsights.internal.perfcounter.PerformanceCounterConfigurationAware; import com.microsoft.applicationinsights.internal.reflect.ClassDataUtils; import com.microsoft.applicationinsights.internal.reflect.ClassDataVerifier; import org.mockito.Mockito; import static org.mockito.Matchers.anyString; import org.junit.Test; import org.junit.Assert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public final class TelemetryConfigurationFactoryTest { private final static String MOCK_IKEY = "c9341531-05ac-4d8c-972e-36e97601d5ff"; private final static String MOCK_ENDPOINT = "MockEndpoint"; private final static String NON_VALID_URL = "http:sd{@~fsd.s.d.f;fffff"; private final static String APP_INSIGHTS_IKEY_TEST_VALUE = "ds"; @PerformanceModule static final class MockPerformanceModule implements TelemetryModule, PerformanceCounterConfigurationAware { public boolean initializeWasCalled = false; public boolean addConfigurationDataWasCalled = false; @Override public void initialize(TelemetryConfiguration configuration) { initializeWasCalled = true; } @Override public void addConfigurationData(PerformanceCountersXmlElement configuration) { addConfigurationDataWasCalled = true; } } @PerformanceModule static final class MockPerformanceBadModule { public boolean initializeWasCalled = false; public void initialize(TelemetryConfiguration configuration) { initializeWasCalled = true; } } @Test public void configurationWithNullIkeyTest() { ikeyTest(null, null); } @Test public void configurationWithEmptykeyTest() { ikeyTest("", null); } @Test public void configurationWithBlankStringIkeyTest() { ikeyTest(" ", null); } @Test public void configurationWithRedundantSpacesIkeyTest() { ikeyTest(" " + MOCK_IKEY + " \t", MOCK_IKEY); } @Test public void configurationWithOnlyRedundantSpacesIkeyTest() { ikeyTest(" \t", null); } @Test public void systemPropertyIKeyBeforeConfigurationIKeyTest() { try { System.setProperty(TelemetryConfigurationFactory.EXTERNAL_PROPERTY_IKEY_NAME, APP_INSIGHTS_IKEY_TEST_VALUE); ikeyTest(MOCK_IKEY, APP_INSIGHTS_IKEY_TEST_VALUE); } finally { // Avoid any influence on other unit tests System.getProperties().remove(TelemetryConfigurationFactory.EXTERNAL_PROPERTY_IKEY_NAME); } } @Test public void testWithEmptySections() { AppInsightsConfigurationBuilder mockParser = Mockito.mock(AppInsightsConfigurationBuilder.class); ApplicationInsightsXmlConfiguration appConf = new ApplicationInsightsXmlConfiguration(); appConf.setInstrumentationKey(MOCK_IKEY); appConf.setTelemetryInitializers(null); appConf.setContextInitializers(null); appConf.setModules(null); appConf.setSdkLogger(null); Mockito.doReturn(appConf).when(mockParser).build(anyString()); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertEquals(mockConfiguration.getInstrumentationKey(), MOCK_IKEY); assertEquals(mockConfiguration.getContextInitializers().size(), 2); assertTrue(mockConfiguration.getChannel() instanceof InProcessTelemetryChannel); } @Test public void testTelemetryContextInitializers() { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); TelemetryInitializersXmlElement telemetryInitializersXmlElement = new TelemetryInitializersXmlElement(); ArrayList<AddTypeXmlElement> contexts = new ArrayList<AddTypeXmlElement>(); AddTypeXmlElement addXmlElement = new AddTypeXmlElement(); addXmlElement.setType("com.microsoft.applicationinsights.extensibility.initializer.TimestampPropertyInitializer"); contexts.add(addXmlElement); telemetryInitializersXmlElement.setAdds(contexts); appConf.setTelemetryInitializers(telemetryInitializersXmlElement); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertEquals(mockConfiguration.getInstrumentationKey(), MOCK_IKEY); assertEquals(mockConfiguration.getContextInitializers().size(), 2); assertEquals(mockConfiguration.getTelemetryInitializers().size(), 1); assertTrue(mockConfiguration.getChannel() instanceof StdOutChannel); } @Test public void testTelemetryModulesWithoutParameters() { MockTelemetryModule module = generateTelemetryModules(false); Assert.assertNotNull(module); Assert.assertNull(module.getParam1()); } @Test public void testTelemetryModulesWithParameters() { MockTelemetryModule module = generateTelemetryModules(true); Assert.assertNotNull(module); Assert.assertEquals("value1", module.getParam1()); } @Test public void testContextInitializers() { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); ContextInitializersXmlElement contextInitializersXmlElement = new ContextInitializersXmlElement(); ArrayList<AddTypeXmlElement> contexts = new ArrayList<AddTypeXmlElement>(); AddTypeXmlElement addXmlElement = new AddTypeXmlElement(); addXmlElement.setType("com.microsoft.applicationinsights.extensibility.initializer.DeviceInfoContextInitializer"); contexts.add(addXmlElement); contextInitializersXmlElement.setAdds(contexts); appConf.setContextInitializers(contextInitializersXmlElement); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertEquals(mockConfiguration.getInstrumentationKey(), MOCK_IKEY); assertEquals(mockConfiguration.getContextInitializers().size(), 3); assertTrue(mockConfiguration.getTelemetryInitializers().isEmpty()); assertTrue(mockConfiguration.getChannel() instanceof StdOutChannel); } @Test public void testInitializeWithFailingParse() throws Exception { AppInsightsConfigurationBuilder mockParser = createMockParserThatFailsToParse(); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertTrue(mockConfiguration.getChannel() instanceof InProcessTelemetryChannel); } @Test public void testInitializeWithNullGetInstrumentationKey() throws Exception { AppInsightsConfigurationBuilder mockParser = createMockParser(false, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertTrue(mockConfiguration.getChannel() instanceof InProcessTelemetryChannel); } @Test public void testInitializeWithEmptyGetInstrumentationKey() throws Exception { AppInsightsConfigurationBuilder mockParser = createMockParser(false, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(""); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertTrue(mockConfiguration.getChannel() instanceof InProcessTelemetryChannel); } @Test public void testInitializeAllDefaults() throws Exception { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.isTrackingDisabled(), false); assertEquals(mockConfiguration.getInstrumentationKey(), MOCK_IKEY); assertEquals(mockConfiguration.getContextInitializers().size(), 2); assertTrue(mockConfiguration.getTelemetryInitializers().isEmpty()); assertTrue(mockConfiguration.getChannel() instanceof StdOutChannel); } @Test public void testDefaultChannelWithData() { AppInsightsConfigurationBuilder mockParser = createMockParserWithDefaultChannel(true); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); appConf.getChannel().setDeveloperMode(true); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.getChannel().isDeveloperMode(), true); } @Test public void testDefaultChannelWithBadData() { AppInsightsConfigurationBuilder mockParser = createMockParserWithDefaultChannel(true); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); ChannelXmlElement channelXmlElement = appConf.getChannel(); channelXmlElement.setEndpointAddress(NON_VALID_URL); channelXmlElement.setDeveloperMode(true); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.getChannel().isDeveloperMode(), false); } private MockTelemetryModule generateTelemetryModules(boolean addParameter) { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, false); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); TelemetryModulesXmlElement modulesXmlElement = new TelemetryModulesXmlElement(); ArrayList<AddTypeXmlElement> modules = new ArrayList<AddTypeXmlElement>(); AddTypeXmlElement addXmlElement = new AddTypeXmlElement(); addXmlElement.setType("com.microsoft.applicationinsights.internal.config.MockTelemetryModule"); if (addParameter) { final ParamXmlElement param1 = new ParamXmlElement(); param1.setName("param1"); param1.setValue("value1"); ArrayList<ParamXmlElement> list = new ArrayList<ParamXmlElement>(); list.add(param1); addXmlElement.setParameters(list); } modules.add(addXmlElement); modulesXmlElement.setAdds(modules); appConf.setModules(modulesXmlElement); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); MockTelemetryModule module = (MockTelemetryModule)mockConfiguration.getTelemetryModules().get(0); return module; } private AppInsightsConfigurationBuilder createMockParserThatFailsToParse() { AppInsightsConfigurationBuilder mockParser = Mockito.mock(AppInsightsConfigurationBuilder.class); Mockito.doReturn(null).when(mockParser).build(anyString()); return mockParser; } private AppInsightsConfigurationBuilder createMockParserWithDefaultChannel(boolean withChannel) { return createMockParser(withChannel, false, false); } // Suppress non relevant warning due to mockito internal stuff @SuppressWarnings("unchecked") private AppInsightsConfigurationBuilder createMockParser(boolean withChannel, boolean setChannel, boolean withPerformanceModules) { AppInsightsConfigurationBuilder mockParser = Mockito.mock(AppInsightsConfigurationBuilder.class); ApplicationInsightsXmlConfiguration appConf = new ApplicationInsightsXmlConfiguration(); appConf.setSdkLogger(new SDKLoggerXmlElement()); if (withChannel) { ChannelXmlElement channelXmlElement = new ChannelXmlElement(); channelXmlElement.setEndpointAddress(MOCK_ENDPOINT); String channelType = null; if (setChannel) { channelType = "com.microsoft.applicationinsights.internal.channel.stdout.StdOutChannel"; channelXmlElement.setType(channelType); } appConf.setChannel(channelXmlElement); } if (withPerformanceModules) { PerformanceCountersXmlElement performanceCountersXmlElement = new PerformanceCountersXmlElement(); appConf.setPerformance(performanceCountersXmlElement); } Mockito.doReturn(appConf).when(mockParser).build(anyString()); return mockParser; } @Test public void testPerformanceModules() { AppInsightsConfigurationBuilder mockParser = createMockParser(true, true, true); ApplicationInsightsXmlConfiguration appConf = mockParser.build(""); appConf.setInstrumentationKey(MOCK_IKEY); appConf.getChannel().setDeveloperMode(true); TelemetryConfigurationFactory.INSTANCE.setPerformanceCountersSection("com.microsoft.applicationinsights.internal.config"); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.getTelemetryModules().size(), 1); assertTrue(mockConfiguration.getTelemetryModules().get(0) instanceof MockPerformanceModule); assertTrue(((MockPerformanceModule)mockConfiguration.getTelemetryModules().get(0)).initializeWasCalled); assertTrue(((MockPerformanceModule)mockConfiguration.getTelemetryModules().get(0)).addConfigurationDataWasCalled); } private void initializeWithFactory(AppInsightsConfigurationBuilder mockParser, TelemetryConfiguration mockConfiguration) { Field field = null; try { field = ClassDataUtils.class.getDeclaredField("verifier"); field.setAccessible(true); ClassDataVerifier mockVerifier = Mockito.mock(ClassDataVerifier.class); Mockito.doReturn(true).when(mockVerifier).verifyClassExists(anyString()); field.set(ClassDataUtils.INSTANCE, mockVerifier); TelemetryConfigurationFactory.INSTANCE.setBuilder(mockParser); TelemetryConfigurationFactory.INSTANCE.initialize(mockConfiguration); } catch (NoSuchFieldException e) { throw new RuntimeException(); } catch (IllegalAccessException e) { throw new RuntimeException(); } } private void ikeyTest(String configurationIkey, String expectedIkey) { // Make sure that there is no exception when fetching the i-key by having both // the i-key and channel in the configuration, otherwise the channel won't be instantiated AppInsightsConfigurationBuilder mockParser = createMockParser(true, false, false); ApplicationInsightsXmlConfiguration appConf = new ApplicationInsightsXmlConfiguration(); appConf.setInstrumentationKey(configurationIkey); Mockito.doReturn(appConf).when(mockParser).build(anyString()); TelemetryConfiguration mockConfiguration = new TelemetryConfiguration(); initializeWithFactory(mockParser, mockConfiguration); assertEquals(mockConfiguration.getInstrumentationKey(), expectedIkey); assertTrue(mockConfiguration.getChannel() instanceof InProcessTelemetryChannel); } }
mit
reasonml-editor/reasonml-idea-plugin
src/com/reason/ide/js/ORJsLibraryManager.java
6164
package com.reason.ide.js; import static com.intellij.openapi.vfs.VirtualFile.EMPTY_ARRAY; import static com.intellij.util.ArrayUtilRt.EMPTY_STRING_ARRAY; import static com.intellij.webcore.libraries.ScriptingLibraryModel.LibraryLevel.PROJECT; import com.intellij.lang.javascript.library.JSLibraryManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupActivity; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.webcore.libraries.ScriptingLibraryModel; import com.reason.Log; import com.reason.bs.BsConfig; import com.reason.bs.BsConfigReader; import com.reason.ide.ORProjectManager; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.jetbrains.annotations.NotNull; public class ORJsLibraryManager implements StartupActivity, DumbAware { private static final Log LOG = Log.create("activity.js.lib"); private static final String LIB_NAME = "Bucklescript"; @Override public void runActivity(@NotNull Project project) { DumbService.getInstance(project).smartInvokeLater(() -> runActivityLater(project)); } private void runActivityLater(@NotNull Project project) { LOG.info("run Js library manager"); Optional<VirtualFile> bsConfigFileOptional = ORProjectManager.findFirstBsConfigurationFile(project); if (bsConfigFileOptional.isPresent()) { VirtualFile bsConfigFile = bsConfigFileOptional.get(); LOG.debug("bucklescript config file", bsConfigFile); String baseDir = "file://" + bsConfigFile.getParent().getPath() + "/node_modules/"; List<VirtualFile> sources = new ArrayList<>(readBsConfigDependencies(project, baseDir, bsConfigFile)); JSLibraryManager jsLibraryManager = JSLibraryManager.getInstance(project); ScriptingLibraryModel bucklescriptModel = jsLibraryManager.getLibraryByName(LIB_NAME); if (bucklescriptModel == null) { LOG.debug("Creating js library", LIB_NAME); jsLibraryManager.createLibrary( LIB_NAME, sources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY, PROJECT, true); } else { LOG.debug("Updating js library", LIB_NAME); jsLibraryManager.updateLibrary( LIB_NAME, LIB_NAME, sources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY); } WriteCommandAction.runWriteCommandAction(project, (Runnable) jsLibraryManager::commitChanges); } } private @NotNull List<VirtualFile> readBsConfigDependencies( @NotNull Project project, @NotNull String nodeModulesDir, @NotNull VirtualFile bsConfigFile) { List<VirtualFile> result = new ArrayList<>(); LOG.debug("Read deps from", bsConfigFile); VirtualFilePointerManager vFilePointerManager = VirtualFilePointerManager.getInstance(); BsConfig bsConfig = BsConfigReader.read(bsConfigFile); JSLibraryManager jsLibraryManager = JSLibraryManager.getInstance(project); Disposable disposable = Disposer.newDisposable(jsLibraryManager, "ORJsLibraryManager"); try { for (String dependency : bsConfig.getDependencies()) { String depDirUrl = nodeModulesDir + dependency; VirtualFilePointer dirPointer = vFilePointerManager.create( depDirUrl, disposable, new VirtualFilePointerListener() { @Override public void validityChanged(@NotNull VirtualFilePointer[] pointers) { if (LOG.isDebugEnabled()) { LOG.debug("validity changed for " + pointers[0]); } ScriptingLibraryModel bucklescriptModel = jsLibraryManager.getLibraryByName(LIB_NAME); if (bucklescriptModel != null) { List<VirtualFile> changedSources = new ArrayList<>(bucklescriptModel.getSourceFiles()); if (pointers[0].isValid()) { VirtualFile dirFile = pointers[0].getFile(); changedSources.add(dirFile); if (dirFile != null) { VirtualFile bsConfigDepFile = dirFile.findChild("bsconfig.json"); if (bsConfigDepFile != null) { changedSources.addAll( readBsConfigDependencies(project, nodeModulesDir, bsConfigDepFile)); } } jsLibraryManager.updateLibrary( LIB_NAME, LIB_NAME, changedSources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY); WriteCommandAction.runWriteCommandAction( project, (Runnable) jsLibraryManager::commitChanges); } else { System.out.println("removed " + pointers[0]); } } } }); VirtualFile dirFile = dirPointer.getFile(); if (dirFile != null) { result.add(dirFile); if (dirFile.isValid()) { VirtualFile bsConfigDepFile = dirFile.findChild("bsconfig.json"); if (bsConfigDepFile != null) { result.addAll(readBsConfigDependencies(project, nodeModulesDir, bsConfigDepFile)); } } } } } finally { disposable.dispose(); } return result; } }
mit
lijianhu1/japi
java/client/src/main/java/com/dounine/japi/core/impl/BuiltInJavaImpl.java
2845
package com.dounine.japi.core.impl; import com.dounine.japi.JapiClient; import com.dounine.japi.core.IBuiltIn; import com.dounine.japi.exception.JapiException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by huanghuanlai on 2017/1/19. */ public class BuiltInJavaImpl implements IBuiltIn { private static final Logger LOGGER = LoggerFactory.getLogger(BuiltInJavaImpl.class); private static String[] builtInPaths; private static List<String> types; private static File builtInFile; private static final BuiltInJavaImpl builtIn = new BuiltInJavaImpl(); private BuiltInJavaImpl() { if (null == builtInFile) { URL url = JapiClient.class.getResource("/class-builtIn-types.txt"); builtInFile = new File(url.getFile()); if (!builtInFile.exists()) { url = JapiClient.class.getResource("/japi/class-builtIn-types.txt"); builtInFile = new File(url.getFile()); } if(!builtInFile.exists()){ String err = url.getFile() + " 文件不存在"; LOGGER.error(err); throw new JapiException(err); } builtInPaths = new String[]{url.getFile()}; } } public static BuiltInJavaImpl getInstance(){ return builtIn; } @Override public List<String> getBuiltInTypes() { if (null == builtInPaths || (null != builtInPaths && builtInPaths.length == 0)) { String err = "builtInPaths 不能为空,至少有一个文件"; LOGGER.error(err); throw new JapiException(err); } if (null != types) { return types; } try { types = new ArrayList<>(); String typesStr = FileUtils.readFileToString(builtInFile, Charset.forName("utf-8")); typesStr = typesStr.replaceAll("\\s", "");//去掉回车 types.addAll(Arrays.asList(typesStr.split(","))); } catch (IOException e) { LOGGER.error(e.getMessage()); } return types; } public boolean isBuiltInType(String keyType) { List<String> keyTypes = getBuiltInTypes(); boolean isBuiltIn = false; for(String key : keyTypes){ if(key.equals(keyType)||key.endsWith(keyType)||keyType.equals(key+"[]")||(key+"[]").endsWith(keyType)){ isBuiltIn = true; break; } } return isBuiltIn; } public void setBuiltInPaths(String[] builtInPaths) { this.builtInPaths = builtInPaths; } }
mit
vincentzhang96/WahrBot
WahrDiscordApi/src/main/java/co/phoenixlab/discord/api/entities/TokenResponse.java
1363
/* * The MIT License (MIT) * * Copyright (c) 2016 Vincent Zhang/PhoenixLAB * * 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 co.phoenixlab.discord.api.entities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public class TokenResponse { private String token; }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/java/awt/event/InvocationEvent.java
16523
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1998, 2013. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.awt.event; import sun.awt.AWTAccessor; import java.awt.ActiveEvent; import java.awt.AWTEvent; /** * An event which executes the <code>run()</code> method on a <code>Runnable * </code> when dispatched by the AWT event dispatcher thread. This class can * be used as a reference implementation of <code>ActiveEvent</code> rather * than declaring a new class and defining <code>dispatch()</code>.<p> * * Instances of this class are placed on the <code>EventQueue</code> by calls * to <code>invokeLater</code> and <code>invokeAndWait</code>. Client code * can use this fact to write replacement functions for <code>invokeLater * </code> and <code>invokeAndWait</code> without writing special-case code * in any <code>AWTEventListener</code> objects. * <p> * An unspecified behavior will be caused if the {@code id} parameter * of any particular {@code InvocationEvent} instance is not * in the range from {@code INVOCATION_FIRST} to {@code INVOCATION_LAST}. * * @author Fred Ecks * @author David Mendenhall * * @see java.awt.ActiveEvent * @see java.awt.EventQueue#invokeLater * @see java.awt.EventQueue#invokeAndWait * @see AWTEventListener * * @since 1.2 */ public class InvocationEvent extends AWTEvent implements ActiveEvent { static { AWTAccessor.setInvocationEventAccessor(new AWTAccessor.InvocationEventAccessor() { @Override public void dispose(InvocationEvent invocationEvent) { invocationEvent.finishedDispatching(false); } }); } /** * Marks the first integer id for the range of invocation event ids. */ public static final int INVOCATION_FIRST = 1200; /** * The default id for all InvocationEvents. */ public static final int INVOCATION_DEFAULT = INVOCATION_FIRST; /** * Marks the last integer id for the range of invocation event ids. */ public static final int INVOCATION_LAST = INVOCATION_DEFAULT; /** * The Runnable whose run() method will be called. */ protected Runnable runnable; /** * The (potentially null) Object whose notifyAll() method will be called * immediately after the Runnable.run() method has returned or thrown an exception * or after the event was disposed. * * @see #isDispatched */ protected volatile Object notifier; /** * The (potentially null) Runnable whose run() method will be called * immediately after the event was dispatched or disposed. * * @see #isDispatched * @since 1.8 */ private final Runnable listener; /** * Indicates whether the <code>run()</code> method of the <code>runnable</code> * was executed or not. * * @see #isDispatched * @since 1.7 */ private volatile boolean dispatched = false; /** * Set to true if dispatch() catches Throwable and stores it in the * exception instance variable. If false, Throwables are propagated up * to the EventDispatchThread's dispatch loop. */ protected boolean catchExceptions; /** * The (potentially null) Exception thrown during execution of the * Runnable.run() method. This variable will also be null if a particular * instance does not catch exceptions. */ private Exception exception = null; /** * The (potentially null) Throwable thrown during execution of the * Runnable.run() method. This variable will also be null if a particular * instance does not catch exceptions. */ private Throwable throwable = null; /** * The timestamp of when this event occurred. * * @serial * @see #getWhen */ private long when; /* * JDK 1.1 serialVersionUID. */ private static final long serialVersionUID = 436056344909459450L; /** * Constructs an <code>InvocationEvent</code> with the specified * source which will execute the runnable's <code>run</code> * method when dispatched. * <p>This is a convenience constructor. An invocation of the form * <tt>InvocationEvent(source, runnable)</tt> * behaves in exactly the same way as the invocation of * <tt>{@link #InvocationEvent(Object, Runnable, Object, boolean) InvocationEvent}(source, runnable, null, false)</tt>. * <p> This method throws an <code>IllegalArgumentException</code> * if <code>source</code> is <code>null</code>. * * @param source The <code>Object</code> that originated the event * @param runnable The <code>Runnable</code> whose <code>run</code> * method will be executed * @throws IllegalArgumentException if <code>source</code> is null * * @see #getSource() * @see #InvocationEvent(Object, Runnable, Object, boolean) */ public InvocationEvent(Object source, Runnable runnable) { this(source, INVOCATION_DEFAULT, runnable, null, null, false); } /** * Constructs an <code>InvocationEvent</code> with the specified * source which will execute the runnable's <code>run</code> * method when dispatched. If notifier is non-<code>null</code>, * <code>notifyAll()</code> will be called on it * immediately after <code>run</code> has returned or thrown an exception. * <p>An invocation of the form <tt>InvocationEvent(source, * runnable, notifier, catchThrowables)</tt> * behaves in exactly the same way as the invocation of * <tt>{@link #InvocationEvent(Object, int, Runnable, Object, boolean) InvocationEvent}(source, InvocationEvent.INVOCATION_DEFAULT, runnable, notifier, catchThrowables)</tt>. * <p>This method throws an <code>IllegalArgumentException</code> * if <code>source</code> is <code>null</code>. * * @param source The <code>Object</code> that originated * the event * @param runnable The <code>Runnable</code> whose * <code>run</code> method will be * executed * @param notifier The {@code Object} whose <code>notifyAll</code> * method will be called after * <code>Runnable.run</code> has returned or * thrown an exception or after the event was * disposed * @param catchThrowables Specifies whether <code>dispatch</code> * should catch Throwable when executing * the <code>Runnable</code>'s <code>run</code> * method, or should instead propagate those * Throwables to the EventDispatchThread's * dispatch loop * @throws IllegalArgumentException if <code>source</code> is null * * @see #getSource() * @see #InvocationEvent(Object, int, Runnable, Object, boolean) */ public InvocationEvent(Object source, Runnable runnable, Object notifier, boolean catchThrowables) { this(source, INVOCATION_DEFAULT, runnable, notifier, null, catchThrowables); } /** * Constructs an <code>InvocationEvent</code> with the specified * source which will execute the runnable's <code>run</code> * method when dispatched. If listener is non-<code>null</code>, * <code>listener.run()</code> will be called immediately after * <code>run</code> has returned, thrown an exception or the event * was disposed. * <p>This method throws an <code>IllegalArgumentException</code> * if <code>source</code> is <code>null</code>. * * @param source The <code>Object</code> that originated * the event * @param runnable The <code>Runnable</code> whose * <code>run</code> method will be * executed * @param listener The <code>Runnable</code>Runnable whose * <code>run()</code> method will be called * after the {@code InvocationEvent} * was dispatched or disposed * @param catchThrowables Specifies whether <code>dispatch</code> * should catch Throwable when executing * the <code>Runnable</code>'s <code>run</code> * method, or should instead propagate those * Throwables to the EventDispatchThread's * dispatch loop * @throws IllegalArgumentException if <code>source</code> is null */ public InvocationEvent(Object source, Runnable runnable, Runnable listener, boolean catchThrowables) { this(source, INVOCATION_DEFAULT, runnable, null, listener, catchThrowables); } /** * Constructs an <code>InvocationEvent</code> with the specified * source and ID which will execute the runnable's <code>run</code> * method when dispatched. If notifier is non-<code>null</code>, * <code>notifyAll</code> will be called on it immediately after * <code>run</code> has returned or thrown an exception. * <p>This method throws an * <code>IllegalArgumentException</code> if <code>source</code> * is <code>null</code>. * * @param source The <code>Object</code> that originated * the event * @param id An integer indicating the type of event. * For information on allowable values, see * the class description for {@link InvocationEvent} * @param runnable The <code>Runnable</code> whose * <code>run</code> method will be executed * @param notifier The <code>Object</code> whose <code>notifyAll</code> * method will be called after * <code>Runnable.run</code> has returned or * thrown an exception or after the event was * disposed * @param catchThrowables Specifies whether <code>dispatch</code> * should catch Throwable when executing the * <code>Runnable</code>'s <code>run</code> * method, or should instead propagate those * Throwables to the EventDispatchThread's * dispatch loop * @throws IllegalArgumentException if <code>source</code> is null * @see #getSource() * @see #getID() */ protected InvocationEvent(Object source, int id, Runnable runnable, Object notifier, boolean catchThrowables) { this(source, id, runnable, notifier, null, catchThrowables); } private InvocationEvent(Object source, int id, Runnable runnable, Object notifier, Runnable listener, boolean catchThrowables) { super(source, id); this.runnable = runnable; this.notifier = notifier; this.listener = listener; this.catchExceptions = catchThrowables; this.when = System.currentTimeMillis(); } /** * Executes the Runnable's <code>run()</code> method and notifies the * notifier (if any) when <code>run()</code> has returned or thrown an exception. * * @see #isDispatched */ public void dispatch() { try { if (catchExceptions) { try { runnable.run(); } catch (Throwable t) { if (t instanceof Exception) { exception = (Exception) t; } throwable = t; } } else { runnable.run(); } } finally { finishedDispatching(true); } } /** * Returns any Exception caught while executing the Runnable's <code>run() * </code> method. * * @return A reference to the Exception if one was thrown; null if no * Exception was thrown or if this InvocationEvent does not * catch exceptions */ public Exception getException() { return (catchExceptions) ? exception : null; } /** * Returns any Throwable caught while executing the Runnable's <code>run() * </code> method. * * @return A reference to the Throwable if one was thrown; null if no * Throwable was thrown or if this InvocationEvent does not * catch Throwables * @since 1.5 */ public Throwable getThrowable() { return (catchExceptions) ? throwable : null; } /** * Returns the timestamp of when this event occurred. * * @return this event's timestamp * @since 1.4 */ public long getWhen() { return when; } /** * Returns {@code true} if the event is dispatched or any exception is * thrown while dispatching, {@code false} otherwise. The method should * be called by a waiting thread that calls the {@code notifier.wait()} method. * Since spurious wakeups are possible (as explained in {@link Object#wait()}), * this method should be used in a waiting loop to ensure that the event * got dispatched: * <pre> * while (!event.isDispatched()) { * notifier.wait(); * } * </pre> * If the waiting thread wakes up without dispatching the event, * the {@code isDispatched()} method returns {@code false}, and * the {@code while} loop executes once more, thus, causing * the awakened thread to revert to the waiting mode. * <p> * If the {@code notifier.notifyAll()} happens before the waiting thread * enters the {@code notifier.wait()} method, the {@code while} loop ensures * that the waiting thread will not enter the {@code notifier.wait()} method. * Otherwise, there is no guarantee that the waiting thread will ever be woken * from the wait. * * @return {@code true} if the event has been dispatched, or any exception * has been thrown while dispatching, {@code false} otherwise * @see #dispatch * @see #notifier * @see #catchExceptions * @since 1.7 */ public boolean isDispatched() { return dispatched; } /** * Called when the event was dispatched or disposed * @param dispatched true if the event was dispatched * false if the event was disposed */ private void finishedDispatching(boolean dispatched) { this.dispatched = dispatched; if (notifier != null) { synchronized (notifier) { notifier.notifyAll(); } } if (listener != null) { listener.run(); } } /** * Returns a parameter string identifying this event. * This method is useful for event-logging and for debugging. * * @return A string identifying the event and its attributes */ public String paramString() { String typeStr; switch(id) { case INVOCATION_DEFAULT: typeStr = "INVOCATION_DEFAULT"; break; default: typeStr = "unknown type"; } return typeStr + ",runnable=" + runnable + ",notifier=" + notifier + ",catchExceptions=" + catchExceptions + ",when=" + when; } }
mit
nicholaswilde/MyFirstApp
app/src/main/java/com/example/nwilde/myfirstapp/ImageGallery.java
3774
package com.example.nwilde.myfirstapp; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import com.example.nwilde.myfirstapp.database.ImageBaseHelper; import com.example.nwilde.myfirstapp.database.ImageCursorWrapper; import com.example.nwilde.myfirstapp.database.ImageDbSchema.ImageTable; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ImageGallery { private static ImageGallery sImageGallery; private Context mContext; private SQLiteDatabase mDatabase; public static ImageGallery get(Context context) { if (sImageGallery == null) { sImageGallery = new ImageGallery(context); } return sImageGallery; } private ImageGallery(Context context) { mContext = context.getApplicationContext(); mDatabase = new ImageBaseHelper(mContext) .getWritableDatabase(); } public void addImage(Image image) { ContentValues values = getContentValues(image); mDatabase.insert(ImageTable.NAME, null, values); } public List<Image> getImages() { List<Image> images = new ArrayList<>(); ImageCursorWrapper cursor = queryImages(null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { images.add(cursor.getImage()); cursor.moveToNext(); } cursor.close(); return images; } public Image getImage(UUID id) { ImageCursorWrapper cursor = queryImages( ImageTable.Cols.UUID + " = ?", new String[]{id.toString()} ); try { if (cursor.getCount() == 0) { return null; } cursor.moveToFirst(); return cursor.getImage(); } finally { cursor.close(); } } public File getPhotoFile(Image image) { File externalFilesDir = mContext .getExternalFilesDir(Environment.DIRECTORY_PICTURES); if (externalFilesDir == null) { return null; } return new File(externalFilesDir, image.getPhotoFilename()); } public void updateImage(Image image) { String uuidString = image.getId().toString(); ContentValues values = getContentValues(image); mDatabase.update(ImageTable.NAME, values, ImageTable.Cols.UUID + " = ?", new String[] { uuidString } ); } private static ContentValues getContentValues(Image image) { ContentValues values = new ContentValues(); values.put(ImageTable.Cols.UUID, image.getId().toString()); values.put(ImageTable.Cols.TITLE, image.getTitle()); values.put(ImageTable.Cols.DATE, image.getDate().getTime()); values.put(ImageTable.Cols.SOLVED, image.isSolved() ? 1 : 0); values.put(ImageTable.Cols.SUSPECT, image.getSuspect()); values.put(ImageTable.Cols.SIZE, image.getFileSize()); values.put(ImageTable.Cols.FILENAME, image.getFileName()); values.put(ImageTable.Cols.FILEPATH, image.getFilePath()); return values; } private ImageCursorWrapper queryImages(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query( ImageTable.NAME, null, // Columns - null selects all columns whereClause, whereArgs, null, // groupBy null, // having null // orderBy ); return new ImageCursorWrapper(cursor); } }
mit
BinEP/Games
Games/src/networkGoFish/GoFishWindow.java
18637
package networkGoFish; import goFishCommons.Button; import goFishCommons.Card; import java.awt.*; import java.awt.event.*; import javax.swing.*; import utilityClasses.*; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import netgame.common.*; /** * This window represents one player in a two-player networked game of * TicTacToe. The window is meant to be created by the program * netgame.tictactoe.Main. */ public class GoFishWindow extends JFrame { /** * The state of the game. This state is a copy of the official state, which * is stored on the server. When the state changes, the state is sent as a * message to this window. (It is actually sent to the TicTacToeClient * object that represents the connection to the server.) When that happens, * the state that was received in the message replaces the value of this * variable, and the board and UI is updated to reflect the changed state. * This is done in the newState() method, which is called by the * TicTacToeClient object. */ private GoFishGameState state; private Board board; // A panel that displays the board. The user // makes moves by clicking on this panel. private JLabel message; // Displays messages to the user about the status of // the game. private int myID; // The ID number that identifies the player using this public boolean cheat = true; // window. private String customFontName; private Font customFont; private static final String Font_File_Name = "joystix"; private GoFishClient connection; // The Client object for sending and // receiving // network messages. /** * This class defines the client object that handles communication with the * Hub. */ private class GoFishClient extends Client { /** * Connect to the hub at a specified host name and port number. */ public GoFishClient(String hubHostName, int hubPort) throws IOException { super(hubHostName, hubPort); } /** * Responds to a message received from the Hub. The only messages that * are supported are TicTacToeGameState objects. When one is received, * the newState() method in the TicTacToeWindow class is called. To * avoid problems with synchronization, that method is called using * SwingUtilities.invokeLater() so that it will run in the GUI event * thread. */ protected void messageReceived(final Object message) { if (message instanceof GoFishGameState) { SwingUtilities.invokeLater(new Runnable() { public void run() { // calls a method at the end of the // TicTacToeWindow class newState((GoFishGameState) message); } }); } } /** * If a shutdown message is received from the Hub, the user is notified * and the program ends. */ protected void serverShutdown(String message) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane .showMessageDialog(GoFishWindow.this, "Your opponent has disconnected.\nThe game is ended."); System.exit(0); } }); } } /** * A JPanel that draws the TicTacToe board. */ private class Board extends JPanel { // Defines the board object protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); if (state == null || state.startGame) { g.setColor(Color.WHITE); // g.setFont(new Font("Joystix", Font.BOLD, 60)); // g.setFont(new Font(customFont.getFamily(), Font.BOLD, 60)); g.setFont(new Font(customFontName, Font.BOLD, 60)); // g.setFont(customFont.deriveFont(Font.BOLD, 60)); CenteredText.draw("GO FISH!!", 500, 500, g, true, 230); g.setFont(new Font(customFontName, Font.BOLD, 20)); // CenteredText.draw("Press Enter to", 500, // 500, g, true, 350); // CenteredText.draw("Start", 500, 500, g, // true, 380); if (state == null) { CenteredText.draw( "Waiting for Others...", 500, 500, g, true, 440); } else { CenteredText.draw( state.messageFromServer[0], 500, 500, g, true, 320); CenteredText.draw( state.messageFromServer[1], 500, 500, g, true, 350); } } if (state == null || state.hands == null || state.deck == null) { // g.drawString("Starting up.", 20, 35); // System.out.println("waiting"); return; } if (state.playing) { drawPlayerHand(myID - 1, g, 350); // drawPlayerHand(1, g, 10); // drawPlayerHand(2, g, 350); state.button.get(0).drawRectangle(g); state.button.get(1).drawRectangle(g); g.setColor(Color.YELLOW); g.fillRect(10, 40 + ((state.turn == myID) ? 1 : 0) * 350, 10, 30); g.setColor(Color.WHITE); CenteredText.draw("" + state.restOfDeck.get(myID - 1).size(), new Rectangle(170, 270, 60, 50), g); CenteredText.draw("" + state.restOfDeck.get((myID == 1) ? 1 : 0).size(), new Rectangle(270, 270, 60, 50), g); CenteredText.draw("P" + myID, new Rectangle(170, 240, 60, 50), g); CenteredText.draw("P" + ((myID == 1) ? 2 : 1), new Rectangle(270, 220, 60, 50), g); // g.drawString(leftPairs.text, 170 + leftPairs.x, 270); // g.drawString(rightPairs.text, 270 + rightPairs.x, 270); // // g.drawString(leftPairNum.text, 170 + leftPairNum.x, 240); // g.drawString(rightPairNum.text, 270 + rightPairNum.x, 240); drawHandCover((myID == 1) ? 2 : 1, g); g.setColor(Color.WHITE); g.setFont(new Font(customFontName, Font.PLAIN, 15)); if (state != null) { CenteredText.draw( state.messageFromServer[1], 500, 500, g, true, 140); CenteredText.draw( state.messageFromServer[0], 500, 500, g, true, 170); } } else if (state.endGame) { g.setColor(Color.WHITE); g.setFont(new Font(customFontName, Font.BOLD, 60)); CenteredText.draw("Player " + state.winner, 500, 500, g, true, 130); CenteredText.draw("Wins!!", 500, 500, g, true, 210); g.setFont(new Font(customFontName, Font.BOLD, 26)); CenteredText.draw("Click to Restart", 500, 500, g, true, 350); } } public void drawHandCover(int pNum, Graphics g) { ArrayList<Card> hand = state.hands.get(pNum - 1); int y = 10; int i = 0; int startX = 20; int spacing = getSpacing(hand); for (Card card : hand) { int x = getXCenter(hand, startX) + (spacing * i); g.setColor(Color.BLUE); g.fillRoundRect(x, y, 56, 100, 5, 5); g.drawRoundRect(x, y, 56, 100, 5, 5); g.setColor(Color.BLACK); g.drawRoundRect(x, y, 56, 100, 5, 5); i++; } } public int getXCenter(ArrayList<Card> hand, int startX) { int size = hand.size(); if (size > 7) size = 7; int width = size * 62 - 6; startX += (460 - width) / 2; return startX; } public int getSpacing(ArrayList<Card> hand) { if (hand.size() < 8) return 62; int size = hand.size() + 1; int cardWidth = size * 56; int space = 460 - cardWidth; return (int) (56 + space / (size - 1)); } public void drawPlayerHand(int pNum, Graphics g, int startY) { ArrayList<Card> hand = state.hands.get(pNum); g.setFont(new Font(customFontName, Font.BOLD, 20)); int i = 0; int startX = 20; int spacing = getSpacing(hand); for (Card card : hand) { int x = getXCenter(hand, startX) + (spacing * i); int y = startY; g.setColor(card.getColor()); g.fillRoundRect(x, y, 56, 100, 5, 5); g.drawRoundRect(x, y, 56, 100, 5, 5); g.setColor(Color.BLACK); g.drawRoundRect(x, y, 56, 100, 5, 5); g.setColor((card.getSuit() % 2 == 0) ? Color.RED : Color.BLACK); CenteredText.draw(card.getCardFace() + card.getSuitIcon(), new Rectangle(x, y + 56, 56, 100), g); // g.drawString(card.getCardFace() + card.getSuitIcon(), // x + out.x, y + 56); state.hands.get(myID - 1).get(i).setRectangle(x, y, 56, 100); i++; } } } public void makeCustomFont(String fontPath) { try { fontPath = "Fonts/" + fontPath + ".ttf"; InputStream fontStream = new BufferedInputStream( new FileInputStream(fontPath)); GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment(); customFont = Font.createFont(Font.TRUETYPE_FONT, fontStream) .deriveFont(Font.BOLD); ge.registerFont(customFont); customFontName = customFont.getFamily(); String[] defaultFonts = { "Serif", "SansSerif", "Monospace", "Dialog", "DialogInput" }; for (int i = 0; i < defaultFonts.length; i++) { if (customFontName.contains(defaultFonts[i])) { customFontName = customFontName.substring(0, customFontName.indexOf(defaultFonts[i]) - 1); } } } catch (Exception e) { e.printStackTrace(); } } public boolean checkIfValidPairs(ArrayList<Card> selectedCards) { boolean allSame = true; int i = 1; while (i < selectedCards.size() && allSame) { allSame = allSame && selectedCards.get(i - 1).getCard() == selectedCards.get( i).getCard(); i++; } return allSame && selectedCards.size() > 1; } public ArrayList<Card> getSelected() { ArrayList<Card> selected = new ArrayList<Card>(); for (Card currentCard : state.hands.get(myID - 1)) { if (currentCard.selected) selected.add(currentCard); } return selected; } public void goFish() { if (!state.deck.isEmpty()) { state.hands.get(myID - 1).add(state.deck.get(0)); state.deck.remove(0); } else { int highestPairs = 0; int highestPlayer = 0; int i = 1; for (ArrayList<Card> playerPairs : state.restOfDeck) { if (playerPairs.size() > highestPairs) { highestPairs = playerPairs.size(); highestPlayer = i; } i++; } setWon(highestPlayer); } sortCards(); } /** * Creates and configures the window, opens a connection to the server, and * makes the widow visible on the screen. This constructor can block until * the connection is established. * * @param hostName * the name or IP address of the host where the server is * running. * @param serverPortNumber * the port number on the server computer when the Hub is * listening for connections. * @throws IOException * if some I/O error occurs while trying to open the connection. * @throws Client.DuplicatePlayerNameException * it playerName is already in use by another player in the * game. */ public GoFishWindow(String hostName, int serverPortNumber) throws IOException { super("Network Go Fish"); connection = new GoFishClient(hostName, serverPortNumber); myID = connection.getID(); makeCustomFont(Font_File_Name); board = new Board(); message = new JLabel("Waiting for two players to connect.", JLabel.CENTER); board.setBackground(Color.BLACK); board.setPreferredSize(new Dimension(500, 500)); board.addMouseListener(new MouseAdapter() { // A mouse listener to // respond to user's clicks. public void mousePressed(MouseEvent evt) { doMouseClick(evt.getX(), evt.getY()); } }); board.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_C) { cheat = !cheat; } } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }); message.setBackground(Color.LIGHT_GRAY); message.setOpaque(true); JPanel content = new JPanel(); content.setLayout(new BorderLayout(2, 2)); content.setBorder(BorderFactory.createLineBorder(Color.GRAY, 2)); content.setBackground(Color.GRAY); content.add(board, BorderLayout.CENTER); content.add(message, BorderLayout.SOUTH); setContentPane(content); pack(); setResizable(false); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { // When the user clicks the window's close box, this listener will // send a disconnect message to the Hub and will end the program. // The other player will then be notified that this player has // disconnected. public void windowClosing(WindowEvent evt) { dispose(); connection.disconnect(); // Send a disconnect message to the // hub. try { Thread.sleep(333); // Wait one-half second to allow the // message to be sent. } catch (InterruptedException e) { } System.exit(0); } }); setLocation(30, 100); setVisible(true); board.repaint(); } public boolean checkIfWon() { int i = 1; for (ArrayList<Card> hand : state.hands) { if (hand.isEmpty()) { setWon(i); return true; } i++; } return false; } public void asking() { if (!getSelected().isEmpty()) { Card selectedCard = getSelected().get(0); ArrayList<Card> matchingCards = new ArrayList<Card>(); int i = 0; for (ArrayList<Card> currentHand : state.hands) { if (i != myID - 1) { for (Card currentCard : currentHand) { if (selectedCard.getCard() == currentCard.getCard()) matchingCards.add(currentCard); } } for (Card matchCard : matchingCards) { currentHand.remove(matchCard); } i++; } state.hands.get(myID - 1).addAll(matchingCards); sortCards(); newMessageLog("Player " + myID + " asked for a " + selectedCard.getCardFace()); if (matchingCards.isEmpty()) nextTurn(); } } public void setWon(int i) { state.winner = i; state.won = true; state.playing = false; state.endGame = true; board.repaint(); connection.send(state); } public void nextTurn() { goFish(); // sortCards(); state.turn++; if (state.turn > state.numOfPlayers) state.turn = 1; newMessageLog("Player " + myID + " drew a Card. Next player"); connection.send(state); } public void pairings() { ArrayList<Card> selectedCards = new ArrayList<Card>(); selectedCards = getSelected(); if (getSelected().size() > 2) { selectedCards.subList(2, selectedCards.size()).clear(); } if (checkIfValidPairs(selectedCards)) { for (Card currentCard : selectedCards) { state.restOfDeck.get(myID - 1).add(currentCard); for (ArrayList<Card> cardAL : state.hands) { cardAL.remove(currentCard); } } newMessageLog("Player " + myID + " paired " + selectedCards.size() + " " + selectedCards.get(0).getCardFace() + "s"); } } public void newMessageLog(String theMessage) { state.messageFromServer[1] = state.messageFromServer[0]; state.messageFromServer[0] = theMessage; } public void resetColors() { for (ArrayList<Card> currentHand : state.hands) { for (Card currentCard : currentHand) { currentCard.selected = false; currentCard.setColor(Color.WHITE); } } } public void sortCards() { for (ArrayList<Card> theCards : state.hands) { Collections.sort(theCards, Card.CardSuitComparator); Collections.sort(theCards, Card.CardNumComparator); } } /** * This method is called when the user clicks the tictactoe board. If the * click represents a legal move at a legal time, then a message is sent to * the Hub to inform it of the move. The Hub will change the game state and * send the new state to both players. It is very important that the game * clients do not change the game state directly, since the "official" game * state is maintained by the Hub. Doing things this way guarantees that * both players see the same board. */ private void doMouseClick(int x, int y) { if (!(state == null || state.hands == null || state.deck == null) && state.playing && state.turn == myID) { if (state.turn == myID) { if (!checkIfWon() && state.playing) { highlightClickedCards(x, y); doClickedButtonAction(x, y); connection.send(state); board.repaint(); } } } else if (state.endGame) { // After a game ends, the winning player -- or either // player in the event of a tie -- can start a new // game by clicking the board. When this happens, // the String "newgame" is sent as a message to Hub. if (myID == state.winner) { connection.send("newgame"); // Start a new game. } } } public void highlightClickedCards(int x, int y) { for (ArrayList<Card> aHand : state.hands) { for (Card r : aHand) { if (r.getRectangle().contains(new Point(x, y))) { r.selected = !r.selected; r.setColor((r.selected) ? Color.YELLOW : Color.WHITE); } } } } public void doClickedButtonAction(int x, int y) { for (Button b : state.button) { if (b.getButton().contains(new Point(x, y))) { if (b.getText().equals("Pair")) { pairings(); } else if (b.getText().equals("Ask")) { asking(); } resetColors(); } } } /** * This method is called when a new game state is received from the hub. It * stores the new state in the instance variable that represents the game * state and updates the user interface to reflect the state. Note that this * method is called on the GUI event thread (using * SwingUtilitites.invokeLater()) to avoid synchronization problems. * (Synchronization is an issue when a method that manipulates the GUI is * called from a thread other than the GUI event thread. In this problem, * there is also the problem that a message can actually be received before * the constructor has completed, which would lead to errors in this method * from uninitialized variables, if SwingUtilities.invokeLater() were not * used.) */ private void newState(GoFishGameState state) { if (state.playerDisconnected) { JOptionPane.showMessageDialog(this, "Your opponent has disconnected.\nThe game is ended."); System.exit(0); } this.state = state; board.repaint(); if (state.hands == null || state.deck == null) { return; // haven't started yet -- waiting for 2nd player } else if (state.endGame) { setTitle("Game Over"); if (myID == state.winner) message.setText("You won! Click to start a new game."); else message.setText("You lost. Waiting for new game..."); } else { if (myID == 1) { setTitle("You are Player " + connection.getID()); } else { setTitle("You are Player " + connection.getID()); } if (myID == state.turn) { message.setText("Your move"); } else { message.setText("Waiting for opponent's move"); } } } }
mit
brucevsked/vskeddemolist
vskeddemos/projects/cdidemo/simplecdi/src/com/vsked/test/CustomerSessionBean.java
2796
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013 Oracle and/or its affiliates. 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_1_1.html * or packager/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 packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [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.vsked.test; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.inject.Named; @Named @Stateless public class CustomerSessionBean implements Serializable{ private static final long serialVersionUID = -7172175558379712971L; public List<Name> getCustomerNames() { List<Name> names = new ArrayList<>(); names.add(new Name("Penny", "TBBT")); names.add(new Name("Sheldon", "TBBT")); names.add(new Name("Amy", "TBBT")); names.add(new Name("Leonard", "TBBT")); names.add(new Name("Bernadette", "TBBT")); names.add(new Name("Raj", "TBBT")); names.add(new Name("Priya", "TBBT")); names.add(new Name("Howard", "TBBT")); return names; } }
mit
BastyZ/RTreesImplementations
src/com/logaritmos/Test.java
1804
package com.logaritmos; import java.util.Random; public class Test { public static void main(String[] args) throws Exception { //int M = (int) args[0]; int B = 4096; //bytes max por pagina int M = 200; //cantidad de rectangulos tal que el nodo no pese mas que B int maxCord = 500000; int maxDelta = 100; Random rnd = new Random(); int m = (M * 40) / 100; // m = 40% M int left = rnd.nextInt(maxCord); int bottom = rnd.nextInt(maxCord); int deltaX = rnd.nextInt(maxDelta); int deltaY = rnd.nextInt(maxDelta); Rectangle r = new Rectangle(left, left + deltaX, bottom + deltaY, bottom); DiskController diskController = new DiskController(M); long address = diskController.memoryAssigner(); Node tree = new Root(m, M, r, diskController, address); diskController.saveNode(tree); long rootSize =diskController.getNodeSize(address); System.out.println("Tamaño de raiz : " + rootSize + " bytes"); int n=0; while (diskController.getNodeSize(address) < B){ if(n==157) { break;} n++; Rectangle rn; left = rnd.nextInt(maxCord); bottom = rnd.nextInt(maxCord); deltaX = rnd.nextInt(maxDelta); deltaY = rnd.nextInt(maxDelta); rn = new Rectangle(left, left + deltaX, bottom + deltaY, bottom); tree.insert(rn, new LinearSplit()); System.out.println("Rectangulos insertados : " + n); } float nodeCoverage = diskController.nodeOcupation(); System.out.println("Coverage : "+nodeCoverage); System.out.println("Tamaño de raiz llena : " + diskController.getNodeSize(address) + " bytes, con "+n+" nodos insertados. Con raiz vacía de "+rootSize+" bytes"); //Tamaño de raiz llena : 4089 bytes, con 157 nodos insertados. Con raiz vacía de 478 bytes } }
mit
VDraks/School-Desk
integration-tests/src/main/java/org/schooldesk/intergrationtests/AbstractTest.java
999
package org.schooldesk.intergrationtests; import org.junit.After; import org.junit.Before; import org.schooldesk.core.services.IServiceFactory; import org.schooldesk.core.services.ServiceFactory; import org.schooldesk.dao.DaoFactory; import org.schooldesk.dao.IDaoFactory; import org.schooldesk.dao.inmemory.inmemory.*; //import org.schooldesk.dao.hibernateimpl.DbHelper; //import org.schooldesk.dao.hibernateimpl.HibernateDaoFactory; public class AbstractTest { private IDaoFactory daoFactory; // private DbHelper dbHelper; private IServiceFactory serviceFactory; @Before public final void init() { daoFactory = DaoFactory.create(); // dbHelper = new DbHelper((HibernateDaoFactory) daoFactory); serviceFactory = ServiceFactory.create(daoFactory); } @After public final void dispose() { // dbHelper.clearDb(); Database.resetDB(); } protected IDaoFactory getDaoFactory() { return daoFactory; } protected IServiceFactory getServiceFactory() { return serviceFactory; } }
mit
Ellychou/Todo-Jersey-Spring-MyBatis
src/main/java/com/ellychou/todo/rest/util/MsgUtils.java
579
/** * Copyright (c) 2015 Ovitas Inc, All rights reserved. */ package com.ellychou.todo.rest.util; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * @author szhou * @version 1.0.1 * @since 2015/3/3 */ public class MsgUtils { private MsgUtils() { } public static Map<String, Serializable> msg(final Serializable value) { return msg("message", value); } public static Map<String, Serializable> msg(final String key, final Serializable value) { return new HashMap<String, Serializable>() { { put(key, value); } }; } }
mit
binape/webspider
src/main/java/binape/utils/HttpClientUtils.java
1144
package binape.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import binape.http.HttpClient; import binape.http.HttpStatusLine; import binape.http.HttpURL; import binape.http.IHttpClient; public class HttpClientUtils { public static String getFileContent(String url, String enc) throws IOException { HttpURL urlent = new HttpURL(url); if (!urlent.valid()) throw new IOException("Invalid URL: " + url); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (IHttpClient client = HttpClient.open(urlent.getHost(), urlent.getPort(), 10000, urlent.isSecureURL())) { client.doGet(urlent.getUri(), (message) -> { HttpStatusLine statusLine = message.getStatusLine(); if (statusLine.getStatusCode() == 200) { IOUtils.copyStream(message.getContentStream(), out); } else if (statusLine.getStatusCode() == 404) { throw new IOException("File Not Found: " + url); } else { throw new IOException("Unknown erorr: " + statusLine); } }); } catch (IOException e) { throw e; } return new String(out.toByteArray(), enc); } } }
mit
Azure/azure-sdk-for-java
sdk/datafactory/azure-resourcemanager-datafactory/src/main/java/com/azure/resourcemanager/datafactory/models/GlobalParameterSpecification.java
2520
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Definition of a single parameter for an entity. */ @Fluent public final class GlobalParameterSpecification { @JsonIgnore private final ClientLogger logger = new ClientLogger(GlobalParameterSpecification.class); /* * Global Parameter type. */ @JsonProperty(value = "type", required = true) private GlobalParameterType type; /* * Value of parameter. */ @JsonProperty(value = "value", required = true) private Object value; /** * Get the type property: Global Parameter type. * * @return the type value. */ public GlobalParameterType type() { return this.type; } /** * Set the type property: Global Parameter type. * * @param type the type value to set. * @return the GlobalParameterSpecification object itself. */ public GlobalParameterSpecification withType(GlobalParameterType type) { this.type = type; return this; } /** * Get the value property: Value of parameter. * * @return the value value. */ public Object value() { return this.value; } /** * Set the value property: Value of parameter. * * @param value the value value to set. * @return the GlobalParameterSpecification object itself. */ public GlobalParameterSpecification withValue(Object value) { this.value = value; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (type() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property type in model GlobalParameterSpecification")); } if (value() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property value in model GlobalParameterSpecification")); } } }
mit
jeimison3/Javaduino
src/com/skill/wirelesstocom/BroadcastClient.java
2139
package com.skill.wirelesstocom; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.logging.Level; import java.util.logging.Logger; public class BroadcastClient { private static int PORT = 11888; public BroadcastClient(int porta){ this.PORT=porta; } public void enviaBroadcast(String mensagem) throws IOException { for(InetAddress HostBroad: Main.broads) { DatagramSocket dsock = new DatagramSocket(); byte[] send = mensagem.getBytes(Main.CONECTION_ENCODING.getCODING()); DatagramPacket data = new DatagramPacket(send, send.length, HostBroad, this.PORT); dsock.send(data); }//Fim do loop foreach System.out.println("> "+ Main.broads.size()+" broadcasts feitos."); } } class BroadcastServer extends Thread { private final int port; public String msgRead=""; public BroadcastServer( int porta ) { this.port = porta; this.setPriority(6); this.start(); } @Override public void run() { try { DatagramSocket dsock = new DatagramSocket( port ); DatagramPacket data; while(!this.isInterrupted()) { data = new DatagramPacket( new byte[2048], 2048 ); dsock.receive(data); SkillForm1.incUDP(); msgRead=(new String( data.getData(), Main.CONECTION_ENCODING.getCODING() )).trim(); System.out.println("[UDP RECEIVE] " + msgRead ); Main.writeCOMData(msgRead); } System.out.println("UDP FINALIZADO"); } catch( SocketException ex ) { Logger.getLogger( BroadcastServer.class.getName() ). log( Level.SEVERE, null, ex ); } catch( IOException ex ) { Logger.getLogger( BroadcastServer.class.getName() ). log( Level.SEVERE, null, ex ); } catch (Throwable throwable) { throwable.printStackTrace(); } } }
mit
zsolt-kali/twis
src/test/java/me/twis/controller/TvShowControllerTest.java
3621
package me.twis.controller; import me.twis.entity.TvShow; import me.twis.entity.TvShowConfiguration; import me.twis.entity.TvShowImages; import me.twis.entity.TvShowSearchResult; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpMethod; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.match.MockRestRequestMatchers; import org.springframework.test.web.client.response.MockRestResponseCreators; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import static org.mockito.Mockito.when; import static org.springframework.test.web.client.MockRestServiceServer.createServer; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; /** * Created by kalizsolt on 10/01/16. */ public class TvShowControllerTest { private static final String TV_SHOW_TITLE = "TvShowTitle"; private static final int TV_SHOW_ID = 123; private static final String TV_SHOW_IMAGES_BASE_URL = "tvShowImagesBaseUrl"; private static final String POSTER_SIZE = "posterSize"; private static final String PROP_KEY_MOVIE_DB_API_KEY = "movieDbApiKey"; private static final String PROP_VALUE_API_KEY = "apiKey"; private static final String PROP_KEY_MOVIE_DB_ROOT_URL = "theMovieDbRootUrl"; private static final String PROP_VALUE_ROOT_URL = "http://rootUrl"; private static final String CONFIGURATION_URL = PROP_VALUE_ROOT_URL + "/configuration?api_key=" + PROP_VALUE_API_KEY; private static final String SEARCH_TV_SHOW_BY_TITLE_URL = PROP_VALUE_ROOT_URL + "/search/tv?query=" + TV_SHOW_TITLE + "&" + "api_key=" + PROP_VALUE_API_KEY; @Mock private RestTemplate restTemplate; @InjectMocks private TvShowController underTest; private MockRestServiceServer mockServer; @Before public void setUp() { MockitoAnnotations.initMocks(this); mockServer = createServer(restTemplate); ReflectionTestUtils.setField(underTest, PROP_KEY_MOVIE_DB_API_KEY, PROP_VALUE_API_KEY); ReflectionTestUtils.setField(underTest, PROP_KEY_MOVIE_DB_ROOT_URL, PROP_VALUE_ROOT_URL); } @Test public void testDummyWithRestTemplate() throws Exception { TvShowSearchResult mockedResponse = new TvShowSearchResult(); TvShow tvShow = new TvShow(); tvShow.setId(TV_SHOW_ID); mockedResponse.setResults(Arrays.asList(tvShow)); when(restTemplate.getForObject(SEARCH_TV_SHOW_BY_TITLE_URL, TvShowSearchResult.class)).thenReturn(mockedResponse); TvShowConfiguration tvShowConfiguration = new TvShowConfiguration(); TvShowImages tvShowImages = new TvShowImages(); tvShowImages.setBaseUrl(TV_SHOW_IMAGES_BASE_URL); tvShowImages.setPosterSizes(Arrays.asList(POSTER_SIZE)); tvShowConfiguration.setImages(tvShowImages); when(restTemplate.getForObject(CONFIGURATION_URL, TvShowConfiguration.class)).thenReturn(tvShowConfiguration); mockServer .expect(requestTo(SEARCH_TV_SHOW_BY_TITLE_URL)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(MockRestResponseCreators.withSuccess()); TvShowSearchResult tvShowSearchResult = underTest.searchTvShowByTitle(TV_SHOW_TITLE); Assert.assertEquals(TV_SHOW_ID, tvShowSearchResult.getResults().get(0).getId()); } }
mit
syd711/callete
callete-api/src/main/java/callete/api/Callete.java
4154
package callete.api; import callete.api.services.ServiceFactory; import callete.api.services.gpio.GPIOService; import callete.api.services.http.HttpService; import callete.api.services.monitoring.MonitoringService; import callete.api.services.music.network.NetworkMusicService; import callete.api.services.music.player.MusicPlayerService; import callete.api.services.music.streams.StreamingService; import callete.api.services.network.NetworkService; import callete.api.services.resources.ResourcesService; import callete.api.services.system.SystemService; import callete.api.services.template.TemplateService; import callete.api.services.weather.WeatherService; import callete.api.util.Config; import callete.api.util.Settings; import org.apache.commons.configuration.Configuration; /** * Central API service entry point. */ public class Callete { private final static Configuration config = Config.getConfiguration(); public static Configuration getConfiguration() { return config; } private static MusicPlayerService musicPlayer; private static WeatherService weatherService; private static GPIOService gpioService; private static HttpService httpService; private static StreamingService streamingService; private static ResourcesService resourcesService; private static SystemService systemService; private static NetworkService networkService; private static TemplateService templateService; private static NetworkMusicService networkMusicService; private static MonitoringService monitoringService; public static MusicPlayerService getMusicPlayer() { if(musicPlayer == null) { musicPlayer = (MusicPlayerService) ServiceFactory.createService(MusicPlayerService.class); } return musicPlayer; } public static WeatherService getWeatherService() { if(weatherService == null) { weatherService = (WeatherService) ServiceFactory.createService(WeatherService.class); } return weatherService; } public static GPIOService getGPIOService() { if(gpioService == null) { gpioService = (GPIOService) ServiceFactory.createService(GPIOService.class); } return gpioService; } public static HttpService getHttpService() { if(httpService == null) { httpService = (HttpService) ServiceFactory.createService(HttpService.class); } return httpService; } public static StreamingService getStreamingService() { if(streamingService == null) { streamingService = (StreamingService) ServiceFactory.createService(StreamingService.class); } return streamingService; } public static ResourcesService getResourcesService() { if(resourcesService == null) { resourcesService = (ResourcesService) ServiceFactory.createService(ResourcesService.class); } return resourcesService; } public static SystemService getSystemService() { if(systemService == null) { systemService = (SystemService) ServiceFactory.createService(SystemService.class); } return systemService; } public static TemplateService getTemplateService() { if(templateService== null) { templateService = (TemplateService) ServiceFactory.createService(TemplateService.class); } return templateService; } public static NetworkService getNetworkService() { if(networkService== null) { networkService = (NetworkService) ServiceFactory.createService(NetworkService.class); } return networkService; } public static MonitoringService getMonitoringService() { if(monitoringService == null) { monitoringService = (MonitoringService) ServiceFactory.createService(MonitoringService.class); } return monitoringService; } public static NetworkMusicService getNetworkMusicService() { if(networkMusicService == null) { networkMusicService = (NetworkMusicService) ServiceFactory.createService(NetworkMusicService.class); } return networkMusicService; } public static Configuration getSettings() { return Settings.getSettings(); } public static void saveSetting(String key, Object value) { Settings.saveSetting(key, value); } }
mit
android-notes/SwissArmyKnife
saklib/src/main/java/com/wanjian/sak/config/Config.java
4305
package com.wanjian.sak.config; import android.content.Context; import android.graphics.drawable.Drawable; import com.wanjian.sak.converter.ISizeConverter; import com.wanjian.sak.converter.OriginSizeConverter; import com.wanjian.sak.converter.Px2DpSizeConverter; import com.wanjian.sak.converter.Px2SpSizeConverter; import com.wanjian.sak.filter.ViewFilter; import com.wanjian.sak.layer.Layer; import com.wanjian.sak.utils.Check; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by wanjian on 2017/2/20. */ public class Config { private int minRange; private int maxRange; // private List<AbsLayer> mLayerViews = new ArrayList<>(); private List<ISizeConverter> mSizeConverterList = new ArrayList<>(); private int startRange; private int endRange; private boolean clipDraw; List<Item>mLayerList; private Config(Build build) { // mLayerViews.addAll(build.mDefaultLayerViews); // mLayerViews.addAll(build.mCustomerLayerViews); ViewFilter.FILTER = build.mViewFilter; mSizeConverterList.addAll(build.mSizeConverterList); minRange = build.min; maxRange = build.max; clipDraw = build.clipDraw; mLayerList = build.mLayerList; } public List<Item> getLayerList() { return mLayerList; } // public List<AbsLayer> getLayerViews() { // return mLayerViews; // } public List<ISizeConverter> getSizeConverters() { if (mSizeConverterList == null || mSizeConverterList.isEmpty()) { return Arrays.<ISizeConverter>asList(new OriginSizeConverter()); } return mSizeConverterList; } public int getStartRange() { return startRange; } public void setStartRange(int startRange) { this.startRange = startRange; } public int getEndRange() { return endRange; } public void setEndRange(int endRange) { this.endRange = endRange; } public boolean isClipDraw() { return clipDraw; } public void setClipDraw(boolean clipDraw) { this.clipDraw = clipDraw; } public int getMinRange() { return minRange; } public int getMaxRange() { return maxRange; } public static class Build { Context mContext; List<ISizeConverter> mSizeConverterList = new ArrayList<>(); ViewFilter mViewFilter; List<Item>mLayerList=new ArrayList<>(); int min = 0; int max = 50; boolean clipDraw = true; public Build(Context context) { Check.isNull(context, "context"); mContext = context.getApplicationContext(); mSizeConverterList.add(new Px2DpSizeConverter()); mSizeConverterList.add(new OriginSizeConverter()); mSizeConverterList.add(new Px2SpSizeConverter()); mViewFilter = ViewFilter.FILTER; } public Build addSizeConverter(ISizeConverter sizeConverter) { Check.isNull(sizeConverter, "sizeConverter"); mSizeConverterList.add(sizeConverter); return this; } // public Build addLayerView(AbsLayer layerView) { // Check.isNull(layerView, "layerView"); //// mDefaultLayerViews.clear(); //// mCustomerLayerViews.add(layerView); // return this; // } public Build viewFilter(ViewFilter viewFilter) { Check.isNull(viewFilter, "viewFilter"); mViewFilter = viewFilter; return this; } public Build range(int min, int max) { if (min < 0) { throw new IllegalArgumentException(); } if (max < min) { throw new IllegalArgumentException(); } this.min = min; this.max = max; return this; } public Build clipDraw(boolean clip) { clipDraw = clip; return this; } public Build addLayer(Class<? extends Layer> clz, Drawable icon, String iconName) { mLayerList.add(new Item(clz,icon,iconName)); return this; } public Config build() { return new Config(this); } } }
mit
gems-uff/dominoes
gitdataminer/src/main/java/com/josericardojunior/gitdataminer/MatrixDescriptor3D.java
836
package com.josericardojunior.gitdataminer; import java.util.ArrayList; import java.util.List; import com.josericardojunior.gitdataminer.Analyzer.InfoType; public class MatrixDescriptor3D extends MatrixDescriptor { private InfoType depthType; private List<String> depthDesc = new ArrayList<String>(); public MatrixDescriptor3D(InfoType _rowType, InfoType _colType, InfoType _depthType){ super(_rowType, _colType); depthType = _depthType; } public int getNumDepths(){ return depthDesc.size(); } public InfoType getDepthType(){ return depthType; } public void AddDepthDesc(String _depthDesc){ depthDesc.add(_depthDesc); } public int getDepthElementIndex(String _name){ return depthDesc.indexOf(_name); } public String getDepthAt(int depthIndex){ return depthDesc.get(depthIndex); } }
mit
fcjack/dev-library
library-api/src/main/java/org/jack/library/repository/AuthorRepository.java
258
package org.jack.library.repository; import org.jack.library.entity.Author; import org.springframework.data.repository.CrudRepository; /** * Created by jackson on 04/01/17. */ public interface AuthorRepository extends CrudRepository<Author, Integer> { }
mit
Mewel/abbyy-to-alto
src/main/java/org/mycore/xml/abbyy/v10/PictureType.java
2801
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.04.18 at 01:41:32 PM CEST // package org.mycore.xml.abbyy.v10; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PictureType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PictureType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="caption" type="{http://www.abbyy.com/FineReader_xml/FineReader10-schema-v1.xml}CaptionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PictureType", propOrder = { "caption" }) public class PictureType { protected List<CaptionType> caption; @XmlAttribute(name = "id", required = true) protected String id; /** * Gets the value of the caption property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the caption property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCaption().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CaptionType } * * */ public List<CaptionType> getCaption() { if (caption == null) { caption = new ArrayList<CaptionType>(); } return this.caption; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
mit
develhack/develhacked-lombok
test/transform/develhack/after-ecj/InitializeFieldsByConstructor.java
2693
class InitializeFieldsByConstructor { @com.develhack.annotation.feature.InitializeFieldsByConstructor class Default { private int field; private final int finalField; private final int initializedFinalField = 0; private transient int transientField; private @com.develhack.annotation.feature.ExcludedFrom(com.develhack.annotation.feature.InitializeFieldsByConstructor.class) String exclude; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") Default(final int finalField) { super(); this.finalField = finalField; } } @com.develhack.annotation.feature.InitializeFieldsByConstructor(finalFieldsInitializer = com.develhack.annotation.feature.Access.DEFAULT,allFieldsInitializer = com.develhack.annotation.feature.Access.PUBLIC) class WithAllFieldsInitializer { private int field; private final int finalField; private final int initializedFinalField = 0; private transient int transientField; private @com.develhack.annotation.feature.ExcludedFrom(com.develhack.annotation.feature.InitializeFieldsByConstructor.class) String exclude; public @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WithAllFieldsInitializer(final int field, final int finalField) { super(); this.field = field; this.finalField = finalField; } @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") WithAllFieldsInitializer(final int finalField) { super(); this.finalField = finalField; } } @com.develhack.annotation.feature.InitializeFieldsByConstructor(finalFieldsInitializer = com.develhack.annotation.feature.Access.NONE,allFieldsInitializer = com.develhack.annotation.feature.Access.PROTECTED) class AllFieldsInitializerOnly { private int field; private final int finalField; private final int initializedFinalField = 0; private transient int transientField; private @com.develhack.annotation.feature.ExcludedFrom(com.develhack.annotation.feature.InitializeFieldsByConstructor.class) String exclude; protected @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") AllFieldsInitializerOnly(final int field, final int finalField) { super(); this.field = field; this.finalField = finalField; } } @com.develhack.annotation.feature.InitializeFieldsByConstructor(finalFieldsInitializer = com.develhack.annotation.feature.Access.PUBLIC,allFieldsInitializer = com.develhack.annotation.feature.Access.PUBLIC) class NoTarget { private final int initializedFinalField = 0; NoTarget() { super(); } } InitializeFieldsByConstructor() { super(); } }
mit
Azure/azure-sdk-for-java
sdk/azurestack/azure-resourcemanager-azurestack/src/main/java/com/azure/resourcemanager/azurestack/fluent/models/ProductListInner.java
2047
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.azurestack.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Pageable list of products. */ @Fluent public final class ProductListInner { @JsonIgnore private final ClientLogger logger = new ClientLogger(ProductListInner.class); /* * URI to the next page. */ @JsonProperty(value = "nextLink") private String nextLink; /* * List of products. */ @JsonProperty(value = "value") private List<ProductInner> value; /** * Get the nextLink property: URI to the next page. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Set the nextLink property: URI to the next page. * * @param nextLink the nextLink value to set. * @return the ProductListInner object itself. */ public ProductListInner withNextLink(String nextLink) { this.nextLink = nextLink; return this; } /** * Get the value property: List of products. * * @return the value value. */ public List<ProductInner> value() { return this.value; } /** * Set the value property: List of products. * * @param value the value value to set. * @return the ProductListInner object itself. */ public ProductListInner withValue(List<ProductInner> value) { this.value = value; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (value() != null) { value().forEach(e -> e.validate()); } } }
mit
tillmannheigel/freedriver_V2
src/test/java/de/freedriver/annotations/Skip.java
290
package de.freedriver.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Skip { }
mit
diegoneri/clinicacirurgica
Fontes/AMC/src/br/com/cirurgica/view/usuario/GestaoUsuario.java
28743
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.cirurgica.view.usuario; import br.com.cirurgica.view.cliente.GestaoCliente; import br.com.cirurgica.dao.CirurgicaConnectionManager; import br.com.cirurgica.dao.LoginDAO; import br.com.cirurgica.model.Usuario; import br.com.cirurgica.view.PrincipalView; import com.utilidades.Utilidades; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author 13b Pessoal */ public class GestaoUsuario extends javax.swing.JFrame { /** * Creates new form GestaoUsuario */ static String RGAlteracao; public GestaoUsuario() throws ParseException { initComponents(); popularTabela(); btnAdicioanr.addKeyListener(new PressEnter()); btnPesquisar.addKeyListener(new PressEnter()); btnVoltar.addKeyListener(new PressEnter()); btnAlterar.addKeyListener(new PressEnter()); btnExcluir.addKeyListener(new PressEnter()); txtPesquisa.addKeyListener(new PressEnter()); } private void popularTabela() { listaUsuarios.clear(); Collection listaRetorno = new LoginDAO().findAll(); if (listaRetorno != null && listaRetorno.size() > 0) { this.listaUsuarios.addAll(listaRetorno); } } /* public void popularTabela() throws ParseException { String sql = "select *, max(v.data_venda) as ultima_venda from usuario u join pessoa p on(u.cd_pessoa = p.cd_pessoa) left join venda v on(u.cd_usuario = v.cd_usuario) group by p.cd_pessoa"; Connection con; con = CirurgicaConnectionManager.getConnection(); DefaultTableModel dataModel = (DefaultTableModel) tbGestaoUsuario.getModel(); dataModel.setNumRows(0); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Object[] linha = {rs.getString("nm_pessoa"), rs.getString("tipo_usuario"), rs.getString("RG"), Utilidades.retornarDataFormatada(rs.getString("ultima_venda"))}; dataModel.addRow(linha); } stmt.close(); } catch (SQLException ex) { Logger.getLogger(PrincipalView.class.getName()).log(Level.SEVERE, null, ex); } } */ /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); listaUsuarios = org.jdesktop.observablecollections.ObservableCollections.observableList(new ArrayList()); usuarioBean = new br.com.cirurgica.model.Usuario(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tbGestaoUsuario = new javax.swing.JTable(); tbGestaoUsuario.getSelectionModel().addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent arg0) { if(tbGestaoUsuario.getSelectedRow() != -1){ usuarioBean = listaUsuarios.get(tbGestaoUsuario.getSelectedRow()); btnExcluir.setEnabled(true); btnAlterar.setEnabled(true); }else{ usuarioBean = null; btnExcluir.setEnabled(false); btnAlterar.setEnabled(false); } } }); jPanel1 = new javax.swing.JPanel(); btnAdicioanr = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); btnPesquisar = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); btnVoltar = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); txtPesquisa = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); btnAlterar = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); btnExcluir = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setTitle("Ana Maria Cirurgica - Usuários"); setBounds(new java.awt.Rectangle(300, 100, 0, 0)); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS)); jPanel2.setLayout(new java.awt.GridBagLayout()); jLabel1.setFont(new java.awt.Font("Segoe UI Light", 1, 24)); // NOI18N jLabel1.setText("Gestão de Usuários"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(11, 188, 0, 0); jPanel2.add(jLabel1, gridBagConstraints); tbGestaoUsuario.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N tbGestaoUsuario.setFocusable(false); tbGestaoUsuario.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listaUsuarios, tbGestaoUsuario); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cdPessoa.nmPessoa}")); columnBinding.setColumnName("Nome"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${login.nmLogin}")); columnBinding.setColumnName("Usuário"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tipoUsuario}")); columnBinding.setColumnName("Tipo Usuário"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, usuarioBean, org.jdesktop.beansbinding.ObjectProperty.create(), tbGestaoUsuario, org.jdesktop.beansbinding.BeanProperty.create("selectedElement"), "usuarioBinding"); bindingGroup.addBinding(binding); tbGestaoUsuario.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbGestaoUsuarioMouseClicked(evt); } }); jScrollPane1.setViewportView(tbGestaoUsuario); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.ipadx = 527; gridBagConstraints.ipady = 113; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 28, 0, 56); jPanel2.add(jScrollPane1, gridBagConstraints); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); btnAdicioanr.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnAdicioanr.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/bt_novo_cliente.png"))); // NOI18N btnAdicioanr.setPreferredSize(new java.awt.Dimension(90, 60)); btnAdicioanr.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAdicioanrActionPerformed(evt); } }); btnAdicioanr.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { btnAdicioanrKeyPressed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("ADICIONAR"); btnPesquisar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/bt_pesquisar.png"))); // NOI18N btnPesquisar.setPreferredSize(new java.awt.Dimension(90, 60)); btnPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPesquisarActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("PESQUISAR"); btnVoltar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/bt_voltar.png"))); // NOI18N btnVoltar.setPreferredSize(new java.awt.Dimension(90, 60)); btnVoltar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVoltarActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel4.setText("VOLTAR(ESC)"); txtPesquisa.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N jLabel5.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel5.setText("Nome de Usuário:"); btnAlterar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/bt_alterar.png"))); // NOI18N btnAlterar.setEnabled(false); btnAlterar.setPreferredSize(new java.awt.Dimension(90, 60)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${not empty usuarioBean}"), btnAlterar, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); btnAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAlterarActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("ALTERAR"); btnExcluir.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/bt_excluir.png"))); // NOI18N btnExcluir.setEnabled(false); btnExcluir.setPreferredSize(new java.awt.Dimension(90, 60)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${not empty usuarioBean}"), btnExcluir, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); btnExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExcluirActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("EXCLUIR"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(btnAdicioanr, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnVoltar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(139, 139, 139)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnVoltar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnAdicioanr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(7, 7, 7) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel3) .addComponent(jLabel4))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.ipadx = -129; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(11, 28, 27, 56); jPanel2.add(jPanel1, gridBagConstraints); getContentPane().add(jPanel2); bindingGroup.bind(); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-633)/2, (screenSize.height-373)/2, 633, 373); }// </editor-fold>//GEN-END:initComponents private void tbGestaoUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbGestaoUsuarioMouseClicked }//GEN-LAST:event_tbGestaoUsuarioMouseClicked private void btnAdicioanrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicioanrActionPerformed chamarCadastrarUsuario(); }//GEN-LAST:event_btnAdicioanrActionPerformed private void btnAdicioanrKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnAdicioanrKeyPressed // TODO add your handling code here: }//GEN-LAST:event_btnAdicioanrKeyPressed private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed pesquisarUsuario(); }//GEN-LAST:event_btnPesquisarActionPerformed private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed chamarVoltar(); }//GEN-LAST:event_btnVoltarActionPerformed private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed chamarVisualizarUsuario(); }//GEN-LAST:event_btnAlterarActionPerformed private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed chamarExcluirUsuario(); }//GEN-LAST:event_btnExcluirActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing chamarVoltar(); }//GEN-LAST:event_formWindowClosing public boolean verificarUsuario(String cd_pessoa) { Connection con = CirurgicaConnectionManager.getConnection(); PreparedStatement stm; String sql = "select *, cd_pessoa from pessoa p join where RG = '" + tbGestaoUsuario.getModel().getValueAt(tbGestaoUsuario.getSelectedRow(), 2).toString() + "'"; String cdPessoa = ""; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { cdPessoa = rs.getString("cd_pessoa"); } } catch (Exception e) { e.printStackTrace(); } return true; } public void excluirUsuario() { Connection con = CirurgicaConnectionManager.getConnection(); PreparedStatement stm; String sql = "select cd_pessoa from pessoa where RG = '" + tbGestaoUsuario.getModel().getValueAt(tbGestaoUsuario.getSelectedRow(), 2).toString() + "'"; String cdPessoa = ""; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { cdPessoa = rs.getString("cd_pessoa"); } } catch (Exception e) { e.printStackTrace(); } int cdPessoaLogada = Utilidades.pessoaLogada.getCdPessoa().intValue(); if (cdPessoaLogada == Integer.parseInt(cdPessoa)) { JOptionPane.showMessageDialog(null, "Não se pode remover um usuário logado.", "Restrição", 1); } else { sql = "delete from usuario where cd_pessoa = " + cdPessoa; try { stm = con.prepareStatement(sql); stm.executeUpdate(); stm.close(); con.close(); JOptionPane.showMessageDialog(null, "CADASTRO EXCLUIDO COM SUCESSO!!!", "Remoção", 1); } catch (SQLException ex) { Logger.getLogger(GestaoCliente.class.getName()).log(Level.SEVERE, null, ex); } } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GestaoUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GestaoUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GestaoUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GestaoUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new GestaoUsuario().setVisible(true); } catch (ParseException ex) { Logger.getLogger(GestaoUsuario.class.getName()).log(Level.SEVERE, null, ex); } } }); } public void pesquisarUsuario() { DefaultTableModel dataModel = (DefaultTableModel) tbGestaoUsuario.getModel(); dataModel.setNumRows(0); String sql = "select *, max(v.data_venda) as ultima_venda from usuario u join pessoa p on(u.cd_pessoa = p.cd_pessoa) left join venda v on(u.cd_usuario = v.cd_usuario) where p.nm_pessoa like '" + txtPesquisa.getText() + "%' group by p.cd_pessoa"; Connection con; con = CirurgicaConnectionManager.getConnection(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Object[] linha = {rs.getString("nm_pessoa"), rs.getString("tipo_usuario"), rs.getString("RG"), Utilidades.retornarDataFormatada(rs.getString("ultima_venda"))}; dataModel.addRow(linha); } } catch (Exception e) { e.printStackTrace(); } } class PressEnter implements KeyListener { public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (btnAdicioanr.isFocusOwner()) { chamarCadastrarUsuario(); } else if (btnPesquisar.isFocusOwner()) { } else if (btnVoltar.isFocusOwner()) { chamarVoltar(); } else if (btnAlterar.isFocusOwner()) { chamarVisualizarUsuario(); } else if (btnExcluir.isFocusOwner()) { chamarExcluirUsuario(); } else if (txtPesquisa.isFocusOwner()) { pesquisarUsuario(); } } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { chamarVoltar(); } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } public void chamarCadastrarUsuario() { CadastrarUsuario cu = new CadastrarUsuario(); cu.setVisible(true); this.dispose(); } public void chamarVisualizarUsuario() { if (tbGestaoUsuario.getSelectedRowCount() == 0) { JOptionPane.showMessageDialog(this, "Selecione um Usuário para Visualizar e/ou Alterar seus dados.", "Seleção Necessária", 1); } else { RGAlteracao = tbGestaoUsuario.getModel().getValueAt(tbGestaoUsuario.getSelectedRow(), 2).toString(); AlterarUsuario au = new AlterarUsuario(); au.setVisible(true); this.setVisible(false); } } public void chamarExcluirUsuario() { if (tbGestaoUsuario.getSelectedRowCount() == 0) { JOptionPane.showMessageDialog(this, "Selecione um Usuário para poder excluir.", "Seleção Necessária", 1); } else { if (JOptionPane.showConfirmDialog(this, "Tem certeza que deseja excluir este cadastro?", "Confirmação", 2, 3) == 0) { excluirUsuario(); } } popularTabela(); } public void chamarVoltar() { PrincipalView p = new PrincipalView(); p.setVisible(true); p.setUsuarioLogado(Utilidades.retornaNomeLogado()); this.dispose(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdicioanr; private javax.swing.JButton btnAlterar; private javax.swing.JButton btnExcluir; private javax.swing.JButton btnPesquisar; private javax.swing.JButton btnVoltar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private java.util.List<Usuario> listaUsuarios; private javax.swing.JTable tbGestaoUsuario; private javax.swing.JTextField txtPesquisa; private br.com.cirurgica.model.Usuario usuarioBean; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }
mit
Upplication/cordova-java
src/test/java/com/upplication/cordova/util/ConfigProcessorTest.java
9630
package com.upplication.cordova.util; import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.w3c.dom.Document; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.UUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; public class ConfigProcessorTest { private FileSystem fs; private DocumentGetter document; private Path configFile; private ConfigProcessor processor; private ConfigProcessorDocument processorDocument; @Before public void setup() throws Exception { this.fs = MemoryFileSystemBuilder.newLinux().build(UUID.randomUUID().toString()); final Document[] doc = new Document[1]; this.document = new DocumentGetter(doc); this.processorDocument = mock(ConfigProcessorDocument.class); this.configFile = createConfigXmlFile(); this.processor = spy(new ConfigProcessor(configFile)); doAnswer(new Answer<ConfigProcessorDocument>() { @Override public ConfigProcessorDocument answer(InvocationOnMock invocationOnMock) throws Throwable { doc[0] = (Document)invocationOnMock.getArguments()[0]; return processorDocument; } }).when(processor).getProcessor(any(Document.class)); } @Test public void when_set_name_then_open_the_file_and_call_ConfigProcessorDocument_and_close() throws Exception { String name = "app name cool"; InOrder inOrder = inOrder(processor, processorDocument); processor.setName(name); inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setName(eq(name)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_version_then_open_the_file_and_call_ConfigProcessorDocument_and_close() throws Exception { String version = "2.0.0"; InOrder inOrder = inOrder(processor, processorDocument); processor.setVersion(version, null, null); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setVersion(eq(version), isNull(String.class), isNull(Integer.class)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_version_ios_then_attr_version_ios_is_changed() throws Exception { String version = "2.0.0"; InOrder inOrder = inOrder(processor, processorDocument); processor.setVersion(version, version, null); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setVersion(eq(version), eq(version), isNull(Integer.class)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_version_android_then_attr_version_android_is_changed() throws Exception { String version = "2.0.0"; Integer versionAndroid = 2; InOrder inOrder = inOrder(processor, processorDocument); processor.setVersion(version, version, versionAndroid); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setVersion(eq(version), eq(version), eq(versionAndroid)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_author_email_then_author_email_is_changed() throws Exception { String email = "email@email.com"; InOrder inOrder = inOrder(processor, processorDocument); processor.setAuthorEmail(email); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setAuthorEmail(eq(email)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_author_name_then_author_content_is_changed() throws Exception { String authorName = "Upplication Software"; InOrder inOrder = inOrder(processor, processorDocument); processor.setAuthorName(authorName); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setAuthorName(eq(authorName)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_author_href_then_href_attr_is_changed() throws Exception { String authorHref = "upplication.com"; InOrder inOrder = inOrder(processor, processorDocument); processor.setAuthorHref(authorHref); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setAuthorHref(eq(authorHref)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_description_then_description_node_content_is_changed() throws Exception { String description = "description"; InOrder inOrder = inOrder(processor, processorDocument); processor.setDescription(description); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).setDescription(eq(description)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_allowNavigation_then_allowNavigation_node_is_added() throws Exception { String href = "*"; InOrder inOrder = inOrder(processor, processorDocument); processor.addAllowNavigation(href); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).addAllowNavigation(eq(href)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } @Test public void when_set_custom_xml_then_append_the_string() throws Exception { String xml = "<universal-link></universal-link>"; InOrder inOrder = inOrder(processor, processorDocument); processor.add(xml); // assert inOrder.verify(processor).openConfig(eq(configFile)); inOrder.verify(processor).getProcessor(eq(document.get())); inOrder.verify(processorDocument).add(eq(xml)); inOrder.verify(processor).saveConfig(eq(configFile), eq(document.get())); } // helpers private Path createConfigXmlFile() throws Exception { // write the content into xml file Path file = fs.getPath("/" + UUID.randomUUID().toString(), "config.xml"); Files.createDirectories(file.getParent()); Files.write(file, xmlDefault.getBytes(), StandardOpenOption.CREATE_NEW); return file; } /** * version cordova 6.1.1 with the command: 'cordova create test' */ private String xmlDefault = "<?xml version='1.0' encoding='utf-8'?>\n" + "<widget id=\"io.cordova.hellocordova\" version=\"0.0.1\" xmlns=\"http://www.w3.org/ns/widgets\" xmlns:cdv=\"http://cordova.apache.org/ns/1.0\">\n" + " <name>HelloCordova</name>\n" + " <description>\n" + " A sample Apache Cordova application that responds to the deviceready event.\n" + " </description>\n" + " <author email=\"dev@cordova.apache.org\" href=\"http://cordova.io\">\n" + " Apache Cordova Team\n" + " </author>\n" + " <content src=\"index.html\" />\n" + " <plugin name=\"cordova-plugin-whitelist\" spec=\"1\" />\n" + " <access origin=\"*\" />\n" + " <allow-intent href=\"http://*/*\" />\n" + " <allow-intent href=\"https://*/*\" />\n" + " <allow-intent href=\"tel:*\" />\n" + " <allow-intent href=\"sms:*\" />\n" + " <allow-intent href=\"mailto:*\" />\n" + " <allow-intent href=\"geo:*\" />\n" + " <platform name=\"android\">\n" + " <allow-intent href=\"market:*\" />\n" + " </platform>\n" + " <platform name=\"ios\">\n" + " <allow-intent href=\"itms:*\" />\n" + " <allow-intent href=\"itms-apps:*\" />\n" + " </platform>\n" + "</widget>"; private static class DocumentGetter { private Document[] document; public DocumentGetter(Document[] document) { this.document = document; } public Document get() { return this.document[0]; } } }
mit
McJty/LostCities
src/main/java/mcjty/lostcities/config/BiomeSelectionStrategy.java
736
package mcjty.lostcities.config; import java.util.HashMap; import java.util.Map; public enum BiomeSelectionStrategy { ORIGINAL("original"), RANDOMIZED("randomized"), VARIED("varied"); private final String name; private static final Map<String, BiomeSelectionStrategy> NAME_TO_TYPE = new HashMap<>(); static { for (BiomeSelectionStrategy type : BiomeSelectionStrategy.values()) { NAME_TO_TYPE.put(type.getName(), type); } } BiomeSelectionStrategy(String name) { this.name = name; } public String getName() { return name; } public static BiomeSelectionStrategy getTypeByName(String name) { return NAME_TO_TYPE.get(name); } }
mit
dru1/wicketblog
src/main/java/at/dru/wicketblog/service/PostCategoryService.java
1024
package at.dru.wicketblog.service; import at.dru.wicketblog.model.PostCategory; import at.dru.wicketblog.model.PostCategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Nonnull; import javax.annotation.Nullable; @Service public class PostCategoryService extends AbstractEntityService<PostCategory> { @Autowired private PostCategoryRepository postCategoryRepository; @Nonnull @Override public Class<PostCategory> getEntityType() { return PostCategory.class; } @Override public void saveEntity(@Nonnull PostCategory entity) { postCategoryRepository.save(entity); } @Nullable @Override public PostCategory findByEntityId(@Nonnull Long entityId) { return postCategoryRepository.findById(entityId).orElse(null); } @Nonnull @Override public Iterable<PostCategory> findAll() { return postCategoryRepository.findAll(); } }
mit
gaetancollaud/fablab-manager
src/main/java/net/collaud/fablab/manager/rest/v1/criteria/AuthCredential.java
657
package net.collaud.fablab.manager.rest.v1.criteria; /** * * @author Gaetan Collaud <gaetancollaud@gmail.com> */ public class AuthCredential { String login; String password; public AuthCredential() { } public AuthCredential(String login, String password) { this.login = login; this.password = password; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "login=" + login + ", password=*****"; } }
mit
josecostamartins/udacity-p2-popularmovies
app/src/main/java/br/com/digitaldreams/popularmovies2/adapter/TrailerRecyclerAdapter.java
2294
package br.com.digitaldreams.popularmovies2.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import br.com.digitaldreams.popularmovies2.R; import br.com.digitaldreams.popularmovies2.models.Trailer; /** * Created by josecostamartins on 9/10/16. */ public class TrailerRecyclerAdapter extends RecyclerView.Adapter<TrailerRecyclerAdapter.ViewHolder>{ private ArrayList<Trailer> mDataSet; private Context mContext; public TrailerRecyclerAdapter(ArrayList<Trailer> mDataSet, Context mContext) { if (mContext == null){ throw new NullPointerException("Context cannot be null"); } this.mDataSet = mDataSet; this.mContext = mContext; } // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView trailerTitle; public ViewHolder(View v) { super(v); trailerTitle = (TextView) v.findViewById(R.id.trailer_name); } } public void notifyDataSetChanged(ArrayList<Trailer> mDataSet){ /*if (mDataSet == null){ throw new NullPointerException("DataSet cannot be null"); }*/ this.mDataSet = mDataSet; notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.trailer_list_item, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Trailer trailer = mDataSet.get(position); holder.trailerTitle.setText(trailer.getName()); } @Override public int getItemCount() { if (mDataSet != null) { return mDataSet.size(); } return 0; } }
mit
williamfiset/Algorithms
src/main/java/com/williamfiset/algorithms/sorting/InsertionSort.java
1234
/** * Insertion sort implementation * * <p>Run with: * * <p>$ ./gradlew run -Palgorithm=sorting.InsertionSort * * @author William Fiset, william.alexandre.fiset@gmail.com */ package com.williamfiset.algorithms.sorting; public class InsertionSort implements InplaceSort { @Override public void sort(int[] values) { InsertionSort.insertionSort(values); } // Sort the given array using insertion sort. The idea behind // insertion sort is that at the array is already sorted from // [0, i] and you want to add the element at position i+1, so // you 'insert' it at the appropriate location. private static void insertionSort(int[] ar) { if (ar == null) { return; } for (int i = 1; i < ar.length; i++) { for (int j = i; j > 0 && ar[j] < ar[j - 1]; j--) { swap(ar, j - 1, j); } } } private static void swap(int[] ar, int i, int j) { int tmp = ar[i]; ar[i] = ar[j]; ar[j] = tmp; } public static void main(String[] args) { InplaceSort sorter = new InsertionSort(); int[] array = {10, 4, 6, 8, 13, 2, 3}; sorter.sort(array); // Prints: // [2, 3, 4, 6, 8, 10, 13] System.out.println(java.util.Arrays.toString(array)); } }
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/intelledit/src/main/java/at/ac/tuwien/big/xmlintelledit/intelledit/oclgen/DelegatingRegistry.java
1439
package at.ac.tuwien.big.xmlintelledit.intelledit.oclgen; import java.util.Collection; import java.util.Map; import java.util.Set; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EValidator; import org.eclipse.emf.ecore.EValidator.Registry; public class DelegatingRegistry implements EValidator.Registry { private final EValidator.Registry delegate; public DelegatingRegistry(Registry delegate) { this.delegate = delegate; } public void clear() { delegate.clear(); } public boolean containsKey(Object key) { return delegate.containsKey(key); } public boolean containsValue(Object value) { return delegate.containsValue(value); } public Set<java.util.Map.Entry<EPackage, Object>> entrySet() { return delegate.entrySet(); } public Object get(Object key) { return delegate.get(key); } public EValidator getEValidator(EPackage ePackage) { return delegate.getEValidator(ePackage); } public boolean isEmpty() { return delegate.isEmpty(); } public Set<EPackage> keySet() { return delegate.keySet(); } public Object put(EPackage key, Object value) { return delegate.put(key, value); } public void putAll(Map<? extends EPackage, ? extends Object> m) { delegate.putAll(m); } public Object remove(Object key) { return delegate.remove(key); } public int size() { return delegate.size(); } public Collection<Object> values() { return delegate.values(); } }
mit
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/account/testDiscoverRightsRequest.java
1842
package generated.zcsclient.account; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for discoverRightsRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="discoverRightsRequest"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="right" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "discoverRightsRequest", propOrder = { "right" }) public class testDiscoverRightsRequest { @XmlElement(required = true) protected List<String> right; /** * Gets the value of the right property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the right property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRight().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getRight() { if (right == null) { right = new ArrayList<String>(); } return this.right; } }
mit
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/admin/testEffectiveAttrInfo.java
5012
package generated.zcsclient.admin; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for effectiveAttrInfo complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="effectiveAttrInfo"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="constraint" type="{urn:zimbraAdmin}constraintInfo" minOccurs="0"/> * &lt;element name="default" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="v" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="n" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "effectiveAttrInfo", propOrder = { "constraint", "_default" }) public class testEffectiveAttrInfo { protected testConstraintInfo constraint; @XmlElement(name = "default") protected testEffectiveAttrInfo.Default _default; @XmlAttribute(name = "n", required = true) protected String n; /** * Gets the value of the constraint property. * * @return * possible object is * {@link testConstraintInfo } * */ public testConstraintInfo getConstraint() { return constraint; } /** * Sets the value of the constraint property. * * @param value * allowed object is * {@link testConstraintInfo } * */ public void setConstraint(testConstraintInfo value) { this.constraint = value; } /** * Gets the value of the default property. * * @return * possible object is * {@link testEffectiveAttrInfo.Default } * */ public testEffectiveAttrInfo.Default getDefault() { return _default; } /** * Sets the value of the default property. * * @param value * allowed object is * {@link testEffectiveAttrInfo.Default } * */ public void setDefault(testEffectiveAttrInfo.Default value) { this._default = value; } /** * Gets the value of the n property. * * @return * possible object is * {@link String } * */ public String getN() { return n; } /** * Sets the value of the n property. * * @param value * allowed object is * {@link String } * */ public void setN(String value) { this.n = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="v" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "v" }) public static class Default { protected List<String> v; /** * Gets the value of the v property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the v property. * * <p> * For example, to add a new item, do as follows: * <pre> * getV().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getV() { if (v == null) { v = new ArrayList<String>(); } return this.v; } } }
mit
butterbrother/alpha-versions
learn/java/FindAreas.java
979
class Figure { double dim1, dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Площадь фигуры не определена."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } double area() { System.out.println("В области четырёхугольника."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } double area() { System.out.println("В области треугольника."); return dim1 * dim2 / 2; } } class FindAreas { public static void calc(Figure ob) { System.out.println("Площадь равна " + ob.area()); } public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); calc(r); calc(t); calc(f); } }
mit
surli/spinefm
spinefm-eclipseplugins-root/spinefm-core/test/fr/unice/spinefm/ActionModel/UserActionModel/impl/test/TestUserCreateContext.java
904
package fr.unice.spinefm.ActionModel.UserActionModel.impl.test; import static org.junit.Assert.assertEquals; import org.junit.Test; import fr.unice.spinefm.ActionModel.UserActionModel.UserActionModelFactory; import fr.unice.spinefm.ActionModel.UserActionModel.UserCreateContext; import fr.unice.spinefm.exceptions.ElementNotFoundException; import fr.unice.spinefm.exceptions.FatalSpineFMException; public class TestUserCreateContext extends InitSimpleModel { @Test public void testCreateContextAndUndoWorks() throws ElementNotFoundException, FatalSpineFMException { this.initModel(); assertEquals(0,cm.getLocalContexts().size()); UserCreateContext ucc = UserActionModelFactory.eINSTANCE.createUserCreateContext(); ucc.initManualAction(cm); ucc.apply(); assertEquals(1,cm.getLocalContexts().size()); cm.getPast().undoLastAction(); assertEquals(0,cm.getLocalContexts().size()); } }
mit
gihangt/Android-App
WeatherApp(source)/app/src/main/java/app/testapplication/gihan/com/weatherapp/XMLGeoWOEID.java
2979
package app.testapplication.gihan.com.weatherapp; import android.content.Intent; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * WOEID API Reader. */ public class XMLGeoWOEID { private String urlString = null; private String WOEID; private XmlPullParserFactory xmlFactoryObject; public volatile boolean parsingComplete = true; public XMLGeoWOEID(String url){ this.urlString = url; } public String getWOEID() { return WOEID; } /** * Read XML out put from API. * @param newParser */ public void getXmlStore(XmlPullParser newParser){ int event; String text = null; try{ event = newParser.getEventType(); while (event != XmlPullParser .END_DOCUMENT){ String name = newParser.getName(); switch (event) { case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = newParser.getText(); break; case XmlPullParser.END_TAG: //Get WOEID. if (name.equals("woeid")) { WOEID =text; } break; } event = newParser.next(); } parsingComplete = false; }catch (Exception e){ e.printStackTrace(); } } /** * Read the url connection on separate thread. */ public void fetchXML(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { URL Geturl = new URL(urlString); HttpURLConnection checkConnection = (HttpURLConnection)Geturl.openConnection(); //Set timer. checkConnection.setReadTimeout(10000); checkConnection.setConnectTimeout(50000); checkConnection.setRequestMethod("GET"); checkConnection.setDoInput(true); checkConnection.connect(); InputStream stream = checkConnection.getInputStream(); xmlFactoryObject = XmlPullParserFactory.newInstance(); XmlPullParser myparser = xmlFactoryObject.newPullParser(); myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES , false); myparser.setInput(stream, null); getXmlStore(myparser); stream.close(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } }
mit
SRPlatin/Sponge
src/main/java/org/spongepowered/mod/mixin/event/state/MixinEventServerStarting.java
1924
/** * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.event.state; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLStateEvent; import org.spongepowered.api.Game; import org.spongepowered.api.event.state.ServerStartingEvent; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.mod.SpongeMod; import org.spongepowered.mod.mixin.Mixin; @NonnullByDefault @Mixin(FMLServerStartingEvent.class) public abstract class MixinEventServerStarting extends FMLStateEvent implements ServerStartingEvent { @Override public Game getGame() { return SpongeMod.instance.getGame(); } }
mit
yuweijun/learning-programming
design-patterns/src/main/java/headfirst/designpatterns/decorator/starbuzzWithSizes/DarkRoast.java
213
package headfirst.designpatterns.decorator.starbuzzWithSizes; public class DarkRoast extends Beverage { public DarkRoast() { description = "Dark Roast Coffee"; } public double cost() { return .99; } }
mit
ARISGames/aris-android-client
app/src/main/java/edu/uoregon/casls/aris_android/tab_controllers/ScannerViewFragment.java
2809
package edu.uoregon.casls.aris_android.tab_controllers; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.uoregon.casls.aris_android.GamePlayActivity; import edu.uoregon.casls.aris_android.R; public class ScannerViewFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_SECTION_NUMBER = "section_number"; private static final String ARG_SECTION_NAME = "section_name"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; // private OnFragmentInteractionListener mListener; public static ScannerViewFragment newInstance(String sectionName) { ScannerViewFragment fragment = new ScannerViewFragment(); Bundle args = new Bundle(); args.putString(ARG_SECTION_NAME, sectionName); fragment.setArguments(args); return fragment; } public ScannerViewFragment() { // Required empty public constructor } // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if (getArguments() != null) { // mParam1 = getArguments().getString(ARG_PARAM1); // mParam2 = getArguments().getString(ARG_PARAM2); // } // } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_scanner_view, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((GamePlayActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NAME)); // try { // mListener = (OnFragmentInteractionListener) activity; // } catch (ClassCastException e) { // throw new ClassCastException(activity.toString() // + " must implement OnFragmentInteractionListener"); // } } @Override public void onDetach() { super.onDetach(); // mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ // public interface OnFragmentInteractionListener { // // TODO: Update argument type and name // public void onFragmentInteraction(Uri uri); // } }
mit
NucleusPowered/QuickStartModuleLoader
src/test/java/uk/co/drnaylor/quickstart/tests/tests/ModuleDependenciesTests.java
4657
/* * This file is part of QuickStart Module Loader, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package uk.co.drnaylor.quickstart.tests.tests; import org.junit.Assert; import org.junit.Test; import uk.co.drnaylor.quickstart.ModuleHolder; import uk.co.drnaylor.quickstart.exceptions.NoModuleException; import uk.co.drnaylor.quickstart.exceptions.QuickStartModuleDiscoveryException; import uk.co.drnaylor.quickstart.exceptions.QuickStartModuleLoaderException; import uk.co.drnaylor.quickstart.exceptions.UndisableableModuleException; import uk.co.drnaylor.quickstart.tests.scaffolding.FakeLoaderTests; public class ModuleDependenciesTests extends FakeLoaderTests { @Test public void testDependentModulesAllLoadWhenEnabled() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException.Enabling, QuickStartModuleLoaderException.Construction { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.dependenciestest"); mc.loadModules(true); Assert.assertEquals(3, mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).size()); } @Test public void testDisablingModuleThreeOnlyDisabledModuleThree() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException, NoModuleException, UndisableableModuleException { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.dependenciestest"); mc.disableModule("modulethree"); mc.loadModules(true); Assert.assertEquals(2, mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).size()); Assert.assertFalse(mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).contains("modulethree")); } @Test public void testDisablingModuleTwoDisablesModuleThreeToo() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException, NoModuleException, UndisableableModuleException { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.dependenciestest"); mc.disableModule("moduletwo"); mc.loadModules(true); Assert.assertEquals(1, mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).size()); Assert.assertFalse(mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).contains("moduletwo")); Assert.assertFalse(mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).contains("modulethree")); } @Test(expected = QuickStartModuleLoaderException.Construction.class) public void testDisablingModuleOneDisablesModuleTwoAndThreeToo() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException, NoModuleException, UndisableableModuleException { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.dependenciestest"); mc.disableModule("moduleone"); mc.loadModules(true); } @Test(expected = QuickStartModuleDiscoveryException.class) public void testCircularDependenciesGetCaught() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException.Enabling, QuickStartModuleLoaderException.Construction, NoModuleException, UndisableableModuleException { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.circulardepstest"); mc.loadModules(true); } @Test(expected = QuickStartModuleLoaderException.Construction.class) public void testMandatoryDependenciesBeingDisabledThrowAnError() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException, NoModuleException, UndisableableModuleException { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.mandatorydepstest"); mc.disableModule("moduleone"); mc.loadModules(true); } @Test public void testDisablingSoftDepDoesNotDisableModule() throws QuickStartModuleDiscoveryException, QuickStartModuleLoaderException, NoModuleException, UndisableableModuleException { ModuleHolder mc = getContainer("uk.co.drnaylor.quickstart.tests.modules.softdepstest"); mc.disableModule("moduleone"); mc.loadModules(true); Assert.assertEquals(1, mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).size()); Assert.assertTrue(mc.getModules(ModuleHolder.ModuleStatusTristate.ENABLE).contains("moduletwo")); } @Test(expected = QuickStartModuleDiscoveryException.class) public void testIncorrectModuleDependencyCausesFailureToLoad() throws QuickStartModuleDiscoveryException { getContainer("uk.co.drnaylor.quickstart.tests.modules.missingdeptest"); } }
mit
leyyin/university
advanced-programming-methods/labs/toy-interpreter-java/src/model/statement/ForkStatement.java
679
package model.statement; public class ForkStatement extends Statement { private Statement program; public ForkStatement(Statement program) { this.program = program; } /** * Getter for property 'program'. * * @return Value for property 'program'. */ public Statement getProgram() { return program; } /** * {@inheritDoc} */ @Override public String toString() { return String.format("fork(%s)", program.toString()); } /** * {@inheritDoc} */ @Override public Statement cloneDeep() { return new ForkStatement(program.cloneDeep()); } }
mit
RaphaelBossek/dev-atlassian-jira-proman
src/main/java/org/raboss/dev/atlassian/jira/proman/ui/ProManEvaluationCriteria.java
2314
package org.raboss.dev.atlassian.jira.proman.ui; import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.jira.config.properties.APKeys; import com.atlassian.jira.web.action.JiraWebActionSupport; import com.atlassian.plugin.spring.scanner.annotation.component.Scanned; import org.raboss.dev.atlassian.jira.proman.api.rest.EvaluationCriteria; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Manage (create,copy,modify,delete) the evaluation criteria in the * UI. Evaluation criteria can be e.g. * - Alignment with Company Goals: How aligned is this project to corporate goals & objectives? * - Revenue Potential: What is the anticipated impact on revenue for this initiative. * - Technical Risk: What is the probability of overcoming the technical challenges of the project? */ @Scanned public class ProManEvaluationCriteria extends JiraWebActionSupport { static final private Logger log; static { log = LoggerFactory.getLogger(ProManEvaluationCriteria.class); } @Override public String doExecute() throws Exception { log.debug("Current action name is " + getActionName()); return SUCCESS; } //@RequiresXsrfCheck public String doCreateEvaluationCriteria() throws Exception { log.debug("doCreateEvaluationCriteria"); log.debug("parameter[evaluation_criterion_name_text_input]={}, parameter[evaluation_criterion_type_select_input]={}", getHttpRequest().getParameter("evaluation_criterion_name_text_input").toString(), getHttpRequest().getParameter("evaluation_criterion_type_select_input").toString()); return returnComplete(); } public String doEditEvaluationCriterion() throws Exception { log.debug("doEditEvaluationCriterion"); return returnComplete(); } public String doCopyEvaluationCriterion() throws Exception { log.debug("doCopyEvaluationCriterion"); return returnComplete(); } public String doDeleteEvaluationCriterion() throws Exception { log.debug("doDeleteEvaluationCriterion"); return returnComplete(); } public String getContextPath() throws Exception { return ComponentAccessor.getApplicationProperties().getString(APKeys.JIRA_BASEURL) + EvaluationCriteria.RESTCONTEXTPATH; } }
mit
CS2103JAN2017-W14-B1/main
src/main/java/seedu/tasklist/commons/core/Config.java
2603
package seedu.tasklist.commons.core; import java.util.Objects; import java.util.logging.Level; /** * Config values used by the app */ public class Config { public static final String DEFAULT_CONFIG_FILE = "config.json"; // Config values customizable through config file private String appTitle = "FlexiTask"; private Level logLevel = Level.INFO; private String userPrefsFilePath = "preferences.json"; private String taskListFilePath = "data/tasklist.xml"; private String taskListName = "MyTaskList"; public String getAppTitle() { return appTitle; } public void setAppTitle(String appTitle) { this.appTitle = appTitle; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getUserPrefsFilePath() { return userPrefsFilePath; } public void setUserPrefsFilePath(String userPrefsFilePath) { this.userPrefsFilePath = userPrefsFilePath; } public String getTaskListFilePath() { return taskListFilePath; } public void setTaskListFilePath(String taskListFilePath) { this.taskListFilePath = taskListFilePath; } public String getTaskListName() { return taskListName; } public void setTaskListName(String taskListName) { this.taskListName = taskListName; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Config)) { //this handles null as well. return false; } Config o = (Config) other; return Objects.equals(appTitle, o.appTitle) && Objects.equals(logLevel, o.logLevel) && Objects.equals(userPrefsFilePath, o.userPrefsFilePath) && Objects.equals(taskListFilePath, o.taskListFilePath) && Objects.equals(taskListName, o.taskListName); } @Override public int hashCode() { return Objects.hash(appTitle, logLevel, userPrefsFilePath, taskListFilePath, taskListName); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("App title : " + appTitle); sb.append("\nCurrent log level : " + logLevel); sb.append("\nPreference file Location : " + userPrefsFilePath); sb.append("\nLocal data file location : " + taskListFilePath); sb.append("\nTaskList name : " + taskListName); return sb.toString(); } }
mit
GuenverL/dta-formation
Java/Pizzeria/pizzeria-admin-app/src/main/java/controller/EditerPizzaController.java
1393
package controller; import java.io.IOException; import javax.inject.Inject; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import dta.pizzeria.model.*; import metier.PizzaService; @WebServlet("/pizzas/edit") public class EditerPizzaController extends HttpServlet { private static final long serialVersionUID = 1L; @Inject private PizzaService ps; private String oldCode; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Pizza pizza = this.ps.findPizza(req.getParameter("code")); this.oldCode = pizza.getCode(); req.setAttribute("pizza", pizza); RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/WEB-INF/views/pizzas/editerPizza.jsp"); disp.forward(req, resp); } /** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.ps.update(this.oldCode, new Pizza(req.getParameter("pizzaCode"), req.getParameter("pizzaName"), Double.valueOf(req.getParameter("pizzaPrice")), CategoriePizza.valueOf((req.getParameter("pizzaCat") .toUpperCase())))); resp.sendRedirect(req.getContextPath() + "/pizzas/list"); } }
mit
GluuFederation/oxAuth
Model/src/main/java/org/gluu/oxauth/model/register/RegisterRequestParam.java
14694
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.model.register; import org.apache.commons.lang.StringUtils; /** * Listed all standard parameters involved in client registration request. * * @author Yuriy Zabrovarnyy * @author Javier Rojas Blum * @version August 20, 2019 */ public enum RegisterRequestParam { /** * Array of redirect URIs values used in the Authorization Code and Implicit grant types. One of the these * registered redirect URI values must match the Scheme, Host, and Path segments of the redirect_uri parameter * value used in each Authorization Request. */ REDIRECT_URIS("redirect_uris"), /** * UMA2 : Array of The Claims Redirect URIs to which the client wishes the authorization server to direct * the requesting party's user agent after completing its interaction. * The URI MUST be absolute, MAY contain an application/x-www-form-urlencoded-formatted query parameter component * that MUST be retained when adding additional parameters, and MUST NOT contain a fragment component. * The client SHOULD pre-register its claims_redirect_uri with the authorization server, and the authorization server * SHOULD require all clients to pre-register their claims redirection endpoints. Claims redirection URIs * are different from the redirection URIs defined in [RFC6749] in that they are intended for the exclusive use * of requesting parties and not resource owners. Therefore, authorization servers MUST NOT redirect requesting parties * to pre-registered redirection URIs defined in [RFC6749] unless such URIs are also pre-registered specifically as * claims redirection URIs. If the URI is pre-registered, this URI MUST exactly match one of the pre-registered claims * redirection URIs, with the matching performed as described in Section 6.2.1 of [RFC3986] (Simple String Comparison). */ CLAIMS_REDIRECT_URIS("claims_redirect_uri"), /** * JSON array containing a list of the OAuth 2.0 response_type values that the Client is declaring that it will * restrict itself to using. If omitted, the default is that the Client will use only the code response type. */ RESPONSE_TYPES("response_types"), /** * JSON array containing a list of the OAuth 2.0 grant types that the Client is declaring that it will restrict * itself to using. */ GRANT_TYPES("grant_types"), /** * Kind of the application. The default if not specified is web. The defined values are native or web. * Web Clients using the OAuth implicit grant type must only register URLs using the https scheme as redirect_uris; * they may not use localhost as the hostname. * Native Clients must only register redirect_uris using custom URI schemes or URLs using the http: scheme with * localhost as the hostname. */ APPLICATION_TYPE("application_type"), /** * Array of e-mail addresses of people responsible for this Client. This may be used by some providers to enable a * Web user interface to modify the Client information. */ CONTACTS("contacts"), /** * Name of the Client to be presented to the user. */ CLIENT_NAME("client_name"), /** * URL that references a logo for the Client application. */ LOGO_URI("logo_uri"), /** * URL of the home page of the Client. */ CLIENT_URI("client_uri"), /** * URL that the Relying Party Client provides to the End-User to read about the how the profile data will be used. */ POLICY_URI("policy_uri"), /** * URL that the Relying Party Client provides to the End-User to read about the Relying Party's terms of service. */ TOS_URI("tos_uri"), /** * URL for the Client's JSON Web Key Set (JWK) document containing key(s) that are used for signing requests to * the OP. The JWK Set may also contain the Client's encryption keys(s) that are used by the OP to encrypt the * responses to the Client. */ JWKS_URI("jwks_uri"), /** * Client's JSON Web Key Set (JWK) document, passed by value. The semantics of the jwks parameter are the same as * the jwks_uri parameter, other than that the JWK Set is passed by value, rather than by reference. * This parameter is intended only to be used by Clients that, for some reason, are unable to use the jwks_uri * parameter, for instance, by native applications that might not have a location to host the contents of the JWK * Set. If a Client can use jwks_uri, it must not use jwks. * One significant downside of jwks is that it does not enable key rotation (which jwks_uri does, as described in * Section 10 of OpenID Connect Core 1.0). The jwks_uri and jwks parameters must not be used together. */ JWKS("jwks"), /** * URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OP. * The URL references a file with a single JSON array of redirect_uri values. */ SECTOR_IDENTIFIER_URI("sector_identifier_uri"), /** * Subject type requested for the Client ID. Valid types include pairwise and public. */ SUBJECT_TYPE("subject_type"), /** * Whether to return RPT as signed JWT */ RPT_AS_JWT("rpt_as_jwt"), /** * Whether to return access token as signed JWT */ ACCESS_TOKEN_AS_JWT("access_token_as_jwt"), /** * Algorithm used for signing of JWT */ ACCESS_TOKEN_SIGNING_ALG("access_token_signing_alg"), /** * JWS alg algorithm (JWA)0 required for the issued ID Token. */ ID_TOKEN_SIGNED_RESPONSE_ALG("id_token_signed_response_alg"), /** * JWE alg algorithm (JWA) required for encrypting the ID Token. */ ID_TOKEN_ENCRYPTED_RESPONSE_ALG("id_token_encrypted_response_alg"), /** * JWE enc algorithm (JWA) required for symmetric encryption of the ID Token. */ ID_TOKEN_ENCRYPTED_RESPONSE_ENC("id_token_encrypted_response_enc"), /** * JWS alg algorithm (JWA) required for UserInfo Responses. */ USERINFO_SIGNED_RESPONSE_ALG("userinfo_signed_response_alg"), /** * JWE alg algorithm (JWA) required for encrypting UserInfo Responses. */ USERINFO_ENCRYPTED_RESPONSE_ALG("userinfo_encrypted_response_alg"), /** * JWE enc algorithm (JWA) required for symmetric encryption of UserInfo Responses. */ USERINFO_ENCRYPTED_RESPONSE_ENC("userinfo_encrypted_response_enc"), /** * JWS alg algorithm (JWA) that must be required by the Authorization Server. */ REQUEST_OBJECT_SIGNING_ALG("request_object_signing_alg"), /** * JWS alg algorithm (JWA) that must be used for signing Request Objects sent to the OP. */ REQUEST_OBJECT_ENCRYPTION_ALG("request_object_encryption_alg"), /** * JWE enc algorithm (JWA) the RP is declaring that it may use for encrypting Request Objects sent to the OP. */ REQUEST_OBJECT_ENCRYPTION_ENC("request_object_encryption_enc"), /** * Requested authentication method for the Token Endpoint. */ TOKEN_ENDPOINT_AUTH_METHOD("token_endpoint_auth_method"), /** * JWS alg algorithm (JWA) that MUST be used for signing the JWT used to authenticate the Client at the * Token Endpoint for the private_key_jwt and client_secret_jwt authentication methods. */ TOKEN_ENDPOINT_AUTH_SIGNING_ALG("token_endpoint_auth_signing_alg"), /** * Default Maximum Authentication Age. Specifies that the End-User must be actively authenticated if the End-User * was authenticated longer ago than the specified number of seconds. The max_age request parameter overrides this * default value. */ DEFAULT_MAX_AGE("default_max_age"), /** * Boolean value specifying whether the auth_time Claim in the ID Token is required. It is required when the value * is true. The auth_time Claim request in the Request Object overrides this setting. */ REQUIRE_AUTH_TIME("require_auth_time"), /** * Default requested Authentication Context Class Reference values. Array of strings that specifies the default acr * values that the Authorization Server must use for processing requests from the Client. */ DEFAULT_ACR_VALUES("default_acr_values"), /** * URI using the https scheme that the Authorization Server can call to initiate a login at the Client. */ INITIATE_LOGIN_URI("initiate_login_uri"), /** * URL supplied by the RP to request that the user be redirected to this location after a logout has been performed, */ POST_LOGOUT_REDIRECT_URIS("post_logout_redirect_uris"), /** * RP URL that will cause the RP to log itself out when rendered in an iframe by the OP. * A sid (session ID) query parameter MAY be included by the OP to enable the RP to validate the request and * to determine which of the potentially multiple sessions is to be logged out. */ FRONT_CHANNEL_LOGOUT_URI("frontchannel_logout_uri"), /** * Boolean value specifying whether the RP requires that a sid (session ID) query parameter be included * to identify the RP session at the OP when the logout_uri is used. If omitted, the default value is false. */ FRONT_CHANNEL_LOGOUT_SESSION_REQUIRED("frontchannel_logout_session_required"), /** * RP URL that will cause the RP to log itself out when sent a Logout Token by the OP. */ BACKCHANNEL_LOGOUT_URI("backchannel_logout_uri"), /** * Boolean value specifying whether the RP requires that a sid (session ID) Claim be included in the Logout Token to identify the RP session with the OP when the backchannel_logout_uri is used. If omitted, the default value is false. */ BACKCHANNEL_LOGOUT_SESSION_REQUIRED("backchannel_logout_session_required"), /** * Array of request_uri values that are pre-registered by the Client for use at the Authorization Server. */ REQUEST_URIS("request_uris"), /** * @deprecated This param will be removed in a future version because the correct is 'scope' not 'scopes', see (rfc7591). */ SCOPES("scopes"), /** * String containing a space-separated list of claims that can be requested individually. */ CLAIMS("claims"), /** * Optional string value specifying the JWT Confirmation Method member name (e.g. tbh) that the Relying Party expects when receiving Token Bound ID Tokens. The presence of this parameter indicates that the Relying Party supports Token Binding of ID Tokens. If omitted, the default is that the Relying Party does not support Token Binding of ID Tokens. */ ID_TOKEN_TOKEN_BINDING_CNF("id_token_token_binding_cnf"), /** * string representation of the expected subject * distinguished name of the certificate, which the OAuth client will * use in mutual TLS authentication. */ TLS_CLIENT_AUTH_SUBJECT_DN("tls_client_auth_subject_dn"), /** * boolean, whether to allow spontaneous scopes for client */ ALLOW_SPONTANEOUS_SCOPES("allow_spontaneous_scopes"), /** * list of spontaneous scopes */ SPONTANEOUS_SCOPES("spontaneous_scopes"), /** * boolean property which indicates whether to run introspection script and then include claims from result into access_token as JWT */ RUN_INTROSPECTION_SCRIPT_BEFORE_ACCESS_TOKEN_CREATION_AS_JWT_AND_INCLUDE_CLAIMS("run_introspection_script_before_access_token_as_jwt_creation_and_include_claims"), /** * boolean property which indicates whether to keep client authorization after expiration */ KEEP_CLIENT_AUTHORIZATION_AFTER_EXPIRATION("keep_client_authorization_after_expiration"), /** * String containing a space-separated list of scope values. */ SCOPE("scope"), /** * Authorized JavaScript origins. */ AUTHORIZED_ORIGINS("authorized_origins"), /** * Client-specific access token expiration. Set this value to null or zero to use the default value. */ ACCESS_TOKEN_LIFETIME("access_token_lifetime"), /** * A unique identifier string (UUID) assigned by the client developer or software publisher used by * registration endpoints to identify the client software to be dynamically registered. */ SOFTWARE_ID("software_id"), /** * A version identifier string for the client software identified by "software_id". * The value of the "software_version" should change on any update to the client software identified by the same * "software_id". */ SOFTWARE_VERSION("software_version"), /** * A software statement containing client metadata values about the client software as claims. * This is a string value containing the entire signed JWT. */ SOFTWARE_STATEMENT("software_statement"), BACKCHANNEL_TOKEN_DELIVERY_MODE("backchannel_token_delivery_mode"), BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT("backchannel_client_notification_endpoint"), BACKCHANNEL_AUTHENTICATION_REQUEST_SIGNING_ALG("backchannel_authentication_request_signing_alg"), BACKCHANNEL_USER_CODE_PARAMETER("backchannel_user_code_parameter"); /** * Parameter name */ private final String name; /** * Constructor * * @param name parameter name */ private RegisterRequestParam(String name) { this.name = name; } /** * Gets parameter name. * * @return parameter name */ public String getName() { return name; } /** * Returns whether parameter is standard * * @param p_parameterName parameter name * @return whether parameter is standard */ public static boolean isStandard(String p_parameterName) { if (StringUtils.isNotBlank(p_parameterName)) { for (RegisterRequestParam t : values()) { if (t.getName().equalsIgnoreCase(p_parameterName)) { return true; } } } return false; } /** * Returns whether custom parameter is valid. * * @param p_parameterName parameter name * @return whether custom parameter is valid */ public static boolean isCustomParameterValid(String p_parameterName) { return StringUtils.isNotBlank(p_parameterName) && !isStandard(p_parameterName); } @Override public String toString() { return name; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_05_01/src/main/java/com/microsoft/azure/management/network/v2020_05_01/VirtualWanSecurityProviderType.java
1506
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_05_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for VirtualWanSecurityProviderType. */ public final class VirtualWanSecurityProviderType extends ExpandableStringEnum<VirtualWanSecurityProviderType> { /** Static value External for VirtualWanSecurityProviderType. */ public static final VirtualWanSecurityProviderType EXTERNAL = fromString("External"); /** Static value Native for VirtualWanSecurityProviderType. */ public static final VirtualWanSecurityProviderType NATIVE = fromString("Native"); /** * Creates or finds a VirtualWanSecurityProviderType from its string representation. * @param name a name to look for * @return the corresponding VirtualWanSecurityProviderType */ @JsonCreator public static VirtualWanSecurityProviderType fromString(String name) { return fromString(name, VirtualWanSecurityProviderType.class); } /** * @return known VirtualWanSecurityProviderType values */ public static Collection<VirtualWanSecurityProviderType> values() { return values(VirtualWanSecurityProviderType.class); } }
mit
highsource/bahnhof.direct
core/src/test/java/org/hisrc/bahnhofdirect/jsi/rtree/RTreeTest.java
716
package org.hisrc.bahnhofdirect.jsi.rtree; import org.junit.Assert; import org.junit.Test; import gnu.trove.procedure.TIntProcedure; import net.sf.jsi.Point; import net.sf.jsi.Rectangle; import net.sf.jsi.SpatialIndex; import net.sf.jsi.rtree.RTree; public class RTreeTest { private SpatialIndex spatialIndex = new RTree(); { spatialIndex.init(null); } @Test public void findsNearest(){ spatialIndex.add(new Rectangle(10, 10, 10, 10), 0); spatialIndex.add(new Rectangle(30, 30, 30, 30), 1); spatialIndex.nearest(new Point(21, 21), new TIntProcedure() { @Override public boolean execute(int value) { Assert.assertEquals(1, value); return true; } }, Float.MAX_VALUE); } }
mit
codeborne/play-press
src/press/RequestManager.java
2821
package press; import play.mvc.Router; import play.vfs.VirtualFile; import press.io.PressFileGlobber; /** * Manages the state of a single request to render the page */ public class RequestManager { public static final boolean RQ_TYPE_SCRIPT = true; public static final boolean RQ_TYPE_STYLE = !RQ_TYPE_SCRIPT; private boolean errorOccurred = false; private RequestHandler scriptRequestHandler = new ScriptRequestHandler(); private RequestHandler styleRequestHandler = new StyleRequestHandler(); private RequestHandler getRequestHandler(boolean rqType) { return rqType == RQ_TYPE_SCRIPT ? scriptRequestHandler : styleRequestHandler; } public String addSingleFile(boolean rqType, String fileName, String ... args) { RequestHandler handler = getRequestHandler(rqType); VirtualFile file = handler.checkFileExists(fileName); String src = null; if (performCompression()) { src = handler.getCompressedUrl(handler.getSingleFileCompressionKey(fileName)); } else { src = Router.reverse(file); } return handler.getTag(src, args); } public String addMultiFile(boolean rqType, String src, boolean packFile, String ... args) { RequestHandler handler = getRequestHandler(rqType); String baseUrl = handler.getSrcDir(); String result = ""; for (String fileName : PressFileGlobber.getResolvedFiles(src, baseUrl)) { VirtualFile file = handler.checkFileExists(fileName); handler.checkForDuplicates(fileName); if (performCompression()) { handler.add(fileName, packFile); } else { result += handler.getTag(Router.reverse(file), args); } } return result; } public String compressedTag(boolean rqType, String key, String ... args) { RequestHandler handler = getRequestHandler(rqType); if (performCompression()) { String requestKey; if (key != null) { handler.getSourceManager().requestKey = key; requestKey = key; } else requestKey = handler.closeRequest(); return handler.getTag(handler.getCompressedUrl(requestKey), args); } return ""; } public void saveFileList() { if (!performCompression()) { return; } scriptRequestHandler.saveFileList(); styleRequestHandler.saveFileList(); } public void errorOccurred() { errorOccurred = true; } private boolean performCompression() { return PluginConfig.enabled && !errorOccurred; } public static void clearCache() { ScriptRequestHandler.clearCache(); StyleRequestHandler.clearCache(); } }
mit
Azure/azure-sdk-for-java
sdk/billing/azure-resourcemanager-billing/src/main/java/com/azure/resourcemanager/billing/models/SubscriptionTransferValidationErrorCode.java
6064
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.billing.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for SubscriptionTransferValidationErrorCode. */ public final class SubscriptionTransferValidationErrorCode extends ExpandableStringEnum<SubscriptionTransferValidationErrorCode> { /** Static value BillingAccountInactive for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode BILLING_ACCOUNT_INACTIVE = fromString("BillingAccountInactive"); /** Static value CrossBillingAccountNotAllowed for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode CROSS_BILLING_ACCOUNT_NOT_ALLOWED = fromString("CrossBillingAccountNotAllowed"); /** Static value DestinationBillingProfileInactive for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode DESTINATION_BILLING_PROFILE_INACTIVE = fromString("DestinationBillingProfileInactive"); /** Static value DestinationBillingProfileNotFound for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode DESTINATION_BILLING_PROFILE_NOT_FOUND = fromString("DestinationBillingProfileNotFound"); /** Static value DestinationBillingProfilePastDue for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode DESTINATION_BILLING_PROFILE_PAST_DUE = fromString("DestinationBillingProfilePastDue"); /** Static value DestinationInvoiceSectionInactive for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode DESTINATION_INVOICE_SECTION_INACTIVE = fromString("DestinationInvoiceSectionInactive"); /** Static value DestinationInvoiceSectionNotFound for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode DESTINATION_INVOICE_SECTION_NOT_FOUND = fromString("DestinationInvoiceSectionNotFound"); /** Static value InsufficientPermissionOnDestination for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode INSUFFICIENT_PERMISSION_ON_DESTINATION = fromString("InsufficientPermissionOnDestination"); /** Static value InsufficientPermissionOnSource for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode INSUFFICIENT_PERMISSION_ON_SOURCE = fromString("InsufficientPermissionOnSource"); /** Static value InvalidDestination for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode INVALID_DESTINATION = fromString("InvalidDestination"); /** Static value InvalidSource for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode INVALID_SOURCE = fromString("InvalidSource"); /** Static value MarketplaceNotEnabledOnDestination for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode MARKETPLACE_NOT_ENABLED_ON_DESTINATION = fromString("MarketplaceNotEnabledOnDestination"); /** Static value NotAvailableForDestinationMarket for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode NOT_AVAILABLE_FOR_DESTINATION_MARKET = fromString("NotAvailableForDestinationMarket"); /** Static value ProductInactive for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode PRODUCT_INACTIVE = fromString("ProductInactive"); /** Static value ProductNotFound for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode PRODUCT_NOT_FOUND = fromString("ProductNotFound"); /** Static value ProductTypeNotSupported for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode PRODUCT_TYPE_NOT_SUPPORTED = fromString("ProductTypeNotSupported"); /** Static value SourceBillingProfilePastDue for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode SOURCE_BILLING_PROFILE_PAST_DUE = fromString("SourceBillingProfilePastDue"); /** Static value SourceInvoiceSectionInactive for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode SOURCE_INVOICE_SECTION_INACTIVE = fromString("SourceInvoiceSectionInactive"); /** Static value SubscriptionNotActive for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode SUBSCRIPTION_NOT_ACTIVE = fromString("SubscriptionNotActive"); /** Static value SubscriptionTypeNotSupported for SubscriptionTransferValidationErrorCode. */ public static final SubscriptionTransferValidationErrorCode SUBSCRIPTION_TYPE_NOT_SUPPORTED = fromString("SubscriptionTypeNotSupported"); /** * Creates or finds a SubscriptionTransferValidationErrorCode from its string representation. * * @param name a name to look for. * @return the corresponding SubscriptionTransferValidationErrorCode. */ @JsonCreator public static SubscriptionTransferValidationErrorCode fromString(String name) { return fromString(name, SubscriptionTransferValidationErrorCode.class); } /** @return known SubscriptionTransferValidationErrorCode values. */ public static Collection<SubscriptionTransferValidationErrorCode> values() { return values(SubscriptionTransferValidationErrorCode.class); } }
mit
OuZhencong/logback
logback-examples/src/main/java/chapters/appenders/mail/Marked_EMail.java
2256
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2013, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package chapters.appenders.mail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.util.StatusPrinter; /** * This application generates a number of message many of which are of LEVEL. * However, only one message bears the "NOTIFY_ADMIN" marker. * */ public class Marked_EMail { static public void main(String[] args) throws Exception { if (args.length != 1) { usage("Wrong number of arguments."); } String configFile = args[0]; LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); lc.reset(); configurator.setContext(lc); configurator.doConfigure(configFile); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); Logger logger = LoggerFactory.getLogger(Marked_EMail.class); int runLength = 100; for (int i = 1; i <= runLength; i++) { if ((i % 10) < 9) { logger.debug("This is a debug message. Message number: " + i); } else { logger.error("This is an error message. Message number: " + i); } } Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN"); logger.error(notifyAdmin, "This is a serious an error requiring the admin's attention", new Exception("Just testing")); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } static void usage(String msg) { System.err.println(msg); System.err.println("Usage: java " + Marked_EMail.class.getName() + " configFile\n" + " configFile a logback configuration file in XML format."); System.exit(1); } }
mit
despectra/github-repoview
githubrepoview/src/main/java/com/despectra/githubrepoview/fragments/ReposFragment.java
2558
package com.despectra.githubrepoview.fragments; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.View; import com.despectra.githubrepoview.R; import com.despectra.githubrepoview.SimpleDividerItemDecoration; import com.despectra.githubrepoview.viewmodel.RepoViewModel; import com.despectra.githubrepoview.viewmodel.ReposListViewModel; import com.despectra.githubrepoview.viewmodel.UserViewModel; /** * Fragment for rendering list of user repos */ public class ReposFragment extends ItemsListFragment<ReposListViewModel, RepoViewModel> { public static final String USER_ARG = "user"; private UserViewModel mRepoOwner; @Override public void onCreate(Bundle savedInstanceState) { String userJson = getArguments().getString(USER_ARG); if(userJson == null) { throw new IllegalStateException("Repos fragment must be instantiated with owner user item"); } mRepoOwner = UserViewModel.deserialize(userJson); super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle(mRepoOwner.getName()); actionBar.setSubtitle(mRepoOwner.getShortInfo()); getRecyclerView().addItemDecoration(new SimpleDividerItemDecoration(getActivity())); } @Override protected ReposListViewModel getListViewModel() { return new ReposListViewModel(getActivity(), getLoaderManager(), mRepoOwner); } @Override public void onAdapterItemClick(RepoViewModel repo, View itemView, int position) { Bundle args = new Bundle(); args.putString(BranchesFragment.OWNER_ARG, mRepoOwner.serialize()); args.putString(BranchesFragment.REPO_ARG, repo.serialize()); FragmentManager manager = getFragmentManager(); String branchesFragmentName = BranchesFragment.class.getName(); BranchesFragment fragment = (BranchesFragment) ItemsListFragment.getInstance(getActivity(), manager, branchesFragmentName, args); getFragmentManager() .beginTransaction() .replace(R.id.fragment_container, fragment, branchesFragmentName) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .addToBackStack(branchesFragmentName) .commit(); } }
mit
kimkevin/AndroidStarterKit
ask-remote-module/src/main/java/com/androidstarterkit/module/ui/adapter/RecyclerViewAdapter.java
1814
package com.androidstarterkit.module.ui.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.androidstarterkit.module.data.AndroidPlatform; import com.androidstarterkit.module.R; import com.bumptech.glide.Glide; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private Context context; private List<AndroidPlatform> platforms; public RecyclerViewAdapter(Context context, List<AndroidPlatform> platforms) { this.context = context; this.platforms = platforms; } @Override public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.layout_list_item, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(final RecyclerViewAdapter.ViewHolder holder, final int position) { AndroidPlatform platform = platforms.get(position); Glide.with(context).load(platform.getLogoUrl()).into(holder.logo); holder.name.setText(platform.getName()); holder.platformVer.setText(platform.getVerCode()); } @Override public int getItemCount() { return platforms.size(); } static class ViewHolder extends RecyclerView.ViewHolder { public ImageView logo; public TextView name; public TextView platformVer; ViewHolder(View itemView) { super(itemView); logo = (ImageView) itemView.findViewById(R.id.img); name = (TextView) itemView.findViewById(R.id.name); platformVer = (TextView) itemView.findViewById(R.id.platform_ver); } } }
mit
nwcaldwell/Java
src/models/board/JavaGame.java
4564
package models.board; import models.Pair; import models.palacefestival.Deck; import models.palacefestival.JavaPlayer; import models.palacefestival.PalaceCard; import java.util.List; public class JavaGame { /* ======================================================================== Pieces Counts Constants ======================================================================== */ private static final int THREE_SPACE_TILES_INIT_COUNT = 56; private static final int IRRIGATION_TILES_COUNT = 16; private static final int LEVEL_2_PALACES_COUNT = 6; private static final int LEVEL_4_PALACES_COUNT = 7; private static final int LEVEL_6_PALACES_COUNT = 8; private static final int LEVEL_8_PALACES_COUNT = 9; private static final int LEVEL_10_PALACES_COUNT = 10; private static final int PLAYERS_INITIAL_FAME_POINTS = 0; private static final int PLAYERS_INITIAL_DEVELOPERS_COUNT = 12; private static final int PLAYERS_INITIAL_RICE_COUNT = 3; private static final int PLAYERS_INITIAL_VILLAGE_COUNT = 2; private static final int PLAYERS_INITIAL_TWO_SPACE_COUNT = 5; private static final int PLAYERS_INITIAL_EXTRA_ACTION_COUNT = 3; private static final int PLAYERS_INITIAL_CARDS_COUNT = 3; /* ======================================================================== Instance variables ======================================================================== */ private JavaPlayer[] players; private Board board; private SharedResources sharedResources; private Deck deck; /* ======================================================================== CONSTRUCTORS ======================================================================== */ // The 'key' in the pair is the player name and the 'value' // public JavaGame(List<Pair<String,String>> playersData, String boardFile){ initPlayers(playersData); board = new Board(HexDirection.N, boardFile); sharedResources = new SharedResources( THREE_SPACE_TILES_INIT_COUNT, IRRIGATION_TILES_COUNT, LEVEL_2_PALACES_COUNT, LEVEL_4_PALACES_COUNT, LEVEL_6_PALACES_COUNT, LEVEL_8_PALACES_COUNT, LEVEL_10_PALACES_COUNT); // TODO DETERMINE HOW TO MAKE THE PLAYERS DRAW INITIAL CARDS // TODO SO THAT IT CAN BE DUPLICATED BY THE LOAD deck = new Deck(); } /* ======================================================================== Public methods ======================================================================== */ public Deck getDeck(){ return deck; } public SharedResources getSharedResources(){ return sharedResources; } public JavaPlayer[] getPlayers(){ return players; } public Board getBoard(){ return board; } public void endFestival(List<PalaceCard> discardedCards, List<JavaPlayer> playersFromFestival, int pointsEarned) { deck.discard(discardedCards); for(JavaPlayer player : playersFromFestival){ player.updateFamePoints(pointsEarned); } } public void undoFestival(List<PalaceCard> discardedCards, List<JavaPlayer> playersFromFestival, int pointsEarned) { deck.undoDiscard(discardedCards); for(JavaPlayer player : playersFromFestival){ player.updateFamePoints((-1)*pointsEarned); } } /* ======================================================================== Private methods ======================================================================== */ private void initPlayers(List<Pair<String,String>> playersData) { players = new JavaPlayer[playersData.size()]; for (int i = 0; i < playersData.size(); i++) { players[i] = new JavaPlayer( playersData.get(i).getKey(), playersData.get(i).getValue(), PLAYERS_INITIAL_FAME_POINTS, PLAYERS_INITIAL_DEVELOPERS_COUNT, PLAYERS_INITIAL_RICE_COUNT, PLAYERS_INITIAL_VILLAGE_COUNT, PLAYERS_INITIAL_TWO_SPACE_COUNT, PLAYERS_INITIAL_EXTRA_ACTION_COUNT); } } /* ======================================================================== Protected methods ======================================================================== */ }
mit
jirkae/BeerCheese
backend/beer-app/src/test/java/edu/vse/daos/SupplierDatoJpaTest.java
1267
package edu.vse.daos; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.assertThat; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import edu.vse.AbstractAppJpaTest; import edu.vse.models.SupplierEntity; public class SupplierDatoJpaTest extends AbstractAppJpaTest { @Autowired private SupplierDao supplierDao; @Test public void testFindOne() throws Exception { SupplierEntity supplierEntity = supplierDao.getOne(1); assertThat(supplierEntity, allOf( hasProperty("id", is(1)), hasProperty("name", is("YoloCorp")), hasProperty("phoneNumber", is("+420789098678")), hasProperty("deliveryTime", is(3L)) ) ); } @Test public void testFindAll() throws Exception { List<SupplierEntity> all = supplierDao.findAll(); assertThat(all, hasSize(1)); } @Test public void testDelete() throws Exception { supplierDao.delete(1); } }
mit
Coderhypo/ayanami
src/test/java/xyz/acmer/util/EncryptHelperTest.java
1530
package xyz.acmer.util; import org.junit.Test; /** * Created by hypo on 16-2-21. */ public class EncryptHelperTest { @Test public void getPassword(){ String password = "This is a Password"; for(int i = 0;i < 10;i++){ password = EncryptHelper.getPassword(password); System.out.println(i + " ### " + password); } System.out.println(); password = "This is a Password"; for(int i = 0;i < 10;i++){ password = EncryptHelper.getPassword(password); System.out.println(i + " ### " + password); } } @Test public void testMD5(){ String string = "This is a String"; StringBuffer stringBuffer = new StringBuffer(); for(int i = 0;i < 50;i++){ stringBuffer.append(string + (i % 10 == 0 ? "\n" : " ")) ; } System.out.println(stringBuffer); System.out.println(EncryptHelper.md5(string)); } @Test public void testBase64(){ String s = "Hello World"; String s1 = EncryptHelper.getBase64(s); String s2 = EncryptHelper.getFromBase64(s1); System.out.println(s); System.out.println(s1); System.out.println(s2); System.out.println(EncryptHelper.getFromBase64("I2luY2x1ZGUgPHN0ZGlvLmg+CgppbnQgb" + "WFpbigpCnsKICAgIGludCBhLGI7CiAgICBzY2FuZigiJ" + "WQgJWQiLCZhLCAmYik7CiAgICBwcmludGYoIiVkXG4iL" + "GErYik7CiAgICByZXR1cm4gMDsKfQ==")); } }
mit
mcdimus/jersey-grizzly-cdi-example
src/main/java/com/example/NewClass.java
240
package com.example; import javax.inject.Named; import javax.inject.Singleton; /** * * @author Dmitri Maksimov */ @Named @Singleton public class NewClass { @Override public String toString() { return "NewClass{" + '}'; } }
mit
amis92/clustering-demo
src/clusterer/Vector.java
2884
package clusterer; import java.util.Arrays; import java.util.List; public class Vector { private static double EPSILON = 0.000000001; private final double[] values; private final String name; public Vector(double... values) { this("un-named", values); } public Vector(String name, double... values) { this.name = name; this.values = values; } /** * calculates the euclidean distance between two vectors */ public static double euclideanDistance(Vector first, Vector second) { if (first.values.length != second.values.length) throw new IllegalArgumentException(); double sumOfSquares = 0; for (int i = 0; i < first.values.length; i++) { sumOfSquares += (first.values[i] - second.values[i]) * (first.values[i] - second.values[i]); } return Math.sqrt(sumOfSquares); } @Override public boolean equals(Object obj) { Vector other = (Vector) obj; for (int i = 0; i < values.length; i++) { if (Math.abs((values[i] - other.values[i])) > EPSILON) return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder("vector: " + name + " = ["); for (int i = 0; i < values.length; i++) { sb.append(values[i]); if (i < values.length - 1) sb.append(", "); } return sb.append("]").toString(); } public int getNearestPointIndex(List<Vector> points) { if (points == null || points.size() == 0) throw new IllegalArgumentException(); int nearestVectorIndex = 0; double minDistance = euclideanDistance(this, points.get(0)); for (int i = 1; i < points.size(); i++) { double distance = euclideanDistance(this, points.get(i)); if (distance < minDistance) { nearestVectorIndex = i; minDistance = distance; } } return nearestVectorIndex; } public static void main(String[] args) { Vector first = new Vector(1, 2, 3, 4, 5); Vector second = new Vector(6, 7, 8, 9, 10); System.out.println(Vector.euclideanDistance(first, second)); System.out.println(Vector.calculateCenter(first, second)); } public static Vector calculateCenter(Vector... vectors) { if (vectors == null || vectors.length == 0) throw new IllegalArgumentException(); Vector center = new Vector(Arrays.copyOf(vectors[0].values, vectors[0].values.length)); for (int i = 1; i < vectors.length; i++) { if (vectors[i].values.length != center.values.length) throw new IllegalArgumentException("vector " + i + "'s dimension is not compatible with first vector!"); for (int j = 0; j < center.values.length; j++) { center.values[j] += vectors[i].values[j]; } } for (int i = 0; i < center.values.length; i++) { center.values[i] = center.values[i] / vectors.length; } return center; } public int getDimensionCount() { return values.length; } public double getDimension(int dimIndex) { return values[dimIndex]; } }
mit
jklingsporn/vertx-jooq
vertx-jooq-generate/src/test/java/io/github/jklingsporn/vertx/jooq/generate/ReactiveMysqlDatabaseClientProvider.java
1541
package io.github.jklingsporn.vertx.jooq.generate; import io.vertx.core.Vertx; import io.vertx.mysqlclient.MySQLConnectOptions; import io.vertx.mysqlclient.MySQLPool; import io.vertx.sqlclient.PoolOptions; import io.vertx.sqlclient.SqlClient; /** * Created by jensklingsporn on 15.02.18. */ public class ReactiveMysqlDatabaseClientProvider { private static ReactiveMysqlDatabaseClientProvider INSTANCE; public static ReactiveMysqlDatabaseClientProvider getInstance() { return INSTANCE == null ? INSTANCE = new ReactiveMysqlDatabaseClientProvider() : INSTANCE; } private final Vertx vertx; private final MySQLPool pgClient; private final io.vertx.reactivex.sqlclient.SqlClient rxPgClient; private ReactiveMysqlDatabaseClientProvider() { this.vertx = Vertx.vertx(); this.pgClient = MySQLPool.pool(vertx, getOptions(), new PoolOptions()); this.rxPgClient = new io.vertx.reactivex.sqlclient.Pool(pgClient); } public SqlClient getClient() { return pgClient; } private MySQLConnectOptions getOptions() { return new MySQLConnectOptions() .setHost("127.0.0.1") .setPort(3306) .setUser(Credentials.MYSQL.getUser()) .setDatabase("vertx") .setPassword(Credentials.MYSQL.getPassword()) ; } public io.vertx.reactivex.sqlclient.SqlClient rxGetClient() { return rxPgClient; } public Vertx getVertx() { return vertx; } }
mit
howma03/sporticus
workspace/src/main/java/com/sporticus/web/controllers/ControllerPublic.java
339
package com.sporticus.web.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by mark on 11/02/2017. */ @Controller public class ControllerPublic { @RequestMapping("/") public String errorHandler() { return "app/index.html"; } }
mit
dot-cat/creative_assistant_android
app/src/main/java/space/dotcat/assistant/screen/roomDetail/thingsHolder/DimmableLightHolder.java
1140
package space.dotcat.assistant.screen.roomDetail.thingsHolder; import android.view.View; import android.widget.SeekBar; import butterknife.BindView; import space.dotcat.assistant.R; import space.dotcat.assistant.content.DimmableLamp; import space.dotcat.assistant.content.Lamp; import space.dotcat.assistant.screen.roomDetail.RoomDetailsAdapter; public class DimmableLightHolder extends LightHolder { @BindView(R.id.sb_light_brightness) public SeekBar mBrightnessLevel; public DimmableLightHolder(View itemView, RoomDetailsAdapter.LampSwitchClickListener switchStateListener, RoomDetailsAdapter.BrightnessLevelListener brightnessLevelListener) { super(itemView, switchStateListener); mBrightnessLevel.setOnSeekBarChangeListener(brightnessLevelListener); } @Override public void bind(Lamp colorTemperatureLamp) { super.bind(colorTemperatureLamp); DimmableLamp dimmableLamp = (DimmableLamp) colorTemperatureLamp; mBrightnessLevel.setTag(getAdapterPosition()); mBrightnessLevel.setProgress(dimmableLamp.getBrightness()); } }
mit
Sergiany/kungfood
src/main/java/br/com/kungFood/entity/UsuarioEntity.java
1129
package br.com.kungFood.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; @Table(name="tb_funcionario") @Entity @NamedQuery(name = "UsuarioEntity.findUser", query= "SELECT u FROM UsuarioEntity u WHERE u.usuario = :usuario AND u.senha = :senha") public class UsuarioEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name="id_funcionario") private String codigo; @Column(name="ds_login_funcionario") private String usuario; @Column(name="ds_senha_funcionario") private String senha; public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } }
mit
carml/carml
carml-model/src/main/java/com/taxonic/carml/model/impl/CarmlGraphMap.java
1151
package com.taxonic.carml.model.impl; import com.google.common.collect.ImmutableSet; import com.taxonic.carml.model.GraphMap; import com.taxonic.carml.model.Resource; import com.taxonic.carml.vocab.Rdf; import java.util.Set; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; import org.apache.commons.lang3.builder.MultilineRecursiveToStringStyle; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.eclipse.rdf4j.model.util.ModelBuilder; import org.eclipse.rdf4j.model.vocabulary.RDF; @SuperBuilder @NoArgsConstructor public class CarmlGraphMap extends CarmlTermMap implements GraphMap { @Override public String toString() { return new ReflectionToStringBuilder(this, new MultilineRecursiveToStringStyle()).toString(); } @Override public Set<Resource> getReferencedResources() { return ImmutableSet.<Resource>builder() .addAll(getReferencedResourcesBase()) .build(); } @Override public void addTriples(ModelBuilder modelBuilder) { modelBuilder.subject(getAsResource()) .add(RDF.TYPE, Rdf.Rr.GraphMap); addTriplesBase(modelBuilder); } }
mit
madumlao/oxAuth
Model/src/main/java/org/xdi/oxauth/model/crypto/Certificate.java
3844
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.model.crypto; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPublicKey; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.xdi.oxauth.model.crypto.signature.ECDSAPublicKey; import org.xdi.oxauth.model.crypto.signature.RSAPublicKey; import org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm; import org.xdi.oxauth.model.util.StringUtils; import java.io.IOException; import java.io.StringWriter; import java.security.cert.X509Certificate; import java.util.Arrays; /** * @author Javier Rojas Blum * @version June 29, 2016 */ public class Certificate { private SignatureAlgorithm signatureAlgorithm; private X509Certificate x509Certificate; public Certificate(SignatureAlgorithm signatureAlgorithm, X509Certificate x509Certificate) { this.signatureAlgorithm = signatureAlgorithm; this.x509Certificate = x509Certificate; } public PublicKey getPublicKey() { PublicKey publicKey = null; if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCRSAPublicKey) { BCRSAPublicKey jcersaPublicKey = (BCRSAPublicKey) x509Certificate.getPublicKey(); publicKey = new RSAPublicKey(jcersaPublicKey.getModulus(), jcersaPublicKey.getPublicExponent()); } else if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCECPublicKey) { BCECPublicKey jceecPublicKey = (BCECPublicKey) x509Certificate.getPublicKey(); publicKey = new ECDSAPublicKey(signatureAlgorithm, jceecPublicKey.getQ().getX().toBigInteger(), jceecPublicKey.getQ().getY().toBigInteger()); } return publicKey; } public RSAPublicKey getRsaPublicKey() { RSAPublicKey rsaPublicKey = null; if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCRSAPublicKey) { BCRSAPublicKey publicKey = (BCRSAPublicKey) x509Certificate.getPublicKey(); rsaPublicKey = new RSAPublicKey(publicKey.getModulus(), publicKey.getPublicExponent()); } return rsaPublicKey; } public ECDSAPublicKey getEcdsaPublicKey() { ECDSAPublicKey ecdsaPublicKey = null; if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCECPublicKey) { BCECPublicKey publicKey = (BCECPublicKey) x509Certificate.getPublicKey(); ecdsaPublicKey = new ECDSAPublicKey(signatureAlgorithm, publicKey.getQ().getX().toBigInteger(), publicKey.getQ().getY().toBigInteger()); } return ecdsaPublicKey; } public JSONArray toJSONArray() throws JSONException { String cert = toString(); cert = cert.replace("\n", ""); cert = cert.replace("-----BEGIN CERTIFICATE-----", ""); cert = cert.replace("-----END CERTIFICATE-----", ""); return new JSONArray(Arrays.asList(cert)); } @Override public String toString() { try { StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter); try { pemWriter.writeObject(x509Certificate); pemWriter.flush(); return stringWriter.toString(); } finally { pemWriter.close(); } } catch (IOException e) { return StringUtils.EMPTY_STRING; } catch (Exception e) { return StringUtils.EMPTY_STRING; } } }
mit
SCNya/otus-java-2017-04-Alexeenko
L8-And-a-Half/src/main/java/com/otus/alexeenko/l8ah/services/custom/builders/spi/InsertQueryBuilder.java
230
package com.otus.alexeenko.l8ah.services.custom.builders.spi; /** * Created by Vsevolod on 17/06/2017. */ public interface InsertQueryBuilder extends QueryBuilder { InsertQueryBuilder addValue(String name, String value); }
mit
rafafor24/Iteracion_2
src/vos/Consulta1y2.java
951
package vos; import org.codehaus.jackson.annotate.JsonProperty; public class Consulta1y2 { @JsonProperty(value="fecha1") private String fecha1; @JsonProperty(value="fecha2") private String fecha2; @JsonProperty(value="representante") private String representante; public Consulta1y2(@JsonProperty(value="fecha1")String fecha1, @JsonProperty(value="fecha2")String fecha2, @JsonProperty(value="representante")String representante) { this.fecha1=fecha1; this.fecha2=fecha2; this.representante=representante; } public String getFecha1() { return fecha1; } public void setFecha1(String fecha1) { this.fecha1 = fecha1; } public String getFecha2() { return fecha2; } public void setFecha2(String fecha2) { this.fecha2 = fecha2; } public String getRepresentante() { return representante; } public void setRepresentante(String representante) { this.representante = representante; } }
mit
cazzar/JukeboxReloaded
oldsrc/java/net/cazzar/mods/jukeboxreloaded/lib/util/Colours.java
1524
/* * The MIT License (MIT) * * Copyright (c) 2014 Cayde Dixon * * 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 net.cazzar.mods.jukeboxreloaded.lib.util; public class Colours { public static final String PURE_WHITE = "ffffff"; /* Text colour related constants */ public static final String TEXT_COLOUR_PREFIX_YELLOW = "\u00a7e"; public static final String TEXT_COLOUR_PREFIX_GRAY = "\u00a77"; public static final String TEXT_COLOUR_PREFIX_WHITE = "\u00a7f"; }
mit
the-blue-alliance/the-blue-alliance-android
android/src/main/java/com/thebluealliance/androidclient/auth/AuthModule.java
1873
package com.thebluealliance.androidclient.auth; import android.content.Context; import com.google.firebase.auth.FirebaseAuth; import com.thebluealliance.androidclient.TbaLogger; import com.thebluealliance.androidclient.accounts.AccountController; import com.thebluealliance.androidclient.accounts.AccountModule; import com.thebluealliance.androidclient.auth.firebase.FirebaseAuthProvider; import com.thebluealliance.androidclient.auth.google.GoogleAuthProvider; import javax.annotation.Nullable; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import dagger.hilt.InstallIn; import dagger.hilt.android.qualifiers.ApplicationContext; import dagger.hilt.components.SingletonComponent; @InstallIn(SingletonComponent.class) @Module(includes = AccountModule.class) public class AuthModule { @Provides @Singleton @Nullable public FirebaseAuth provideFirebaseAuth() { try { return FirebaseAuth.getInstance(); } catch (IllegalStateException ex) { /* When there is no google-secrets.json file found, the library throws an exception * here which causes insta-crashes for us. Silently recover here... */ TbaLogger.e("Unable to find google-secrets.json, disabling login"); return null; } } @Provides public GoogleAuthProvider provideGoogleAuthProvider(@ApplicationContext Context context, AccountController accountController) { return new GoogleAuthProvider(context, accountController); } @Provides @Named("firebase_auth") public AuthProvider provideFirebaseAuthProvider(@Nullable FirebaseAuth firebaseAuth, GoogleAuthProvider googleAuthProvider) { return new FirebaseAuthProvider(firebaseAuth, googleAuthProvider); } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/ApplicationGatewaySslCipherSuite.java
7994
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_11_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for ApplicationGatewaySslCipherSuite. */ public final class ApplicationGatewaySslCipherSuite extends ExpandableStringEnum<ApplicationGatewaySslCipherSuite> { /** Static value TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = fromString("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"); /** Static value TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = fromString("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"); /** Static value TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = fromString("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"); /** Static value TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = fromString("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"); /** Static value TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = fromString("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"); /** Static value TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = fromString("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"); /** Static value TLS_DHE_RSA_WITH_AES_256_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_RSA_WITH_AES_256_CBC_SHA = fromString("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"); /** Static value TLS_DHE_RSA_WITH_AES_128_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_RSA_WITH_AES_128_CBC_SHA = fromString("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"); /** Static value TLS_RSA_WITH_AES_256_GCM_SHA384 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_AES_256_GCM_SHA384 = fromString("TLS_RSA_WITH_AES_256_GCM_SHA384"); /** Static value TLS_RSA_WITH_AES_128_GCM_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_AES_128_GCM_SHA256 = fromString("TLS_RSA_WITH_AES_128_GCM_SHA256"); /** Static value TLS_RSA_WITH_AES_256_CBC_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_AES_256_CBC_SHA256 = fromString("TLS_RSA_WITH_AES_256_CBC_SHA256"); /** Static value TLS_RSA_WITH_AES_128_CBC_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_AES_128_CBC_SHA256 = fromString("TLS_RSA_WITH_AES_128_CBC_SHA256"); /** Static value TLS_RSA_WITH_AES_256_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_AES_256_CBC_SHA = fromString("TLS_RSA_WITH_AES_256_CBC_SHA"); /** Static value TLS_RSA_WITH_AES_128_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_AES_128_CBC_SHA = fromString("TLS_RSA_WITH_AES_128_CBC_SHA"); /** Static value TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = fromString("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"); /** Static value TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = fromString("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); /** Static value TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = fromString("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"); /** Static value TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = fromString("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"); /** Static value TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = fromString("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"); /** Static value TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = fromString("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"); /** Static value TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = fromString("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"); /** Static value TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = fromString("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"); /** Static value TLS_DHE_DSS_WITH_AES_256_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_DSS_WITH_AES_256_CBC_SHA = fromString("TLS_DHE_DSS_WITH_AES_256_CBC_SHA"); /** Static value TLS_DHE_DSS_WITH_AES_128_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_DSS_WITH_AES_128_CBC_SHA = fromString("TLS_DHE_DSS_WITH_AES_128_CBC_SHA"); /** Static value TLS_RSA_WITH_3DES_EDE_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_RSA_WITH_3DES_EDE_CBC_SHA = fromString("TLS_RSA_WITH_3DES_EDE_CBC_SHA"); /** Static value TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = fromString("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"); /** Static value TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = fromString("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); /** Static value TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 for ApplicationGatewaySslCipherSuite. */ public static final ApplicationGatewaySslCipherSuite TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = fromString("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"); /** * Creates or finds a ApplicationGatewaySslCipherSuite from its string representation. * @param name a name to look for * @return the corresponding ApplicationGatewaySslCipherSuite */ @JsonCreator public static ApplicationGatewaySslCipherSuite fromString(String name) { return fromString(name, ApplicationGatewaySslCipherSuite.class); } /** * @return known ApplicationGatewaySslCipherSuite values */ public static Collection<ApplicationGatewaySslCipherSuite> values() { return values(ApplicationGatewaySslCipherSuite.class); } }
mit